pi-alibaba-token-plan 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +86 -2
- package/README.ru.md +87 -0
- package/extensions/index.js +58 -0
- package/package.json +45 -4
- package/src/auth.js +68 -0
- package/src/catalog.js +140 -0
- package/src/models.js +64 -0
- package/src/regions.js +25 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Salesao
|
|
4
|
+
Copyright (c) 2025 Mario Zechner (Pi questionnaire example)
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,87 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-alibaba-token-plan
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Alibaba Model Studio **Token Plan** as a Pi provider: sign in with `/login`, pick the region your
|
|
4
|
+
plan was bought in, and get the plan's own model list with correct context limits and thinking.
|
|
5
|
+
|
|
6
|
+
Works with both Token Plan endpoints — Singapore (International) and China (Beijing). Keys are
|
|
7
|
+
region-specific, so the region is stored with the key.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pi install npm:pi-alibaba-token-plan
|
|
13
|
+
# or straight from the repository
|
|
14
|
+
pi install git:github.com/Salesao/pi-alibaba-token-plan
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Where the key comes from
|
|
18
|
+
|
|
19
|
+
The Token Plan lives in the Alibaba Cloud Model Studio console —
|
|
20
|
+
[modelstudio.console.alibabacloud.com](https://modelstudio.console.alibabacloud.com/).
|
|
21
|
+
Open the subscription page for your region and copy its dedicated API key:
|
|
22
|
+
|
|
23
|
+
| Region | Console page |
|
|
24
|
+
|---|---|
|
|
25
|
+
| Singapore (International) | [Token Plan Personal](https://modelstudio.console.alibabacloud.com/ap-southeast-1/subscription/token-plan/personal) |
|
|
26
|
+
| China (Beijing) | [Token Plan](https://bailian.console.aliyun.com/cn-beijing/subscription/token-plan) |
|
|
27
|
+
|
|
28
|
+
The same console lists the models your plan serves. A pay-as-you-go DashScope key does not work here.
|
|
29
|
+
|
|
30
|
+
## Sign in
|
|
31
|
+
|
|
32
|
+
```text
|
|
33
|
+
/login alibaba-openai
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
1. Pick **Singapore (International)** or **China (Beijing)** — the region shown in your Token Plan console.
|
|
37
|
+
2. Paste the Token Plan API key (a dedicated key, not a pay-as-you-go DashScope key).
|
|
38
|
+
|
|
39
|
+
The key is verified against the selected region before it is saved. A key from the other region is
|
|
40
|
+
rejected with a clear message and nothing is stored. Credentials live in `~/.pi/agent/auth.json`.
|
|
41
|
+
|
|
42
|
+
Prefer environment variables? Both are read when no credential is stored:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
export ALIBABA_API_KEY=sk-sp-your-key-here
|
|
46
|
+
export ALIBABA_TOKEN_PLAN_REGION=sg # sg (default) or cn
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Use
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pi --model alibaba-openai/qwen4-max-preview:xhigh
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Thinking levels for the Qwen models are `low`, `medium` and `xhigh` — ask for `:xhigh`, not `:high`.
|
|
56
|
+
`qwen4-max-preview` has a 1M context and a 393,216-token output budget shared by thinking and the
|
|
57
|
+
answer. It is a **preview**: Alibaba retires it after 2026-11-25.
|
|
58
|
+
|
|
59
|
+
## How the model list works
|
|
60
|
+
|
|
61
|
+
- The model ids come from your plan's own `GET /models`, so new models appear without a package update.
|
|
62
|
+
- That answer carries ids only. Context limits, thinking levels and input types come from the public
|
|
63
|
+
pi.dev catalogs of the Qwen Token Plan providers, then from a small verified table inside this
|
|
64
|
+
package for models those catalogs lag on.
|
|
65
|
+
- Pi stores the resulting catalog in `~/.pi/agent/models-store.json`, which is what offline starts and
|
|
66
|
+
`pi -p` use. The list is refreshed on interactive startup, at most once every 15 minutes.
|
|
67
|
+
- **First run:** start `pi` interactively once. Until that first catalog fetch there is nothing stored,
|
|
68
|
+
so `pi --list-models` and `pi -p` show no models for this provider. (`pi update --models` only
|
|
69
|
+
refreshes Pi's built-in catalogs, not provider extensions.)
|
|
70
|
+
- A failed or empty answer never wipes the catalog you already have.
|
|
71
|
+
|
|
72
|
+
Only chat models are listed. The plan's image, video and audio models are filtered out.
|
|
73
|
+
Costs are reported as zero because the plan is a subscription, not per-token billing.
|
|
74
|
+
|
|
75
|
+
## Development
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
npm install # installs the host SDK peer dependencies for the tests
|
|
79
|
+
npm test
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Try it without installing: `pi -ne -e ./pi-alibaba-token-plan --list-models alibaba`
|
|
83
|
+
(`-ne` disables extension discovery, so a hand-installed copy cannot clash over the provider id).
|
|
84
|
+
|
|
85
|
+
## License
|
|
86
|
+
|
|
87
|
+
MIT
|
package/README.ru.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# pi-alibaba-token-plan
|
|
2
|
+
|
|
3
|
+
Подписка **Alibaba Model Studio Token Plan** как провайдер Pi: вход через `/login`, выбор региона
|
|
4
|
+
покупки и список моделей самой подписки с правильными лимитами контекста и thinking.
|
|
5
|
+
|
|
6
|
+
Поддержаны оба адреса Token Plan — Сингапур (международный) и Китай (Пекин). Ключи привязаны к
|
|
7
|
+
региону, поэтому регион хранится вместе с ключом.
|
|
8
|
+
|
|
9
|
+
## Установка
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pi install npm:pi-alibaba-token-plan
|
|
13
|
+
# или прямо из репозитория
|
|
14
|
+
pi install git:github.com/Salesao/pi-alibaba-token-plan
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Откуда берётся ключ
|
|
18
|
+
|
|
19
|
+
Подписка Token Plan живёт в консоли Alibaba Cloud Model Studio —
|
|
20
|
+
[modelstudio.console.alibabacloud.com](https://modelstudio.console.alibabacloud.com/).
|
|
21
|
+
Откройте страницу подписки своего региона и скопируйте её специальный API-ключ:
|
|
22
|
+
|
|
23
|
+
| Регион | Страница консоли |
|
|
24
|
+
|---|---|
|
|
25
|
+
| Сингапур (международный) | [Token Plan Personal](https://modelstudio.console.alibabacloud.com/ap-southeast-1/subscription/token-plan/personal) |
|
|
26
|
+
| Китай (Пекин) | [Token Plan](https://bailian.console.aliyun.com/cn-beijing/subscription/token-plan) |
|
|
27
|
+
|
|
28
|
+
В той же консоли видно, какие модели доступны вашей подписке. Обычный pay-as-you-go ключ DashScope здесь не работает.
|
|
29
|
+
|
|
30
|
+
## Вход
|
|
31
|
+
|
|
32
|
+
```text
|
|
33
|
+
/login alibaba-openai
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
1. Выберите **Singapore (International)** или **China (Beijing)** — тот регион, что указан в консоли Token Plan.
|
|
37
|
+
2. Вставьте ключ Token Plan (специальный ключ подписки, не pay-as-you-go ключ DashScope).
|
|
38
|
+
|
|
39
|
+
Ключ проверяется на выбранном регионе до сохранения. Ключ другого региона отклоняется с понятным
|
|
40
|
+
сообщением, и ничего не записывается. Ключи хранятся в `~/.pi/agent/auth.json`.
|
|
41
|
+
|
|
42
|
+
Предпочитаете переменные окружения? Обе читаются, если сохранённого ключа нет:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
export ALIBABA_API_KEY=sk-sp-ваш-ключ
|
|
46
|
+
export ALIBABA_TOKEN_PLAN_REGION=sg # sg (по умолчанию) или cn
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Использование
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pi --model alibaba-openai/qwen4-max-preview:xhigh
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Уровни thinking у моделей Qwen — `low`, `medium` и `xhigh`: просите `:xhigh`, а не `:high`.
|
|
56
|
+
У `qwen4-max-preview` контекст 1M и бюджет вывода 393 216 токенов, общий для thinking и ответа.
|
|
57
|
+
Это **превью**: Alibaba отключает модель после 25.11.2026.
|
|
58
|
+
|
|
59
|
+
## Как устроен список моделей
|
|
60
|
+
|
|
61
|
+
- Id моделей приходят из `GET /models` самой подписки, поэтому новые модели появляются без обновления пакета.
|
|
62
|
+
- В этом ответе только id. Лимиты контекста, уровни thinking и типы входа берутся из открытых
|
|
63
|
+
каталогов pi.dev для провайдеров Qwen Token Plan, а для моделей, которых там ещё нет, — из
|
|
64
|
+
небольшой проверенной таблицы внутри пакета.
|
|
65
|
+
- Полученный каталог pi хранит в `~/.pi/agent/models-store.json` — именно его используют офлайн-запуски
|
|
66
|
+
и `pi -p`. Список обновляется при интерактивном запуске, не чаще раза в 15 минут.
|
|
67
|
+
- **Первый запуск:** один раз запустите `pi` в терминале. До первой загрузки каталога хранить нечего,
|
|
68
|
+
поэтому `pi --list-models` и `pi -p` не показывают моделей этого провайдера. (`pi update --models`
|
|
69
|
+
обновляет только встроенные каталоги pi, не провайдеры-расширения.)
|
|
70
|
+
- Неудачный или пустой ответ никогда не стирает уже имеющийся каталог.
|
|
71
|
+
|
|
72
|
+
В списке только чатовые модели. Модели картинок, видео и звука из подписки отфильтрованы.
|
|
73
|
+
Стоимость показывается нулевой: подписка, а не оплата за токены.
|
|
74
|
+
|
|
75
|
+
## Разработка
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
npm install # ставит хостовые SDK-зависимости для тестов
|
|
79
|
+
npm test
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Попробовать без установки: `pi -ne -e ./pi-alibaba-token-plan --list-models alibaba`
|
|
83
|
+
(`-ne` отключает обнаружение расширений, поэтому вручную вложенная копия не конфликтует по id провайдера).
|
|
84
|
+
|
|
85
|
+
## Лицензия
|
|
86
|
+
|
|
87
|
+
MIT
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Alibaba Model Studio Token Plan provider for Pi.
|
|
3
|
+
*
|
|
4
|
+
* The plan's /models answer carries ids only, so limits and thinking settings
|
|
5
|
+
* come from the pi.dev catalogs plus a verified table (see src/catalog.js).
|
|
6
|
+
* Pi owns catalog persistence: createProvider restores context.stored and
|
|
7
|
+
* publishes what fetchModels returns, so this package writes no cache of its own.
|
|
8
|
+
*
|
|
9
|
+
* Login: /login alibaba-openai → region → key. Keys are region-specific.
|
|
10
|
+
*/
|
|
11
|
+
import { createProvider } from "@earendil-works/pi-ai";
|
|
12
|
+
// The api factories live on the compat entrypoint, which is also the specifier Pi
|
|
13
|
+
// maps for extensions; a deeper subpath resolves only when node_modules exists.
|
|
14
|
+
import { openAICompletionsApi } from "@earendil-works/pi-ai/compat";
|
|
15
|
+
import { homedir } from "node:os";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
import { API_KEY_ENV, createApiKeyAuth } from "../src/auth.js";
|
|
18
|
+
import { REFRESH_INTERVAL_MS, isFresh, loadModels, readLegacyCache } from "../src/models.js";
|
|
19
|
+
import { DEFAULT_REGION, REGION_ENV, baseUrlFor, resolveRegion } from "../src/regions.js";
|
|
20
|
+
|
|
21
|
+
const PROVIDER_ID = "alibaba-openai";
|
|
22
|
+
|
|
23
|
+
export default function register(pi, { fetchImpl = fetch, agentDir = join(homedir(), ".pi", "agent") } = {}) {
|
|
24
|
+
async function fetchModels(context) {
|
|
25
|
+
const region = resolveRegion(context.credential?.env?.[REGION_ENV] ?? process.env[REGION_ENV]);
|
|
26
|
+
const apiKey = context.credential?.key ?? process.env[API_KEY_ENV];
|
|
27
|
+
if (!apiKey) throw new Error(`No Token Plan API key. Run /login ${PROVIDER_ID}`);
|
|
28
|
+
return loadModels({
|
|
29
|
+
baseUrl: baseUrlFor(region),
|
|
30
|
+
apiKey,
|
|
31
|
+
providerId: PROVIDER_ID,
|
|
32
|
+
signal: context.signal,
|
|
33
|
+
fetchImpl,
|
|
34
|
+
previousModels: context.stored?.models,
|
|
35
|
+
legacyModels: readLegacyCache({ agentDir }),
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const provider = createProvider({
|
|
40
|
+
id: PROVIDER_ID,
|
|
41
|
+
name: "Alibaba Token Plan",
|
|
42
|
+
baseUrl: baseUrlFor(DEFAULT_REGION),
|
|
43
|
+
auth: { apiKey: createApiKeyAuth({ fetchImpl }) },
|
|
44
|
+
models: [],
|
|
45
|
+
fetchModels,
|
|
46
|
+
api: openAICompletionsApi(),
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
// Freshness policy: within the interval, ask pi for a restore-only pass so a
|
|
50
|
+
// startup does not refetch. `force` (pi update --models) always goes to the network.
|
|
51
|
+
const refresh = provider.refreshModels;
|
|
52
|
+
provider.refreshModels = (context) =>
|
|
53
|
+
refresh(isFresh(context.stored) && !context.force ? { ...context, allowNetwork: false } : context);
|
|
54
|
+
|
|
55
|
+
pi.registerProvider(provider);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export { PROVIDER_ID, REFRESH_INTERVAL_MS };
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-alibaba-token-plan",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Alibaba Model Studio Token Plan provider for Pi: /login with region selection and a live model catalog",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Salesao",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/Salesao/pi-alibaba-token-plan.git"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/Salesao/pi-alibaba-token-plan#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/Salesao/pi-alibaba-token-plan/issues"
|
|
15
|
+
},
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=18"
|
|
18
|
+
},
|
|
19
|
+
"scripts": {
|
|
20
|
+
"test": "node --test test/*.test.mjs"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"extensions",
|
|
24
|
+
"src",
|
|
25
|
+
"LICENSE",
|
|
26
|
+
"README*.md"
|
|
27
|
+
],
|
|
28
|
+
"pi": {
|
|
29
|
+
"extensions": [
|
|
30
|
+
"./extensions/index.js"
|
|
31
|
+
]
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"@earendil-works/pi-ai": "*",
|
|
35
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
36
|
+
},
|
|
37
|
+
"keywords": [
|
|
38
|
+
"pi-package",
|
|
39
|
+
"pi",
|
|
40
|
+
"pi-coding-agent",
|
|
41
|
+
"extension",
|
|
42
|
+
"provider",
|
|
43
|
+
"alibaba",
|
|
44
|
+
"qwen",
|
|
45
|
+
"token-plan"
|
|
46
|
+
]
|
|
47
|
+
}
|
package/src/auth.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { REGIONS, REGION_ENV, baseUrlFor, resolveRegion } from "./regions.js";
|
|
2
|
+
|
|
3
|
+
export const API_KEY_ENV = "ALIBABA_API_KEY";
|
|
4
|
+
|
|
5
|
+
const REQUEST_TIMEOUT_MS = 6000;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Api-key auth for the Token Plan. The plan sells region-specific keys, so the
|
|
9
|
+
* region is chosen at login and stored with the credential; request auth then
|
|
10
|
+
* carries the matching baseUrl.
|
|
11
|
+
*/
|
|
12
|
+
export function createApiKeyAuth({ fetchImpl = fetch, timeoutMs = REQUEST_TIMEOUT_MS } = {}) {
|
|
13
|
+
async function readKeyAndRegion({ ctx, credential }) {
|
|
14
|
+
const storedKey = credential?.type === "api_key" ? credential.key : undefined;
|
|
15
|
+
const key = storedKey ?? (await ctx.env(API_KEY_ENV));
|
|
16
|
+
if (!key) return undefined;
|
|
17
|
+
const region = resolveRegion(credential?.env?.[REGION_ENV] ?? (await ctx.env(REGION_ENV)));
|
|
18
|
+
return { key, region, source: storedKey ? "stored credential" : API_KEY_ENV };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
return {
|
|
22
|
+
name: "Alibaba Token Plan API key",
|
|
23
|
+
|
|
24
|
+
async login(interaction) {
|
|
25
|
+
const region = resolveRegion(
|
|
26
|
+
await interaction.prompt({
|
|
27
|
+
type: "select",
|
|
28
|
+
message: "Where was the Token Plan purchased?",
|
|
29
|
+
options: Object.entries(REGIONS).map(([id, { label }]) => ({ id, label })),
|
|
30
|
+
}),
|
|
31
|
+
);
|
|
32
|
+
const key = (
|
|
33
|
+
await interaction.prompt({ type: "secret", message: "Enter the Token Plan API key" })
|
|
34
|
+
).trim();
|
|
35
|
+
if (!key) throw new Error("API key is empty");
|
|
36
|
+
|
|
37
|
+
const response = await fetchImpl(`${baseUrlFor(region)}/models`, {
|
|
38
|
+
headers: { authorization: `Bearer ${key}`, accept: "application/json" },
|
|
39
|
+
signal: AbortSignal.any([interaction.signal, AbortSignal.timeout(timeoutMs)]),
|
|
40
|
+
});
|
|
41
|
+
if (response.status === 401) {
|
|
42
|
+
throw new Error(
|
|
43
|
+
"This key belongs to a different region. Pick the region where the Token Plan was purchased.",
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
if (!response.ok) throw new Error(`Token Plan key check failed with HTTP ${response.status}`);
|
|
47
|
+
|
|
48
|
+
return { type: "api_key", key, env: { [REGION_ENV]: region } };
|
|
49
|
+
},
|
|
50
|
+
|
|
51
|
+
async check(input) {
|
|
52
|
+
const resolved = await readKeyAndRegion(input);
|
|
53
|
+
return resolved ? { type: "api_key", source: resolved.source } : undefined;
|
|
54
|
+
},
|
|
55
|
+
|
|
56
|
+
async resolve(input) {
|
|
57
|
+
const resolved = await readKeyAndRegion(input);
|
|
58
|
+
if (!resolved) return undefined;
|
|
59
|
+
return {
|
|
60
|
+
auth: { apiKey: resolved.key, baseUrl: baseUrlFor(resolved.region) },
|
|
61
|
+
// The SDK rebuilds the discovery credential from key + env only, so the
|
|
62
|
+
// region has to travel here as well or catalog refresh loses it.
|
|
63
|
+
env: { [REGION_ENV]: resolved.region },
|
|
64
|
+
source: resolved.source,
|
|
65
|
+
};
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
package/src/catalog.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// Model metadata. The plan's own /models answer carries ids only, so limits and
|
|
2
|
+
// thinking settings come from the pi.dev catalogs of the Qwen Token Plan
|
|
3
|
+
// providers, then from a small verified table for models those catalogs lag on.
|
|
4
|
+
// Catalog entries describe a different domain: their baseUrl is never used.
|
|
5
|
+
|
|
6
|
+
export const ZERO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
7
|
+
|
|
8
|
+
// Verified differences of this endpoint; catalogs add thinking format per model.
|
|
9
|
+
export const BASE_COMPAT = {
|
|
10
|
+
supportsDeveloperRole: false,
|
|
11
|
+
supportsStore: false,
|
|
12
|
+
maxTokensField: "max_completion_tokens",
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
// Personal catalogs first: the Team catalog is a superset that covers lags.
|
|
16
|
+
export const CATALOG_URLS = [
|
|
17
|
+
"https://pi.dev/api/models/providers/qwen-token-plan-individual?types=chat",
|
|
18
|
+
"https://pi.dev/api/models/providers/qwen-token-plan?types=chat",
|
|
19
|
+
"https://pi.dev/api/models/providers/qwen-token-plan-individual-cn?types=chat",
|
|
20
|
+
"https://pi.dev/api/models/providers/qwen-token-plan-cn?types=chat",
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
const REQUEST_TIMEOUT_MS = 6000;
|
|
24
|
+
|
|
25
|
+
// /models also lists image, video and audio models, which cannot be used for chat.
|
|
26
|
+
const CHAT_FAMILY_ID = /^(qwen|glm|deepseek|kimi|minimax)/i;
|
|
27
|
+
const NON_CHAT_ID = /(^wan|image|audio|tts|asr|realtime|video|embed|rerank|ocr)/i;
|
|
28
|
+
|
|
29
|
+
// Models the plan serves but the catalogs do not describe yet. Specs come from
|
|
30
|
+
// https://docs.modelstudio.console.alibabacloud.com/en/model-studio/<model-id>.
|
|
31
|
+
export const VERIFIED_OVERRIDES = {
|
|
32
|
+
// Preview until 2026-11-25. Alias: qwen4.0-max-preview. Thinking on by default (xhigh).
|
|
33
|
+
"qwen4-max-preview": {
|
|
34
|
+
name: "Qwen4 Max Preview",
|
|
35
|
+
reasoning: true,
|
|
36
|
+
input: ["text", "image"],
|
|
37
|
+
contextWindow: 1_000_000,
|
|
38
|
+
// Shared budget for thinking and the final answer.
|
|
39
|
+
maxTokens: 393_216,
|
|
40
|
+
thinkingLevelMap: { off: null, minimal: null, low: "low", medium: "medium", high: null, xhigh: "xhigh", max: null },
|
|
41
|
+
compat: { thinkingFormat: "qwen", supportsReasoningEffort: true, supportsStrictMode: true },
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export function isChatCandidate(id) {
|
|
46
|
+
return id === "auto" || (CHAT_FAMILY_ID.test(id) && !NON_CHAT_ID.test(id));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function toModelConfig(raw) {
|
|
50
|
+
if (!raw || typeof raw.id !== "string" || typeof raw.contextWindow !== "number" || typeof raw.maxTokens !== "number") {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
const input = Array.isArray(raw.input) ? raw.input.filter((kind) => kind === "text" || kind === "image") : ["text"];
|
|
54
|
+
const model = {
|
|
55
|
+
id: raw.id,
|
|
56
|
+
name: typeof raw.name === "string" ? raw.name : raw.id,
|
|
57
|
+
reasoning: raw.reasoning === true,
|
|
58
|
+
input: input.length > 0 ? input : ["text"],
|
|
59
|
+
cost: ZERO_COST, // subscription credits, not per-token prices
|
|
60
|
+
contextWindow: raw.contextWindow,
|
|
61
|
+
maxTokens: raw.maxTokens,
|
|
62
|
+
compat: { ...BASE_COMPAT, ...raw.compat },
|
|
63
|
+
};
|
|
64
|
+
if (raw.thinkingLevelMap) model.thinkingLevelMap = raw.thinkingLevelMap;
|
|
65
|
+
if (raw.inputLimits) model.inputLimits = raw.inputLimits;
|
|
66
|
+
return model;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function verifiedOverride(id) {
|
|
70
|
+
const patch = VERIFIED_OVERRIDES[id];
|
|
71
|
+
if (!patch) return undefined;
|
|
72
|
+
return toModelConfig({
|
|
73
|
+
id,
|
|
74
|
+
name: id,
|
|
75
|
+
reasoning: false,
|
|
76
|
+
input: ["text"],
|
|
77
|
+
contextWindow: 131072,
|
|
78
|
+
maxTokens: 16384,
|
|
79
|
+
...patch,
|
|
80
|
+
compat: { ...BASE_COMPAT, ...patch.compat },
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Conservative entry for a model that is live but not described anywhere yet. */
|
|
85
|
+
export function unverifiedModel(id) {
|
|
86
|
+
return toModelConfig({
|
|
87
|
+
id,
|
|
88
|
+
name: id === "auto" ? "Auto (plan router)" : `${id} (unverified)`,
|
|
89
|
+
reasoning: false,
|
|
90
|
+
input: ["text"],
|
|
91
|
+
contextWindow: 131072,
|
|
92
|
+
maxTokens: 16384,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Catalog metadata by model id. Never throws: an outage falls back to what we already know. */
|
|
97
|
+
export async function fetchCatalogModels({ signal, fetchImpl = fetch, timeoutMs = REQUEST_TIMEOUT_MS }) {
|
|
98
|
+
const catalogModels = new Map();
|
|
99
|
+
const responses = await Promise.all(
|
|
100
|
+
CATALOG_URLS.map(async (url) => {
|
|
101
|
+
try {
|
|
102
|
+
const response = await fetchImpl(url, {
|
|
103
|
+
headers: { accept: "application/json" },
|
|
104
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]),
|
|
105
|
+
});
|
|
106
|
+
if (!response.ok) return [];
|
|
107
|
+
const body = await response.json();
|
|
108
|
+
return Array.isArray(body) ? body : Array.isArray(body?.models) ? body.models : Object.values(body ?? {});
|
|
109
|
+
} catch {
|
|
110
|
+
return [];
|
|
111
|
+
}
|
|
112
|
+
}),
|
|
113
|
+
);
|
|
114
|
+
for (const entries of responses) {
|
|
115
|
+
for (const raw of entries) {
|
|
116
|
+
if (!raw || (raw.type !== undefined && raw.type !== "chat")) continue;
|
|
117
|
+
const model = toModelConfig(raw);
|
|
118
|
+
if (model && !catalogModels.has(model.id)) catalogModels.set(model.id, model);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return catalogModels;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function buildModels({ liveIds, catalogModels, previousModels, baseUrl, providerId }) {
|
|
125
|
+
const previousById = new Map((previousModels ?? []).map((model) => [model.id, model]));
|
|
126
|
+
const models = [];
|
|
127
|
+
for (const id of new Set(liveIds)) {
|
|
128
|
+
const known = catalogModels.get(id) ?? verifiedOverride(id) ?? previousById.get(id);
|
|
129
|
+
const model = known ?? (isChatCandidate(id) ? unverifiedModel(id) : undefined);
|
|
130
|
+
if (!model) continue;
|
|
131
|
+
models.push({
|
|
132
|
+
...toModelConfig(model),
|
|
133
|
+
type: "chat",
|
|
134
|
+
api: "openai-completions",
|
|
135
|
+
provider: providerId,
|
|
136
|
+
baseUrl,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
return models.sort((left, right) => left.id.localeCompare(right.id));
|
|
140
|
+
}
|
package/src/models.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { buildModels, fetchCatalogModels, toModelConfig } from "./catalog.js";
|
|
4
|
+
|
|
5
|
+
export const REFRESH_INTERVAL_MS = 15 * 60 * 1000;
|
|
6
|
+
export const REQUEST_TIMEOUT_MS = 6000;
|
|
7
|
+
|
|
8
|
+
/** The plan's own catalog: ids only, no limits. An empty answer must not wipe what we know. */
|
|
9
|
+
export async function fetchLiveIds({ baseUrl, apiKey, signal, fetchImpl = fetch, timeoutMs = REQUEST_TIMEOUT_MS }) {
|
|
10
|
+
const response = await fetchImpl(`${baseUrl}/models`, {
|
|
11
|
+
headers: { authorization: `Bearer ${apiKey}`, accept: "application/json" },
|
|
12
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]),
|
|
13
|
+
});
|
|
14
|
+
if (!response.ok) throw new Error(`Token Plan GET /models failed with HTTP ${response.status}`);
|
|
15
|
+
let body;
|
|
16
|
+
try {
|
|
17
|
+
body = await response.json();
|
|
18
|
+
} catch {
|
|
19
|
+
throw new Error("Token Plan GET /models returned an unexpected response (not JSON)");
|
|
20
|
+
}
|
|
21
|
+
const ids = Array.isArray(body?.data)
|
|
22
|
+
? body.data.map((entry) => entry?.id).filter((id) => typeof id === "string")
|
|
23
|
+
: [];
|
|
24
|
+
if (ids.length === 0) throw new Error("Token Plan GET /models returned no models");
|
|
25
|
+
return ids;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function isFresh(stored, now = Date.now()) {
|
|
29
|
+
return typeof stored?.checkedAt === "number" && now - stored.checkedAt < REFRESH_INTERVAL_MS;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** One-time migration: the snapshot the hand-installed extension kept inside its own folder. */
|
|
33
|
+
export function readLegacyCache({ agentDir }) {
|
|
34
|
+
try {
|
|
35
|
+
const parsed = JSON.parse(
|
|
36
|
+
readFileSync(join(agentDir, "extensions", "alibaba-token-plan", "models-cache.json"), "utf8"),
|
|
37
|
+
);
|
|
38
|
+
if (!Array.isArray(parsed?.models)) return undefined;
|
|
39
|
+
const models = parsed.models.map(toModelConfig).filter(Boolean);
|
|
40
|
+
return models.length > 0 ? models : undefined;
|
|
41
|
+
} catch {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function loadModels({
|
|
47
|
+
baseUrl,
|
|
48
|
+
apiKey,
|
|
49
|
+
providerId,
|
|
50
|
+
signal,
|
|
51
|
+
fetchImpl = fetch,
|
|
52
|
+
previousModels,
|
|
53
|
+
legacyModels,
|
|
54
|
+
}) {
|
|
55
|
+
const liveIds = await fetchLiveIds({ baseUrl, apiKey, signal, fetchImpl });
|
|
56
|
+
const catalogModels = await fetchCatalogModels({ signal, fetchImpl });
|
|
57
|
+
return buildModels({
|
|
58
|
+
liveIds,
|
|
59
|
+
catalogModels,
|
|
60
|
+
previousModels: previousModels?.length ? previousModels : (legacyModels ?? []),
|
|
61
|
+
baseUrl,
|
|
62
|
+
providerId,
|
|
63
|
+
});
|
|
64
|
+
}
|
package/src/regions.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Token Plan endpoints. Keys are region-specific: a key from one region is
|
|
2
|
+
// rejected with 401 by the other, so the region travels with the credential.
|
|
3
|
+
// Source: Model Studio docs, "Base URL overview" (international and China sites).
|
|
4
|
+
export const REGIONS = {
|
|
5
|
+
sg: {
|
|
6
|
+
label: "Singapore (International)",
|
|
7
|
+
baseUrl: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
|
|
8
|
+
},
|
|
9
|
+
cn: {
|
|
10
|
+
label: "China (Beijing)",
|
|
11
|
+
baseUrl: "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
|
|
12
|
+
},
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export const DEFAULT_REGION = "sg";
|
|
16
|
+
|
|
17
|
+
export const REGION_ENV = "ALIBABA_TOKEN_PLAN_REGION";
|
|
18
|
+
|
|
19
|
+
export function resolveRegion(value) {
|
|
20
|
+
return typeof value === "string" && Object.hasOwn(REGIONS, value) ? value : DEFAULT_REGION;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function baseUrlFor(region) {
|
|
24
|
+
return REGIONS[resolveRegion(region)].baseUrl;
|
|
25
|
+
}
|