@lks347/dsh-oauth 0.0.0-stage → 1.0.2
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.en.md +155 -0
- package/README.md +101 -2
- package/app.js +1045 -0
- package/auth.html +80 -0
- package/client.js +31 -0
- package/cordis.patch.yml +4 -0
- package/docs/CONNECTIONS.md +77 -0
- package/docs/LIVE-VALIDATION-1.0.1.md +100 -0
- package/docs/RELEASE-1.0.1.md +48 -0
- package/docs/RELEASE-1.0.2.md +8 -0
- package/docs/VALIDATION.md +59 -0
- package/docs/evidence/live-1.0.1.json +135 -0
- package/docs/evidence/release-1.0.1.json +38 -0
- package/index.html +43 -0
- package/package.json +64 -4
- package/providers.js +73 -0
- package/scripts/check-upstreams.mjs +27 -0
- package/scripts/link-peers.js +38 -0
- package/scripts/verify-browser.mjs +297 -0
- package/scripts/verify-host.mjs +431 -0
- package/scripts/verify-live.mjs +268 -0
- package/scripts/verify-package.mjs +168 -0
- package/scripts/verify-persistence.mjs +307 -0
- package/scripts/verify-subscriptions-ui.mjs +321 -0
- package/src/account.js +85 -0
- package/src/account.test.js +52 -0
- package/src/authorization.js +199 -0
- package/src/authorization.test.js +332 -0
- package/src/catalog.js +180 -0
- package/src/catalog.test.js +146 -0
- package/src/chat-recovery.js +110 -0
- package/src/chat-recovery.test.js +261 -0
- package/src/connection-runtime.js +129 -0
- package/src/connection-runtime.test.js +244 -0
- package/src/connections.js +70 -0
- package/src/grants.js +104 -0
- package/src/grants.test.js +340 -0
- package/src/index.js +676 -0
- package/src/local-imports.js +263 -0
- package/src/local-imports.test.js +201 -0
- package/src/media.js +152 -0
- package/src/models.js +610 -0
- package/src/models.test.js +503 -0
- package/src/profile-store.js +51 -0
- package/src/pulls.js +100 -0
- package/src/pulls.test.js +156 -0
- package/src/qwen.js +141 -0
- package/src/qwen.test.js +35 -0
- package/src/request-errors.js +50 -0
- package/src/request-errors.test.js +131 -0
- package/src/routes.js +47 -0
- package/src/routes.test.js +136 -0
- package/src/subscription-models.test.js +160 -0
- package/src/usage/aggregators.js +292 -0
- package/src/usage/aggregators.test.js +316 -0
- package/src/usage/core.js +68 -0
- package/src/usage/index.js +93 -0
- package/src/usage/official.js +339 -0
- package/src/usage/official.test.js +273 -0
- package/src/usage/service.test.js +89 -0
- package/src/xai-browser.js +272 -0
- package/src/xai-browser.test.js +256 -0
- package/src/xai-login.js +121 -0
- package/src/xai-login.test.js +259 -0
- package/styles.css +364 -0
- package/theme.js +118 -0
- package/upstreams.json +10 -0
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { restoreRoute, writeRoute } from "./routes.js";
|
|
4
|
+
|
|
5
|
+
/** A revision-checked settings fake keeps tests at the public settings seam. */
|
|
6
|
+
function memorySettings(user = {}, mounted = true) {
|
|
7
|
+
const state = { user: structuredClone(user), revision: 1 };
|
|
8
|
+
const calls = [];
|
|
9
|
+
return {
|
|
10
|
+
state, calls,
|
|
11
|
+
describe() { return mounted ? [{ ns: "llm-pi-ai", user: structuredClone(state.user), revision: state.revision }] : []; },
|
|
12
|
+
async mutate(namespace, operations, revision) {
|
|
13
|
+
assert.equal(namespace, "llm-pi-ai");
|
|
14
|
+
assert.equal(revision, state.revision);
|
|
15
|
+
calls.push(structuredClone(operations));
|
|
16
|
+
for (const operation of operations) {
|
|
17
|
+
let parent = state.user;
|
|
18
|
+
for (const key of operation.path.slice(0, -1)) parent = parent[key] ??= {};
|
|
19
|
+
const leaf = operation.path.at(-1);
|
|
20
|
+
if (operation.op === "set") parent[leaf] = structuredClone(operation.value);
|
|
21
|
+
else if (operation.op === "unset") delete parent[leaf];
|
|
22
|
+
else assert.fail(`unexpected operation: ${operation.op}`);
|
|
23
|
+
}
|
|
24
|
+
state.revision += 1;
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const models = [{ id: "pulled-chat", name: "Pulled Chat" }];
|
|
30
|
+
const qwenPlan = (list = models) => ({ displayName: "通义千问", api: "openai-completions", baseURL: "https://portal.qwen.ai/v1", apiKeyEnv: "QWEN_OAUTH_ACCESS", defaultInput: ["text"], models: list });
|
|
31
|
+
|
|
32
|
+
test("restoring a normal pull returns the previous model list and keeps unrelated provider settings", async () => {
|
|
33
|
+
const original = { providers: { anthropic: { models: [{ id: "prior-chat" }], baseURL: "https://prior.example.test", custom: "keep" } } };
|
|
34
|
+
const settings = memorySettings(original);
|
|
35
|
+
const route = await writeRoute(settings, "anthropic", models);
|
|
36
|
+
assert.deepEqual(settings.state.user.providers.anthropic.models, models);
|
|
37
|
+
assert.deepEqual(settings.calls[0].map((operation) => operation.path), [["providers", "anthropic", "models"]]);
|
|
38
|
+
await restoreRoute(settings, route);
|
|
39
|
+
assert.deepEqual(settings.state.user, original);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("repeated normal pulls retain the original model list as the restoration target", async () => {
|
|
43
|
+
const original = { providers: { xai: { models: [{ id: "original" }], custom: "keep" } } };
|
|
44
|
+
const settings = memorySettings(original);
|
|
45
|
+
const first = await writeRoute(settings, "xai", models);
|
|
46
|
+
const second = await writeRoute(settings, "xai", [{ id: "second-pull" }], undefined, first);
|
|
47
|
+
await restoreRoute(settings, second);
|
|
48
|
+
assert.deepEqual(settings.state.user, original);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test("a failed second pull rolls back to the first pull while expiry still restores the original models", async () => {
|
|
52
|
+
const original = { providers: { xai: { models: [{ id: "original" }] } } };
|
|
53
|
+
const settings = memorySettings(original);
|
|
54
|
+
const first = await writeRoute(settings, "xai", models);
|
|
55
|
+
const second = await writeRoute(settings, "xai", [{ id: "second-pull" }], undefined, first);
|
|
56
|
+
await restoreRoute(settings, second.rollback);
|
|
57
|
+
assert.deepEqual(settings.state.user.providers.xai.models, models);
|
|
58
|
+
await restoreRoute(settings, first);
|
|
59
|
+
assert.deepEqual(settings.state.user, original);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("a plugin-created Qwen route is removed after repeated pulls while other providers remain", async () => {
|
|
63
|
+
const original = { providers: { unrelated: { models: [{ id: "keep" }] } } };
|
|
64
|
+
const settings = memorySettings(original);
|
|
65
|
+
const first = await writeRoute(settings, "qwen", models, qwenPlan());
|
|
66
|
+
assert.deepEqual(first.edits.map((edit) => edit.path), [["providers", "qwen"]]);
|
|
67
|
+
const replacement = [{ id: "qwen-second" }];
|
|
68
|
+
const second = await writeRoute(settings, "qwen", replacement, qwenPlan(replacement), first);
|
|
69
|
+
assert.deepEqual(second.edits.map((edit) => edit.path), [["providers", "qwen"]]);
|
|
70
|
+
assert.deepEqual(settings.state.user.providers.qwen.models, replacement);
|
|
71
|
+
await restoreRoute(settings, second);
|
|
72
|
+
assert.deepEqual(settings.state.user, original);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test("an existing Qwen provider regains each previous setting when the pull expires", async () => {
|
|
76
|
+
const original = { providers: { qwen: { displayName: "Existing Qwen", api: "openai-completions", baseURL: "https://prior.example.test/v1", models: [{ id: "old" }], custom: "keep" } } };
|
|
77
|
+
const settings = memorySettings(original);
|
|
78
|
+
const route = await writeRoute(settings, "qwen", models, qwenPlan());
|
|
79
|
+
await restoreRoute(settings, route);
|
|
80
|
+
assert.deepEqual(settings.state.user, original);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test("cleanup preserves model lists the user edits after pulling", async () => {
|
|
84
|
+
const settings = memorySettings({ providers: { anthropic: { models: [{ id: "original" }], custom: "keep" } } });
|
|
85
|
+
const route = await writeRoute(settings, "anthropic", models);
|
|
86
|
+
settings.state.user.providers.anthropic.models = [{ id: "user-edited" }];
|
|
87
|
+
const edited = structuredClone(settings.state.user);
|
|
88
|
+
await restoreRoute(settings, route);
|
|
89
|
+
assert.deepEqual(settings.state.user, edited);
|
|
90
|
+
assert.equal(settings.calls.length, 1);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test("a user edit between two pulls becomes the next pull's restoration target", async () => {
|
|
94
|
+
const settings = memorySettings({ providers: { xai: { models: [{ id: "original" }] } } });
|
|
95
|
+
const first = await writeRoute(settings, "xai", models);
|
|
96
|
+
settings.state.user.providers.xai.models = [{ id: "user-edited" }];
|
|
97
|
+
const edited = structuredClone(settings.state.user);
|
|
98
|
+
const second = await writeRoute(settings, "xai", [{ id: "later-pull" }], undefined, first);
|
|
99
|
+
await restoreRoute(settings, second);
|
|
100
|
+
assert.deepEqual(settings.state.user, edited);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test("cleanup preserves later user changes to a plugin-created Qwen provider", async () => {
|
|
104
|
+
const settings = memorySettings({ providers: {} });
|
|
105
|
+
const route = await writeRoute(settings, "qwen", models, qwenPlan());
|
|
106
|
+
settings.state.user.providers.qwen.baseURL = "https://user.example.test/v1";
|
|
107
|
+
settings.state.user.providers.qwen.userOption = "keep";
|
|
108
|
+
const edited = structuredClone(settings.state.user);
|
|
109
|
+
await restoreRoute(settings, route);
|
|
110
|
+
assert.deepEqual(settings.state.user, edited);
|
|
111
|
+
assert.equal(settings.calls.length, 1);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("a pull without prior models removes only the models override during cleanup", async () => {
|
|
115
|
+
const original = { providers: { xai: { custom: "keep" } } };
|
|
116
|
+
const settings = memorySettings(original);
|
|
117
|
+
const route = await writeRoute(settings, "xai", models);
|
|
118
|
+
await restoreRoute(settings, route);
|
|
119
|
+
assert.deepEqual(settings.state.user, original);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test("missing settings namespaces reject writes and deferred cleanup instead of claiming success", async () => {
|
|
123
|
+
const settings = memorySettings({}, false);
|
|
124
|
+
await assert.rejects(writeRoute(settings, "xai", models), /设置尚未挂载/);
|
|
125
|
+
await assert.rejects(restoreRoute(settings, { edits: [{ path: ["providers", "xai", "models"], written: models }] }), /设置尚未挂载/);
|
|
126
|
+
assert.equal(settings.calls.length, 0);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
test("legacy pulls without ownership data do not authorize removing provider configuration", async () => {
|
|
130
|
+
const original = { providers: { xai: { models, custom: "keep" } } };
|
|
131
|
+
const settings = memorySettings(original);
|
|
132
|
+
await restoreRoute(settings, undefined);
|
|
133
|
+
await restoreRoute(settings, { models });
|
|
134
|
+
assert.deepEqual(settings.state.user, original);
|
|
135
|
+
assert.equal(settings.calls.length, 0);
|
|
136
|
+
});
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { builtinModels } from '@earendil-works/pi-ai/providers/all';
|
|
4
|
+
import { fetchAccountModels, modelListRequest, parseModelList, reasoningEffortsFrom, modelCompatFrom } from './models.js';
|
|
5
|
+
import { aggregatorUsageIds } from './usage/aggregators.js';
|
|
6
|
+
import { getProviderDefinition } from './catalog.js';
|
|
7
|
+
|
|
8
|
+
test('all nine aggregate catalogs retain capability metadata and explicit provenance', async t => {
|
|
9
|
+
const requests = [];
|
|
10
|
+
t.mock.method(globalThis, 'fetch', async (url, options) => {
|
|
11
|
+
requests.push({ url: String(url), options });
|
|
12
|
+
return new Response(JSON.stringify({ data: [{ id: 'vendor/agent-model', name: 'Agent Model', context_length: 200000, top_provider: { max_completion_tokens: 16384 }, architecture: { input_modalities: ['text', 'image', 'video'], output_modalities: ['text'] }, supported_parameters: ['tools', 'reasoning'], supported_reasoning_levels: ['low', 'high'] }] }));
|
|
13
|
+
});
|
|
14
|
+
for (const id of aggregatorUsageIds) {
|
|
15
|
+
const metadata = { access: 'fixture-model-key', organizationId: 'org_123', workspaceId: 'workspace_123' };
|
|
16
|
+
const definition = getProviderDefinition(id, metadata);
|
|
17
|
+
const [row] = await fetchAccountModels(id, metadata);
|
|
18
|
+
assert.equal(row.source, definition.modelSource, id);
|
|
19
|
+
assert.equal(row.entitlement, definition.entitlement, id);
|
|
20
|
+
assert.equal(row.contextWindow, 200000);
|
|
21
|
+
assert.equal(row.maxTokens, 16384);
|
|
22
|
+
assert.deepEqual(row.input, ['text', 'image']);
|
|
23
|
+
assert.deepEqual(row.output, ['text']);
|
|
24
|
+
assert.deepEqual(row.reasoningEfforts, { low: 'low', high: 'high' });
|
|
25
|
+
assert.equal(row.tools, true);
|
|
26
|
+
assert.equal(row.role, 'chat');
|
|
27
|
+
const request = requests.at(-1);
|
|
28
|
+
assert.equal(request.url, definition.modelsURL);
|
|
29
|
+
assert.equal(request.options.redirect, 'error');
|
|
30
|
+
assert.equal(new Headers(request.options.headers).get('authorization'), 'Bearer fixture-model-key');
|
|
31
|
+
}
|
|
32
|
+
assert.equal(requests.length, 9);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test('NanoGPT detailed flags preserve vision and reasoning without inventing effort levels', () => {
|
|
36
|
+
const [row] = parseModelList({ data: [{ id: 'vendor/model', description: 'Supports video input and speech-oriented tasks', context_length: 1000000, max_output_tokens: 128000, capabilities: { vision: true, video_input: true, reasoning: true, tool_calling: true, structured_output: true } }] }, 'nanogpt');
|
|
37
|
+
assert.equal(row.role, 'chat');
|
|
38
|
+
assert.deepEqual(row.input, ['text', 'image']);
|
|
39
|
+
assert.equal(row.reasoning, true);
|
|
40
|
+
assert.equal(row.reasoningEfforts, undefined);
|
|
41
|
+
assert.equal(row.tools, true);
|
|
42
|
+
assert.equal(row.output, undefined);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('explicit output modality distinguishes Poe community media from video-understanding chat', () => {
|
|
46
|
+
const rows = parseModelList({ data: [
|
|
47
|
+
{ id: 'community-picture-bot', architecture: { input_modalities: ['text'], output_modalities: ['image'] } },
|
|
48
|
+
{ id: 'community-animation', architecture: { output_modalities: ['video'] } },
|
|
49
|
+
{ id: 'community-voice', architecture: { output_modalities: ['audio'] } },
|
|
50
|
+
{ id: 'video-understanding', name: 'Video Understanding', architecture: { modality: 'text,image,video->text' } },
|
|
51
|
+
] }, 'poe');
|
|
52
|
+
assert.deepEqual(rows.map(row => [row.id, row.role]), [['community-picture-bot', 'image'], ['community-animation', 'video'], ['video-understanding', 'chat']]);
|
|
53
|
+
assert.deepEqual(rows[0].output, ['image']);
|
|
54
|
+
assert.deepEqual(rows[1].output, ['video']);
|
|
55
|
+
assert.deepEqual(rows[2].input, ['text', 'image']);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test('generic minimal catalog does not advertise missing tools, reasoning, or modalities', () => {
|
|
59
|
+
const [row] = parseModelList({ data: [{ id: 'hf:vendor/model' }] }, 'synthetic');
|
|
60
|
+
assert.equal(row.tools, undefined);
|
|
61
|
+
assert.equal(row.reasoning, undefined);
|
|
62
|
+
assert.equal(row.reasoningEfforts, undefined);
|
|
63
|
+
assert.equal(row.input, undefined);
|
|
64
|
+
assert.equal(row.output, undefined);
|
|
65
|
+
assert.equal(row.contextWindow, undefined);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test('explicit false flags remain false and are not overridden by a generic feature name', () => {
|
|
69
|
+
const [row] = parseModelList({ data: [{ id: 'plain', capabilities: { reasoning: false, tool_calling: false, vision: false }, supported_parameters: ['tools'] }] });
|
|
70
|
+
assert.equal(row.tools, false);
|
|
71
|
+
assert.equal(row.reasoning, false);
|
|
72
|
+
assert.equal(row.reasoningEfforts, false);
|
|
73
|
+
assert.deepEqual(row.input, ['text']);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('installed reasoning maps preserve supported wire values and omit null levels', () => {
|
|
77
|
+
const [row] = parseModelList([{ id: 'installed', reasoning: true, thinkingLevelMap: { off: null, minimal: null, low: 'low', medium: 'medium', high: 'high', xhigh: null, max: 'max' } }]);
|
|
78
|
+
assert.equal(row.reasoning, true);
|
|
79
|
+
assert.deepEqual(row.reasoningEfforts, { low: 'low', medium: 'medium', high: 'high', max: 'max' });
|
|
80
|
+
assert.equal(reasoningEffortsFrom({ supported_reasoning_levels: ['constructor', '__proto__', 'toString'] }), undefined);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test('DeepSeek documented effort metadata maps only advertised reasoning levels', () => {
|
|
84
|
+
const [row] = parseModelList({ data: [{ id: 'deepseek-model', context_window: 1000000, max_output_tokens: 384000, input_modalities: ['text', 'image'], output_modalities: ['text'], effort: { supported_levels: ['low', 'high', 'max'], default_level: 'high' } }] }, 'deepseek');
|
|
85
|
+
assert.deepEqual(row.reasoningEfforts, { low: 'low', high: 'high', max: 'max' });
|
|
86
|
+
assert.equal(row.contextWindow, 1000000);
|
|
87
|
+
assert.equal(row.maxTokens, 384000);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test('installed MiniMax, ZAI and Alibaba models remain available when live discovery is unsupported', async t => {
|
|
91
|
+
t.mock.method(globalThis, 'fetch', async (url) => {
|
|
92
|
+
assert.match(new URL(url).pathname, /\/(?:models|token_plan\/remains)$/);
|
|
93
|
+
return new Response('', { status: 404 });
|
|
94
|
+
});
|
|
95
|
+
const registry = builtinModels({ authContext: { env: async () => undefined, fileExists: async () => false } });
|
|
96
|
+
for (const provider of ['minimax', 'zai', 'aliyun-token-plan']) for (const region of ['cn', 'global']) {
|
|
97
|
+
const definition = getProviderDefinition(provider, { region });
|
|
98
|
+
const upstream = registry.getModels(definition.catalogProvider);
|
|
99
|
+
const models = await fetchAccountModels(provider, { access: 'fixture-key', region });
|
|
100
|
+
assert.equal(models.length, upstream.length);
|
|
101
|
+
for (const model of models) {
|
|
102
|
+
const installed = upstream.find(row => row.id === model.id);
|
|
103
|
+
assert.ok(installed);
|
|
104
|
+
assert.equal(model.source, 'installed-catalog');
|
|
105
|
+
assert.equal(model.entitlement, 'unknown');
|
|
106
|
+
assert.equal(model.reasoning, installed.reasoning);
|
|
107
|
+
assert.equal(model.contextWindow, installed.contextWindow);
|
|
108
|
+
assert.equal(model.maxTokens, installed.maxTokens);
|
|
109
|
+
assert.deepEqual(model.input, installed.input);
|
|
110
|
+
if (installed.compat) assert.deepEqual(model.compat, modelCompatFrom(installed.compat));
|
|
111
|
+
if (installed.thinkingLevelMap) {
|
|
112
|
+
const expected = Object.fromEntries(Object.entries(installed.thinkingLevelMap).filter(([, value]) => typeof value === 'string'));
|
|
113
|
+
if (Object.keys(expected).length) assert.deepEqual(model.reasoningEfforts, expected);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test('installed compat retains protocol settings but omits unsupported Harness fields', () => {
|
|
120
|
+
assert.deepEqual(modelCompatFrom({ supportsDeveloperRole: false, supportsStore: false, supportsReasoningEffort: true, thinkingFormat: 'qwen', maxTokensField: 'max_tokens', zaiToolStream: true, baseURL: 'https://evil.example', headers: { authorization: 'secret' } }), {
|
|
121
|
+
supportsDeveloperRole: false, supportsStore: false, supportsReasoningEffort: true, thinkingFormat: 'qwen', maxTokensField: 'max_tokens',
|
|
122
|
+
});
|
|
123
|
+
assert.deepEqual(modelCompatFrom({ chatTemplateKwargs: { enable_thinking: { $var: 'thinking.enabled', omitWhenOff: true }, nested: { unsafe: 'not-supported' }, temperature: 0.1 }, thinkingFormat: 'unknown', supportsStore: 'yes' }), {
|
|
124
|
+
chatTemplateKwargs: { enable_thinking: { $var: 'thinking.enabled', omitWhenOff: true }, temperature: 0.1 },
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test('new aggregate credentials stay on pinned model hosts and cannot be overridden with extra headers', () => {
|
|
129
|
+
for (const provider of aggregatorUsageIds) {
|
|
130
|
+
const request = modelListRequest(provider, 'selected-key', { apiBase: 'https://evil.example', baseURL: 'https://evil.example', requestHeaders: { authorization: 'Bearer different-account', Cookie: 'session=other' } });
|
|
131
|
+
assert.equal(request.url, getProviderDefinition(provider).modelsURL);
|
|
132
|
+
assert.equal(new Headers(request.headers).get('authorization'), 'Bearer selected-key');
|
|
133
|
+
assert.equal(new Headers(request.headers).get('cookie'), null);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test('gateway catalog is bound to configured instance and unconfigured Google does not fabricate a list', () => {
|
|
138
|
+
const request = modelListRequest('new-api', 'selected-key', { baseURL: 'https://gateway.example/v1' });
|
|
139
|
+
assert.equal(request.url, 'https://gateway.example/v1/models');
|
|
140
|
+
assert.throws(() => modelListRequest('new-api', 'key', { baseURL: 'http://127.0.0.1/v1' }), /目录接口/);
|
|
141
|
+
assert.throws(() => modelListRequest('google-antigravity', 'key'), /目录接口/);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
test('Alibaba and MiniMax can discover models absent from the installed registry', async t => {
|
|
145
|
+
t.mock.method(globalThis, 'fetch', async (url, options) => {
|
|
146
|
+
assert.equal(options.headers.authorization, 'Bearer fixture');
|
|
147
|
+
const target = new URL(url);
|
|
148
|
+
if (target.hostname === 'token-plan.cn-beijing.maas.aliyuncs.com') {
|
|
149
|
+
assert.equal(target.pathname, '/compatible-mode/v1/models');
|
|
150
|
+
return Response.json({ data: [{ id: 'new-bailian-chat' }] });
|
|
151
|
+
}
|
|
152
|
+
assert.equal(target.origin + target.pathname, 'https://api.minimax.cn/v1/token_plan/remains');
|
|
153
|
+
return Response.json({ model_remains: [{ model_name: 'MiniMax-M9' }, { model_name: 'All Models' }] });
|
|
154
|
+
});
|
|
155
|
+
const ali = await fetchAccountModels('aliyun-token-plan', { region: 'cn', access: 'fixture' });
|
|
156
|
+
assert.deepEqual(ali.map(model => [model.id, model.source]), [['new-bailian-chat', 'account']]);
|
|
157
|
+
const minimax = await fetchAccountModels('minimax', { region: 'cn', access: 'fixture' });
|
|
158
|
+
assert.equal(minimax.find(model => model.id === 'MiniMax-M9').source, 'account-quota');
|
|
159
|
+
assert.equal(minimax.some(model => model.id === 'All Models'), false);
|
|
160
|
+
});
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { finite, iso, quotaWindow, balance, UsageError } from './core.js';
|
|
2
|
+
|
|
3
|
+
// Supplier contracts are intentionally issuer-bound. Never derive a billing
|
|
4
|
+
// endpoint from an inference base URL or send management keys to model routes.
|
|
5
|
+
export const aggregatorUsageIds = Object.freeze([
|
|
6
|
+
'openrouter', 'nanogpt', 'zenmux', 'opencode-go', 'opencode-zen',
|
|
7
|
+
'kilo', 'poe', 'synthetic', 'chutes',
|
|
8
|
+
]);
|
|
9
|
+
|
|
10
|
+
const object = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
11
|
+
const number = value => value == null || typeof value === 'boolean' || value === '' ? undefined : finite(value);
|
|
12
|
+
const decimal = value => number(value) === undefined ? undefined : value;
|
|
13
|
+
const hasMetric = row => ['used', 'limit', 'remaining', 'usedPercent', 'remainingPercent'].some(key => number(row[key]) !== undefined) || row.unlimited === true;
|
|
14
|
+
const snapshot = () => ({ windows: [], balances: [], notes: [], status: 'fresh' });
|
|
15
|
+
const partial = (out, note) => { out.status = 'partial'; out.notes.push(note); };
|
|
16
|
+
const window = (out, row) => { if (hasMetric(row)) out.windows.push(quotaWindow(row)); };
|
|
17
|
+
const wallet = (out, row) => { if (decimal(row.amount) !== undefined) out.balances.push(balance(row)); };
|
|
18
|
+
const invalid = () => new UsageError('invalid-response', 'The usage service returned no recognized quota data.');
|
|
19
|
+
const requireAccess = value => {
|
|
20
|
+
if (typeof value !== 'string' || !value.trim() || /[\r\n]/.test(value)) {
|
|
21
|
+
throw new UsageError('needs-configuration', 'A valid usage credential is required.', { status: 400 });
|
|
22
|
+
}
|
|
23
|
+
return value;
|
|
24
|
+
};
|
|
25
|
+
const bearer = access => ({ Authorization: `Bearer ${requireAccess(access)}`, Accept: 'application/json' });
|
|
26
|
+
const read = (ctx, url, access = ctx.access, headers = {}) => ctx.request(url, { method: 'GET', headers: { ...bearer(access), ...headers } });
|
|
27
|
+
const scopeId = value => typeof value === 'string' && /^[A-Za-z0-9_.:-]{1,200}$/.test(value) ? value : undefined;
|
|
28
|
+
|
|
29
|
+
function finish(out, recognized = false) {
|
|
30
|
+
if (!out.windows.length && !out.balances.length && !recognized) throw invalid();
|
|
31
|
+
if (!out.notes.length) delete out.notes;
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function openrouter(ctx) {
|
|
36
|
+
const data = object(object(await read(ctx, 'https://openrouter.ai/api/v1/key')).data);
|
|
37
|
+
const out = snapshot();
|
|
38
|
+
const period = ({ daily: 'usage_daily', weekly: 'usage_weekly', monthly: 'usage_monthly' })[data.limit_reset];
|
|
39
|
+
const used = number(period ? data[period] : data.usage);
|
|
40
|
+
window(out, {
|
|
41
|
+
id: 'key-limit', label: 'API key budget (USD)', unit: 'money', scope: 'api-key',
|
|
42
|
+
used, limit: number(data.limit), remaining: number(data.limit_remaining),
|
|
43
|
+
unlimited: data.limit === null,
|
|
44
|
+
});
|
|
45
|
+
for (const name of ['daily', 'weekly', 'monthly']) {
|
|
46
|
+
window(out, { id: `key-spend-${name}`, label: `${name} API key spend (USD)`, unit: 'money', scope: 'api-key', used: number(data[`usage_${name}`]) });
|
|
47
|
+
}
|
|
48
|
+
const budgets = Array.isArray(data.budgets) ? data.budgets : [];
|
|
49
|
+
for (const [i, raw] of budgets.slice(0, 100).entries()) {
|
|
50
|
+
const b = object(raw);
|
|
51
|
+
window(out, {
|
|
52
|
+
id: `budget-${i}`, label: 'Applicable budget (USD)', unit: 'money',
|
|
53
|
+
scope: ['organization', 'member', 'workspace', 'key'].includes(b.scope) ? b.scope : 'api-key',
|
|
54
|
+
used: number(b.spend_usd), limit: number(b.limit_usd), remaining: number(b.remaining_usd),
|
|
55
|
+
resetAt: iso(b.resets_at, 'iso'),
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
if (object(data.effective_budget).limit_usd != null) {
|
|
59
|
+
const b = data.effective_budget;
|
|
60
|
+
window(out, { id: 'effective-budget', label: 'Effective budget (USD; overlaps applicable budgets)', unit: 'money', scope: ['organization', 'member', 'workspace', 'key'].includes(b.scope) ? b.scope : 'api-key', used: number(b.spend_usd), limit: number(b.limit_usd), remaining: number(b.remaining_usd), resetAt: iso(b.resets_at, 'iso') });
|
|
61
|
+
}
|
|
62
|
+
const free = object(data.free_model_daily_requests);
|
|
63
|
+
window(out, { id: 'free-model-daily', label: 'Free model daily requests', unit: 'requests', scope: 'account', used: number(free.used), limit: number(free.limit), remaining: number(free.remaining) });
|
|
64
|
+
if (ctx.billingAccess) {
|
|
65
|
+
try {
|
|
66
|
+
const billing = object(object(await read(ctx, 'https://openrouter.ai/api/v1/credits', ctx.billingAccess)).data);
|
|
67
|
+
const total = number(billing.total_credits);
|
|
68
|
+
const spent = number(billing.total_usage);
|
|
69
|
+
if (total === undefined || spent === undefined) throw invalid();
|
|
70
|
+
// This credential can belong to a separate account. Keep its provenance
|
|
71
|
+
// distinct; the host binds it to an account before presenting a union.
|
|
72
|
+
wallet(out, { id: 'billing-account', label: 'Management credential account balance', amount: total - spent, currency: 'USD', unit: 'money', scope: 'billing-account' });
|
|
73
|
+
out.notes.push('management-balance-has-independent-account-scope');
|
|
74
|
+
} catch {
|
|
75
|
+
partial(out, 'account-balance-unavailable');
|
|
76
|
+
}
|
|
77
|
+
} else partial(out, 'account-balance-needs-permission');
|
|
78
|
+
return finish(out);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function nanogpt(ctx) {
|
|
82
|
+
const data = object(await read(ctx, 'https://api.nano-gpt.com/api/subscription/v1/usage'));
|
|
83
|
+
const out = snapshot();
|
|
84
|
+
const limits = object(data.limits);
|
|
85
|
+
for (const [id, unit, label] of [
|
|
86
|
+
['dailyInputTokens', 'tokens', 'Daily input token allowance'],
|
|
87
|
+
['weeklyInputTokens', 'tokens', 'Weekly input token allowance'],
|
|
88
|
+
['dailyImages', 'credits', 'Daily image allowance (images)'],
|
|
89
|
+
['tokens', 'tokens', 'Trial token allowance'],
|
|
90
|
+
]) {
|
|
91
|
+
const row = object(data[id]);
|
|
92
|
+
if (row.degraded === true) { partial(out, `${id}-unavailable`); continue; }
|
|
93
|
+
window(out, {
|
|
94
|
+
id, label, unit, scope: 'account:subscription', used: number(row.used), remaining: number(row.remaining),
|
|
95
|
+
limit: number(id === 'tokens' ? object(data.tokenLimits).total : limits[id]),
|
|
96
|
+
usedPercent: number(row.percentUsed) === undefined ? undefined : number(row.percentUsed) * 100,
|
|
97
|
+
resetAt: iso(row.resetAt, 'milliseconds'),
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
if (typeof data.active === 'boolean') out.notes.push(data.active ? 'subscription-active' : 'subscription-inactive');
|
|
101
|
+
const route = object(data.routing);
|
|
102
|
+
if (['subscription', 'paygo', 'unavailable'].includes(route.recommendedMode)) out.notes.push(`billing-route-${route.recommendedMode}`);
|
|
103
|
+
if (route.subscriptionQuotaAvailable === null) partial(out, 'subscription-quota-unknown');
|
|
104
|
+
// Cash balances require a different endpoint and are not implied by active
|
|
105
|
+
// subscription status. The management-only token is a different credential.
|
|
106
|
+
return finish(out, typeof data.active === 'boolean' || out.status === 'partial');
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function zenmux(ctx) {
|
|
110
|
+
if (!ctx.billingAccess) throw new UsageError('needs-permission', 'ZenMux usage requires a Management API key.', { status: 403 });
|
|
111
|
+
requireAccess(ctx.billingAccess);
|
|
112
|
+
const out = snapshot();
|
|
113
|
+
let recognized = false;
|
|
114
|
+
const managementRead = async url => {
|
|
115
|
+
try { return await read(ctx, url, ctx.billingAccess); }
|
|
116
|
+
catch (error) {
|
|
117
|
+
// ZenMux documents HTTP 422 for its management rate limits; the shared
|
|
118
|
+
// transport cannot apply that provider-specific meaning globally.
|
|
119
|
+
if (error?.status === 422) throw new UsageError('rate-limited', 'ZenMux management usage is temporarily rate limited.', { status: 422, retryAt: error.retryAt });
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
const responses = await Promise.allSettled([
|
|
124
|
+
managementRead('https://zenmux.ai/api/v1/management/subscription/detail'),
|
|
125
|
+
managementRead('https://zenmux.ai/api/v1/management/payg/balance'),
|
|
126
|
+
]);
|
|
127
|
+
if (responses[0].status === 'fulfilled') {
|
|
128
|
+
const root = object(responses[0].value);
|
|
129
|
+
const data = root.success === false ? {} : object(root.data);
|
|
130
|
+
const tier = object(data.plan).tier;
|
|
131
|
+
if (['free', 'pro', 'max', 'ultra'].includes(tier)) { out.plan = { id: tier, name: `ZenMux ${tier}` }; recognized = true; }
|
|
132
|
+
for (const [key, seconds, label] of [['quota_5_hour', 18000, 'Five-hour Flows'], ['quota_7_day', 604800, 'Seven-day Flows']]) {
|
|
133
|
+
const row = object(data[key]);
|
|
134
|
+
window(out, { id: key, label, unit: 'credits', scope: 'account:subscription', used: number(row.used_flows), limit: number(row.max_flows), remaining: number(row.remaining_flows), usedPercent: number(row.usage_percentage) === undefined ? undefined : number(row.usage_percentage) * 100, resetAt: iso(row.resets_at, 'iso'), windowSeconds: seconds });
|
|
135
|
+
}
|
|
136
|
+
window(out, { id: 'monthly-cap', label: 'Monthly Flows cap (usage unavailable)', unit: 'credits', scope: 'account:subscription', limit: number(object(data.quota_monthly).max_flows) });
|
|
137
|
+
if (!out.windows.length && !recognized) partial(out, 'subscription-detail-unavailable');
|
|
138
|
+
else out.notes.push('monthly-usage-not-provided');
|
|
139
|
+
} else partial(out, 'subscription-detail-unavailable');
|
|
140
|
+
if (responses[1].status === 'fulfilled') {
|
|
141
|
+
const root = object(responses[1].value);
|
|
142
|
+
const data = root.success === false ? {} : object(root.data);
|
|
143
|
+
for (const [field, id, label] of [['total_credits', 'payg-total', 'Total PAYG balance'], ['top_up_credits', 'payg-top-up', 'Top-up balance (part of total)'], ['bonus_credits', 'payg-bonus', 'Bonus balance (part of total)']]) {
|
|
144
|
+
wallet(out, { id, label, unit: 'money', currency: 'USD', amount: decimal(data[field]), scope: 'account:payg' });
|
|
145
|
+
}
|
|
146
|
+
if (!out.balances.length) partial(out, 'payg-balance-unavailable');
|
|
147
|
+
} else partial(out, 'payg-balance-unavailable');
|
|
148
|
+
if (!recognized && !out.windows.length && !out.balances.length) {
|
|
149
|
+
const rejected = responses.find(r => r.status === 'rejected');
|
|
150
|
+
if (rejected) throw rejected.reason;
|
|
151
|
+
}
|
|
152
|
+
return finish(out, recognized);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function opencodeScope(ctx) {
|
|
156
|
+
const id = scopeId(ctx.workspaceId) || scopeId(ctx.organizationId) || scopeId(object(object(ctx.rawGrant).metadata).orgID) || scopeId(object(ctx.rawGrant).org_id);
|
|
157
|
+
if (!id) throw new UsageError('needs-configuration', 'Select the OpenCode workspace before querying usage.', { status: 400 });
|
|
158
|
+
return id;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function opencode(ctx, go) {
|
|
162
|
+
const id = opencodeScope(ctx);
|
|
163
|
+
const out = snapshot();
|
|
164
|
+
if (go) {
|
|
165
|
+
const data = object(object(await read(ctx, 'https://opencode.ai/zen/go/v1/usage', ctx.access, { 'x-opencode-org-id': id })).usage);
|
|
166
|
+
for (const [name, label, seconds] of [['rolling', 'Go five-hour allowance', 18000], ['weekly', 'Go weekly allowance', 604800], ['monthly', 'Go monthly allowance', undefined]]) {
|
|
167
|
+
const row = object(data[name]);
|
|
168
|
+
window(out, { id: name, label, unit: 'percent', scope: `workspace:${id}:member`, usedPercent: number(row.percent), resetAt: iso(row.resetsAt, 'iso'), windowSeconds: seconds });
|
|
169
|
+
if (row.status === 'rate-limited') out.notes.push(`${name}-rate-limited`);
|
|
170
|
+
}
|
|
171
|
+
return finish(out);
|
|
172
|
+
}
|
|
173
|
+
const budgets = await read(ctx, 'https://opencode.ai/console/api/policies/current-budgets', ctx.access, { 'x-org-id': id });
|
|
174
|
+
if (!Array.isArray(budgets)) throw invalid();
|
|
175
|
+
for (const [i, raw] of budgets.slice(0, 100).entries()) {
|
|
176
|
+
const row = object(raw);
|
|
177
|
+
const scope = `workspace:${id}:${row.scope === 'combined' ? 'shared' : 'member'}`;
|
|
178
|
+
if (row.per === 'model') {
|
|
179
|
+
// spentDollars is the maximum model's usage, not the sum; preserve each
|
|
180
|
+
// independently constrained model when the server supplies its spend.
|
|
181
|
+
for (const [j, model] of (Array.isArray(row.models) ? row.models : []).slice(0, 200).entries()) {
|
|
182
|
+
window(out, { id: `budget-${i}-model-${j}`, label: `Model budget ${i + 1}.${j + 1} (USD)`, unit: 'money', scope: `${scope}:model`, used: number(object(model).spentDollars), limit: number(row.limitDollars), resetAt: iso(row.resetsAt, 'iso') });
|
|
183
|
+
}
|
|
184
|
+
if (!row.models?.length) out.notes.push('per-model-budget-details-unavailable');
|
|
185
|
+
} else {
|
|
186
|
+
window(out, { id: `budget-${i}`, label: 'Workspace budget (USD)', unit: 'money', scope, used: number(row.spentDollars), limit: number(row.limitDollars), resetAt: iso(row.resetsAt, 'iso') });
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
out.notes.push('workspace-wallet-not-included');
|
|
190
|
+
return finish(out, budgets.length === 0);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function trpcPayload(entry) {
|
|
194
|
+
const value = object(entry);
|
|
195
|
+
if (value.error) return undefined;
|
|
196
|
+
const result = object(value.result);
|
|
197
|
+
const data = object(result.data);
|
|
198
|
+
return Object.hasOwn(data, 'json') ? data.json : (result.data ?? result.json);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function kilo(ctx) {
|
|
202
|
+
const url = new URL('https://app.kilo.ai/api/trpc/user.getCreditBlocks,kiloPass.getState');
|
|
203
|
+
url.searchParams.set('batch', '1');
|
|
204
|
+
url.searchParams.set('input', JSON.stringify({ 0: { json: null }, 1: { json: null } }));
|
|
205
|
+
const organization = ctx.organizationId == null ? undefined : scopeId(ctx.organizationId);
|
|
206
|
+
if (ctx.organizationId != null && !organization) throw new UsageError('needs-configuration', 'Invalid Kilo organization scope.', { status: 400 });
|
|
207
|
+
const root = await read(ctx, url.href, ctx.access, organization ? { 'X-KILOCODE-ORGANIZATIONID': organization } : {});
|
|
208
|
+
const entries = Array.isArray(root) ? root : object(root);
|
|
209
|
+
const credits = object(trpcPayload(entries[0]));
|
|
210
|
+
const pass = object(trpcPayload(entries[1]));
|
|
211
|
+
const out = snapshot();
|
|
212
|
+
const scope = organization ? `organization:${organization}` : 'account';
|
|
213
|
+
const blocks = Array.isArray(credits.creditBlocks) ? credits.creditBlocks : undefined;
|
|
214
|
+
const totalBalance = number(credits.totalBalance_mUsd);
|
|
215
|
+
if (totalBalance !== undefined) wallet(out, { id: 'account-balance', label: 'Total credit balance', unit: 'money', currency: 'USD', amount: totalBalance / 1_000_000, scope });
|
|
216
|
+
if (blocks) {
|
|
217
|
+
// Do not sum a subset of malformed blocks into an apparently complete total.
|
|
218
|
+
if (totalBalance === undefined && blocks.length && blocks.every(b => number(object(b).balance_mUsd) !== undefined)) {
|
|
219
|
+
wallet(out, { id: 'account-balance', label: 'Total credit-block balance', unit: 'money', currency: 'USD', amount: blocks.reduce((sum, b) => sum + number(b.balance_mUsd) / 1_000_000, 0), scope });
|
|
220
|
+
}
|
|
221
|
+
for (const [i, raw] of blocks.slice(0, 200).entries()) {
|
|
222
|
+
const b = object(raw);
|
|
223
|
+
wallet(out, { id: `credit-block-${i}`, label: `Credit block ${i + 1} (part of account balance)`, unit: 'money', currency: 'USD', amount: number(b.balance_mUsd) === undefined ? undefined : number(b.balance_mUsd) / 1_000_000, scope });
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const sub = Object.hasOwn(pass, 'subscription') ? object(pass.subscription) : pass;
|
|
227
|
+
const used = number(sub.currentPeriodUsageUsd);
|
|
228
|
+
const base = number(sub.currentPeriodBaseCreditsUsd);
|
|
229
|
+
const bonus = number(sub.currentPeriodBonusCreditsUsd);
|
|
230
|
+
// An absent bonus field is unknown, not an implicit zero-credit grant.
|
|
231
|
+
const limit = base !== undefined && bonus !== undefined ? base + bonus : undefined;
|
|
232
|
+
window(out, { id: 'pass-cycle', label: 'Pass current cycle credits (USD)', unit: 'money', scope: `${scope}:pass`, used, limit });
|
|
233
|
+
if (base !== undefined) window(out, { id: 'pass-base', label: 'Pass base allotment (USD; included in cycle)', unit: 'money', scope: `${scope}:pass`, limit: base });
|
|
234
|
+
if (bonus !== undefined) window(out, { id: 'pass-bonus', label: 'Pass bonus allotment (USD; included in cycle)', unit: 'money', scope: `${scope}:pass`, limit: bonus });
|
|
235
|
+
if (used !== undefined || base !== undefined || bonus !== undefined) {
|
|
236
|
+
out.plan = { name: 'Kilo Pass' };
|
|
237
|
+
const renewal = [sub.nextBillingAt, sub.nextRenewalAt, sub.renewsAt, sub.renewAt].map(v => iso(v, 'iso')).find(Boolean);
|
|
238
|
+
if (renewal) out.plan.renewsAt = renewal;
|
|
239
|
+
}
|
|
240
|
+
if (!trpcPayload(entries[0])) partial(out, 'credit-balance-unavailable');
|
|
241
|
+
if (!trpcPayload(entries[1])) partial(out, 'pass-detail-unavailable');
|
|
242
|
+
out.notes.push('internal-billing-api');
|
|
243
|
+
return finish(out, pass.subscription === null && out.status === 'fresh');
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async function poe(ctx) {
|
|
247
|
+
const data = object(await read(ctx, 'https://api.poe.com/usage/current_balance'));
|
|
248
|
+
const out = snapshot();
|
|
249
|
+
wallet(out, { id: 'points', label: 'Combined subscription and add-on points', amount: decimal(data.current_point_balance), unit: 'credits', scope: 'account' });
|
|
250
|
+
out.notes.push('points-balance-not-currency', 'subscription-split-and-reset-not-provided');
|
|
251
|
+
return finish(out);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async function synthetic(ctx) {
|
|
255
|
+
const data = object(await read(ctx, 'https://api.synthetic.new/v2/quotas'));
|
|
256
|
+
const out = snapshot();
|
|
257
|
+
const current = object(data.planWeeklyLimit);
|
|
258
|
+
if (number(current.percentRemaining) !== undefined) {
|
|
259
|
+
const next = iso(current.nextRegenAt, 'iso');
|
|
260
|
+
window(out, { id: 'weekly', label: 'Weekly plan allowance', unit: 'percent', scope: 'account:subscription', remainingPercent: number(current.percentRemaining), nextRegenAt: next, nextRegenPercent: number(current.nextRegenPercent) });
|
|
261
|
+
out.notes.push('incremental-regeneration-not-full-reset');
|
|
262
|
+
} else {
|
|
263
|
+
const rolling = object(data.rollingFiveHourLimit);
|
|
264
|
+
window(out, { id: 'legacy-five-hour', label: 'Legacy five-hour allowance', unit: 'requests', scope: 'account:subscription', limit: number(rolling.max), remaining: number(rolling.remaining), windowSeconds: 18000 });
|
|
265
|
+
const weekly = object(data.weeklyTokenLimit);
|
|
266
|
+
window(out, { id: 'legacy-weekly', label: 'Legacy weekly credits', unit: 'credits', scope: 'account:subscription', limit: number(weekly.maxCredits), remaining: number(weekly.remainingCredits), remainingPercent: number(weekly.percentRemaining) });
|
|
267
|
+
if (out.windows.length) out.notes.push('legacy-quota-schema', 'incremental-regeneration-not-full-reset');
|
|
268
|
+
const old = object(data.subscription);
|
|
269
|
+
if (!out.windows.length) window(out, { id: 'legacy-subscription', label: 'Legacy subscription requests', unit: 'requests', scope: 'account:subscription', limit: number(old.limit), used: number(old.requests), resetAt: iso(old.renewsAt, 'iso') });
|
|
270
|
+
}
|
|
271
|
+
return finish(out);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
async function chutes(ctx) {
|
|
275
|
+
const data = object(await read(ctx, 'https://api.chutes.ai/users/me/subscription_usage'));
|
|
276
|
+
const out = snapshot();
|
|
277
|
+
if (data.subscription === false) { out.notes.push('no-subscription', 'payg-balance-not-provided'); return finish(out, true); }
|
|
278
|
+
if (data.subscription !== true) throw invalid();
|
|
279
|
+
for (const [id, label, seconds] of [['four_hour', 'Four-hour PAYG-equivalent allowance (USD)', 14400], ['monthly', 'Monthly PAYG-equivalent allowance (USD)', undefined]]) {
|
|
280
|
+
const row = object(data[id]);
|
|
281
|
+
window(out, { id, label, unit: 'money', scope: 'account:subscription', used: number(row.usage), limit: number(row.cap), remaining: number(row.remaining), unlimited: row.uncapped === true, resetAt: iso(row.reset_at, 'iso'), windowSeconds: seconds });
|
|
282
|
+
}
|
|
283
|
+
out.notes.push('allowance-is-payg-equivalent-not-wallet', 'four-hour-fixed-server-bucket', 'daily-request-quota-not-included');
|
|
284
|
+
return finish(out);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
export async function fetchAggregatorUsage(id, ctx) {
|
|
288
|
+
if (!aggregatorUsageIds.includes(id)) throw new UsageError('unsupported', 'No usage adapter is available for this platform.');
|
|
289
|
+
if (typeof ctx?.request !== 'function') throw new UsageError('needs-configuration', 'A usage transport is required.', { status: 400 });
|
|
290
|
+
const adapters = { openrouter, nanogpt, zenmux, 'opencode-go': c => opencode(c, true), 'opencode-zen': c => opencode(c, false), kilo, poe, synthetic, chutes };
|
|
291
|
+
return adapters[id](ctx);
|
|
292
|
+
}
|