dsh-volcengine-provider 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -8
- package/docs/arkcli-contract.md +1 -1
- package/docs/changelog.md +9 -1
- package/docs/client-preview.png +0 -0
- package/docs/development.md +5 -4
- package/docs/model-management.md +61 -0
- package/docs/usage.md +20 -2
- package/docs/validation.md +15 -2
- package/lib/adapter-lease.mjs +76 -0
- package/lib/catalog-snapshot.json +0 -2
- package/lib/catalog.mjs +134 -35
- package/lib/client.js +556 -5
- package/lib/index.mjs +74 -21
- package/lib/manager.mjs +60 -7
- package/lib/model-defaults.mjs +47 -0
- package/lib/state.mjs +205 -67
- package/package.json +2 -2
package/lib/index.mjs
CHANGED
|
@@ -11,6 +11,8 @@ import { ArkController } from './manager.mjs';
|
|
|
11
11
|
import { ROUTES, PLANS } from './state.mjs';
|
|
12
12
|
import { profilesFor } from './catalog.mjs';
|
|
13
13
|
import { arkRemote } from './remote.mjs';
|
|
14
|
+
import { captureModelDefaults, getModelDefaults, applyModelDefaults, describeModelDefaults } from './model-defaults.mjs';
|
|
15
|
+
import { createAdapterLease, leasedStream } from './adapter-lease.mjs';
|
|
14
16
|
|
|
15
17
|
export const name = 'dsh-volcengine-provider';
|
|
16
18
|
export const inject = ['llm'];
|
|
@@ -25,24 +27,70 @@ export function apply(ctx, config) {
|
|
|
25
27
|
const value = credentials ? (await credentials.resolve(credentialRef(ref)))?.value : launchEnvironmentOf(ctx).get(ref)?.value;
|
|
26
28
|
return typeof value === 'string' && value.length ? value : undefined;
|
|
27
29
|
} });
|
|
28
|
-
let
|
|
29
|
-
|
|
30
|
-
|
|
30
|
+
let registration, currentGeneration;
|
|
31
|
+
const generations = new Set();
|
|
32
|
+
const finalizers = new FinalizationRegistry(release => {
|
|
33
|
+
void release().catch(() => ctx.logger.error('旧模型适配器清理失败'));
|
|
34
|
+
});
|
|
35
|
+
function generation() {
|
|
36
|
+
if (!currentGeneration?.adapter || currentGeneration.lease.closed) throw new Error('模型路由未启用');
|
|
37
|
+
return currentGeneration;
|
|
38
|
+
}
|
|
39
|
+
function requestOptions(options, defaults) {
|
|
40
|
+
return {
|
|
41
|
+
...applyModelDefaults(options, defaults),
|
|
42
|
+
signal: options.signal ? AbortSignal.any([options.signal, controller.life.signal]) : controller.life.signal
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
async function withGeneration(operation) {
|
|
46
|
+
const held = generation();
|
|
47
|
+
const release = held.lease.retain();
|
|
48
|
+
try { return await operation(held); } finally { await release(); }
|
|
49
|
+
}
|
|
50
|
+
// Each prepared call retains its adapter scope and defaults until consumption or collection.
|
|
31
51
|
class ManagedAdapter extends LlmAdapter {
|
|
32
|
-
providerInfo(provider) { return
|
|
33
|
-
providerRetryPolicy(provider) { return
|
|
34
|
-
imageRequestPricing(provider, model) { return
|
|
35
|
-
imageRequestTarget(provider, model, image) { return
|
|
36
|
-
listModels(provider) { return
|
|
37
|
-
resolveModel(provider, model, signal) {
|
|
38
|
-
|
|
39
|
-
|
|
52
|
+
providerInfo(provider) { return generation().adapter.providerInfo(provider); }
|
|
53
|
+
providerRetryPolicy(provider) { return generation().adapter.providerRetryPolicy(provider); }
|
|
54
|
+
imageRequestPricing(provider, model) { return generation().adapter.imageRequestPricing(provider, model); }
|
|
55
|
+
imageRequestTarget(provider, model, image) { return generation().adapter.imageRequestTarget(provider, model, image); }
|
|
56
|
+
listModels(provider) { return withGeneration(held => held.adapter.listModels(provider)); }
|
|
57
|
+
resolveModel(provider, model, signal) {
|
|
58
|
+
return withGeneration(async held => describeModelDefaults(await held.adapter.resolveModel(provider, model, signal), getModelDefaults(held.defaults, provider, model)));
|
|
59
|
+
}
|
|
60
|
+
async prepareCall(provider, model, signal) {
|
|
61
|
+
const held = generation();
|
|
62
|
+
const release = held.lease.retain();
|
|
63
|
+
try {
|
|
64
|
+
const defaults = getModelDefaults(held.defaults, provider, model);
|
|
65
|
+
const prepared = await held.adapter.prepareCall(provider, model, signal);
|
|
66
|
+
const token = {};
|
|
67
|
+
let consumed = false;
|
|
68
|
+
const wrapped = {
|
|
69
|
+
...prepared,
|
|
70
|
+
model: describeModelDefaults(prepared.model, defaults),
|
|
71
|
+
stream: options => {
|
|
72
|
+
if (consumed) throw new Error('已准备的模型请求只能使用一次');
|
|
73
|
+
consumed = true;
|
|
74
|
+
finalizers.unregister(token);
|
|
75
|
+
return leasedStream(() => prepared.stream(requestOptions(options, defaults)), held.lease, release, finalizers);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
finalizers.register(wrapped, release, token);
|
|
79
|
+
return wrapped;
|
|
80
|
+
} catch (error) { await release(); throw error; }
|
|
81
|
+
}
|
|
82
|
+
stream(options) {
|
|
83
|
+
const held = generation();
|
|
84
|
+
const defaults = getModelDefaults(held.defaults, options.provider, options.model);
|
|
85
|
+
return leasedStream(() => held.adapter.stream(requestOptions(options, defaults)), held.lease, undefined, finalizers);
|
|
86
|
+
}
|
|
40
87
|
}
|
|
41
88
|
const managedAdapter = new ManagedAdapter();
|
|
42
89
|
async function refreshAdapters() {
|
|
43
90
|
if (controller.disposed) return;
|
|
44
91
|
const state = structuredClone(controller.store.current);
|
|
45
92
|
const providers = profilesFor(state);
|
|
93
|
+
const nextDefaults = captureModelDefaults(state);
|
|
46
94
|
const staged = { adapter: undefined, routes: [], released: false };
|
|
47
95
|
class AccountCredentials extends CredentialProvider {
|
|
48
96
|
async resolve(ref) {
|
|
@@ -57,7 +105,7 @@ export function apply(ctx, config) {
|
|
|
57
105
|
}
|
|
58
106
|
async listRecords() { return []; }
|
|
59
107
|
async readRecord() { return undefined; }
|
|
60
|
-
async modifyRecord() { throw new Error('
|
|
108
|
+
async modifyRecord() { throw new Error('请通过火山方舟 Provider 的网页登录管理账号'); }
|
|
61
109
|
async describe(ref) { return { configured: Boolean(await this.resolve(ref)) }; }
|
|
62
110
|
}
|
|
63
111
|
for (const plan of PLANS) if (providers[ROUTES[plan]]) providers[ROUTES[plan]].apiKeyEnv = `ARK_PROVIDER_${plan === 'agent-plan' ? 'AGENT' : 'CODING'}`;
|
|
@@ -88,25 +136,29 @@ export function apply(ctx, config) {
|
|
|
88
136
|
await child.inject(['credentials', 'llm'], async scope => { await scope.plugin(piAi, { providers }); });
|
|
89
137
|
}
|
|
90
138
|
});
|
|
139
|
+
const previous = currentGeneration;
|
|
140
|
+
let nextGeneration;
|
|
91
141
|
try {
|
|
92
142
|
await nextFork;
|
|
93
143
|
if (controller.disposed) { await nextFork.dispose(); return; }
|
|
94
144
|
if (Object.keys(providers).length && (!staged.adapter || staged.released)) throw new Error('Core 适配器未完成校验');
|
|
95
|
-
|
|
96
|
-
|
|
145
|
+
nextGeneration = { adapter: staged.adapter, defaults: nextDefaults };
|
|
146
|
+
nextGeneration.lease = createAdapterLease(async () => {
|
|
147
|
+
try { await nextFork.dispose(); } finally { generations.delete(nextGeneration); }
|
|
148
|
+
}, () => ctx.logger.error('旧模型适配器清理失败'));
|
|
149
|
+
generations.add(nextGeneration);
|
|
150
|
+
currentGeneration = nextGeneration;
|
|
97
151
|
try {
|
|
98
152
|
if (registration) registration.replace(staged.routes);
|
|
99
153
|
else if (staged.routes.length) registration = ctx.llm.registerAdapter(staged.routes, managedAdapter);
|
|
100
|
-
} catch (error) {
|
|
101
|
-
const old = adapterFork;
|
|
102
|
-
adapterFork = nextFork;
|
|
154
|
+
} catch (error) { currentGeneration = previous; throw error; }
|
|
103
155
|
controller.routingError = undefined;
|
|
104
|
-
if (old) await old.dispose();
|
|
105
156
|
} catch {
|
|
106
|
-
await nextFork.dispose();
|
|
157
|
+
if (nextGeneration) await nextGeneration.lease.dispose(); else await nextFork.dispose();
|
|
107
158
|
controller.routingError = '模型路由更新失败;已保留此前可用路由。请检查路由冲突、模型缓存或 Core 兼容性后重试。';
|
|
108
159
|
throw new Error(controller.routingError);
|
|
109
160
|
}
|
|
161
|
+
if (previous) await previous.lease.retire().catch(() => ctx.logger.error('旧模型适配器清理失败'));
|
|
110
162
|
}
|
|
111
163
|
let routingQueue = Promise.resolve();
|
|
112
164
|
const queueRoutingUpdate = () => {
|
|
@@ -127,11 +179,12 @@ export function apply(ctx, config) {
|
|
|
127
179
|
ctx.on('credentials/reference-updated', () => controller.clearCaches());
|
|
128
180
|
controller.ready = controller.store.load().then(queueRoutingUpdate).catch(() => {
|
|
129
181
|
controller.routingError ??= '初始化失败:请检查账号元数据和模型缓存;原文件未覆盖。';
|
|
130
|
-
ctx.logger.error('
|
|
182
|
+
ctx.logger.error('火山方舟 Provider 初始化失败;请在设置页查看状态');
|
|
131
183
|
});
|
|
132
184
|
ctx.on('dispose', async () => {
|
|
133
185
|
controller.dispose();
|
|
134
186
|
if (registration) registration();
|
|
135
|
-
|
|
187
|
+
const results = await Promise.allSettled([...generations].map(held => held.lease.dispose()));
|
|
188
|
+
if (results.some(result => result.status === 'rejected')) ctx.logger.error('模型适配器卸载失败');
|
|
136
189
|
});
|
|
137
190
|
}
|
package/lib/manager.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { dirname, join } from 'node:path';
|
|
2
2
|
import { spawn } from 'node:child_process';
|
|
3
|
-
import { StateStore, account, assertPlan, PLANS, ROUTES, revision } from './state.mjs';
|
|
4
|
-
import {
|
|
3
|
+
import { StateStore, account, assertBudgetCompatibleEfforts, assertModelId, assertPlan, normalizeModelSettings, PLANS, ROUTES, revision } from './state.mjs';
|
|
4
|
+
import { catalogStatus, effectiveModel, getModelRows, normalizeCatalog } from './catalog.mjs';
|
|
5
5
|
import { ArkCli, locateCli } from './cli.mjs';
|
|
6
6
|
import { ArkOAuth } from './oauth.mjs';
|
|
7
7
|
import { fetchUsage, parseAgentUsage, parseCodingUsage } from './quota.mjs';
|
|
@@ -20,6 +20,13 @@ export function planProfiles(status) {
|
|
|
20
20
|
if (!Object.keys(profiles).length) throw new Error('登录身份没有可用的个人 Agent/Coding 套餐 profile');
|
|
21
21
|
return profiles;
|
|
22
22
|
}
|
|
23
|
+
/** 目录中必须已有该模型:设置不得凭空造出目录里不存在的模型。 */
|
|
24
|
+
function modelRow(state, accountId, plan, modelId) {
|
|
25
|
+
const row = getModelRows(state, accountId, plan).find(item => item.id === modelId);
|
|
26
|
+
if (!row) throw new Error('模型不在当前目录中,请先刷新模型目录');
|
|
27
|
+
return row;
|
|
28
|
+
}
|
|
29
|
+
|
|
23
30
|
export class ArkController {
|
|
24
31
|
constructor({ statePath, arkCliPath, resolveRef, cliFactory, fetchImpl, spawnImpl = spawn }) {
|
|
25
32
|
this.store = new StateStore(statePath); this.arkCliPath = arkCliPath;
|
|
@@ -81,12 +88,20 @@ export class ArkController {
|
|
|
81
88
|
return { ...owner, hasApiKeys, hasQuotaKeys, authMode: oauth ? 'oauth' : 'references' };
|
|
82
89
|
}));
|
|
83
90
|
return {
|
|
84
|
-
revision: revision(state), accounts, active: { ...state.active }, routes: ROUTES,
|
|
91
|
+
revision: revision(state), accounts, active: { ...state.active }, enabled: { ...state.enabled }, routes: ROUTES,
|
|
85
92
|
...(this.routingError ? { routingError: this.routingError } : {}),
|
|
86
93
|
catalogs: state.accounts.flatMap(a => PLANS.map(plan => {
|
|
87
|
-
const
|
|
88
|
-
const
|
|
89
|
-
return {
|
|
94
|
+
const status = catalogStatus(state, a.id, plan);
|
|
95
|
+
const models = getModelRows(state, a.id, plan);
|
|
96
|
+
return {
|
|
97
|
+
accountId: a.id, plan,
|
|
98
|
+
count: status.broken ? 0 : status.count,
|
|
99
|
+
enabledCount: models.filter(model => model.enabled).length,
|
|
100
|
+
source: status.source,
|
|
101
|
+
...(status.broken ? { error: '模型缓存损坏,请重新拉取模型' } : {}),
|
|
102
|
+
...(status.updatedAt ? { updatedAt: status.updatedAt } : {}),
|
|
103
|
+
models
|
|
104
|
+
};
|
|
90
105
|
})), login: this.oauth.status()
|
|
91
106
|
};
|
|
92
107
|
}
|
|
@@ -181,10 +196,48 @@ export class ArkController {
|
|
|
181
196
|
if (this.oauth.status().accountId === accountId && ['launching', 'waiting', 'verifying'].includes(this.oauth.status().state)) throw new Error('请先取消该账号的登录');
|
|
182
197
|
next.accounts = next.accounts.filter(a => a.id !== accountId);
|
|
183
198
|
delete next.oauth[accountId];
|
|
184
|
-
for (const p of PLANS) { if (next.active[p] === accountId) next.active[p] = null; delete next.catalogs[`${accountId}:${p}`]; }
|
|
199
|
+
for (const p of PLANS) { if (next.active[p] === accountId) next.active[p] = null; delete next.catalogs[`${accountId}:${p}`]; delete next.modelSettings[`${accountId}:${p}`]; }
|
|
185
200
|
} else if (op === 'select') {
|
|
186
201
|
assertPlan(plan); if (accountId !== null) this.owner(accountId); next.active[plan] = accountId;
|
|
187
202
|
} else if (op === 'models') next.catalogs[`${accountId}:${plan}`] = catalog;
|
|
203
|
+
else if (op === 'setProviderEnabled') {
|
|
204
|
+
assertPlan(plan);
|
|
205
|
+
if (typeof request.enabled !== 'boolean') throw new Error('套餐启用状态必须是布尔值');
|
|
206
|
+
next.enabled[plan] = request.enabled;
|
|
207
|
+
} else if (op === 'setModelEnabled') {
|
|
208
|
+
assertPlan(plan); this.owner(accountId); assertModelId(request.modelId);
|
|
209
|
+
if (typeof request.enabled !== 'boolean') throw new Error('模型启用状态必须是布尔值');
|
|
210
|
+
modelRow(next, accountId, plan, request.modelId);
|
|
211
|
+
const key = `${accountId}:${plan}`;
|
|
212
|
+
const bucket = { ...(next.modelSettings[key] ?? {}) };
|
|
213
|
+
bucket[request.modelId] = { ...(bucket[request.modelId] ?? {}), enabled: request.enabled };
|
|
214
|
+
next.modelSettings[key] = bucket;
|
|
215
|
+
} else if (op === 'saveModelSettings') {
|
|
216
|
+
assertPlan(plan); this.owner(accountId); assertModelId(request.modelId);
|
|
217
|
+
const settings = normalizeModelSettings(request.settings ?? {});
|
|
218
|
+
const row = modelRow(next, accountId, plan, request.modelId);
|
|
219
|
+
const effective = effectiveModel(row.defaults, settings);
|
|
220
|
+
if (effective.maxTokens > effective.contextWindow) throw new Error('maxTokens 不得超过有效 contextWindow');
|
|
221
|
+
if (settings.defaultReasoning !== undefined && settings.defaultReasoning !== null) {
|
|
222
|
+
const efforts = effective.reasoningEfforts;
|
|
223
|
+
if (!efforts || efforts === false || !(settings.defaultReasoning in efforts)) throw new Error('默认思考档位未被有效思考档位映射支持');
|
|
224
|
+
}
|
|
225
|
+
assertBudgetCompatibleEfforts(effective.reasoningEfforts, effective.forceAdaptiveThinking);
|
|
226
|
+
const key = `${accountId}:${plan}`;
|
|
227
|
+
const bucket = { ...(next.modelSettings[key] ?? {}) };
|
|
228
|
+
const previous = bucket[request.modelId] ?? {};
|
|
229
|
+
// 参数整份替换;启用开关只有显式给出时才改写。
|
|
230
|
+
const { enabled, ...parameters } = settings;
|
|
231
|
+
const kept = enabled === undefined && previous.enabled !== undefined ? { enabled: previous.enabled } : {};
|
|
232
|
+
bucket[request.modelId] = enabled === undefined ? { ...kept, ...parameters } : { ...settings };
|
|
233
|
+
next.modelSettings[key] = bucket;
|
|
234
|
+
} else if (op === 'resetModelSettings') {
|
|
235
|
+
assertPlan(plan); this.owner(accountId); assertModelId(request.modelId);
|
|
236
|
+
const key = `${accountId}:${plan}`;
|
|
237
|
+
const bucket = { ...(next.modelSettings[key] ?? {}) };
|
|
238
|
+
delete bucket[request.modelId];
|
|
239
|
+
if (Object.keys(bucket).length) next.modelSettings[key] = bucket; else delete next.modelSettings[key];
|
|
240
|
+
}
|
|
188
241
|
else throw new Error('未知操作');
|
|
189
242
|
return next;
|
|
190
243
|
});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { PLANS, ROUTES } from './state.mjs';
|
|
2
|
+
import { getModelRows } from './catalog.mjs';
|
|
3
|
+
|
|
4
|
+
const keyFor = (provider, model) => `${provider}\0${model}`;
|
|
5
|
+
|
|
6
|
+
/** Capture only defaults owned by the currently selected account and route. */
|
|
7
|
+
export function captureModelDefaults(state) {
|
|
8
|
+
const defaults = new Map();
|
|
9
|
+
for (const plan of PLANS) {
|
|
10
|
+
if (state.enabled?.[plan] === false) continue;
|
|
11
|
+
const accountId = state.active[plan];
|
|
12
|
+
if (!state.accounts.some(account => account.id === accountId)) continue;
|
|
13
|
+
for (const row of getModelRows(state, accountId, plan)) {
|
|
14
|
+
if (!row.enabled) continue;
|
|
15
|
+
const value = {};
|
|
16
|
+
if (row.effective.temperature !== undefined) value.temperature = row.effective.temperature;
|
|
17
|
+
if (row.effective.defaultReasoning != null) value.reasoningEffort = row.effective.defaultReasoning;
|
|
18
|
+
defaults.set(keyFor(ROUTES[plan], row.id), Object.freeze(value));
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return defaults;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function getModelDefaults(defaults, provider, model) {
|
|
25
|
+
return defaults.get(keyFor(provider, model));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Explicit call controls always win over saved model defaults. */
|
|
29
|
+
export function applyModelDefaults(options, defaults = {}) {
|
|
30
|
+
const patch = {};
|
|
31
|
+
for (const field of ['temperature', 'reasoningEffort']) {
|
|
32
|
+
if (options[field] === undefined && defaults[field] !== undefined) patch[field] = defaults[field];
|
|
33
|
+
}
|
|
34
|
+
return Object.keys(patch).length ? { ...options, ...patch } : options;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Expose the same default effort that will be applied at dispatch. */
|
|
38
|
+
export function describeModelDefaults(info, defaults = {}) {
|
|
39
|
+
if (!info.reasoning) {
|
|
40
|
+
if (defaults.reasoningEffort !== undefined) throw new Error('非思考模型不能配置默认思考档位');
|
|
41
|
+
return info;
|
|
42
|
+
}
|
|
43
|
+
const { defaultEffort: _previousDefault, ...reasoning } = info.reasoning;
|
|
44
|
+
const effort = defaults.reasoningEffort;
|
|
45
|
+
if (effort !== undefined && !reasoning.efforts.some(item => item.id === effort)) throw new Error('默认思考档位与模型能力不匹配');
|
|
46
|
+
return { ...info, reasoning: { ...reasoning, ...(effort === undefined ? {} : { defaultEffort: effort }) } };
|
|
47
|
+
}
|
package/lib/state.mjs
CHANGED
|
@@ -2,86 +2,224 @@ import { createHash } from 'node:crypto';
|
|
|
2
2
|
import { mkdir, readFile, writeFile, rename } from 'node:fs/promises';
|
|
3
3
|
import { dirname } from 'node:path';
|
|
4
4
|
|
|
5
|
+
export const STATE_VERSION = 2;
|
|
5
6
|
export const PLANS = ['agent-plan', 'coding-plan'];
|
|
6
7
|
export const ROUTES = { 'agent-plan': 'volcengine-agent-plan', 'coding-plan': 'volcengine-coding-plan' };
|
|
7
8
|
export const LABELS = { 'agent-plan': '火山方舟 · Agent 套餐', 'coding-plan': '火山方舟 · 编程套餐' };
|
|
9
|
+
// Core(pi-ai)已声明的思考档位,模型设置只接受这些键。
|
|
10
|
+
export const CORE_THINKING_LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
11
|
+
// 逐模型覆盖允许出现的字段;其余字段一律拒绝(含任何凭据字段)。
|
|
12
|
+
export const MODEL_SETTING_FIELDS = ['enabled', 'contextWindow', 'maxTokens', 'temperature', 'reasoningEfforts', 'defaultReasoning', 'forceAdaptiveThinking'];
|
|
13
|
+
// 预算模式(未开启自适应思考)下 Core 只消费档位键:xhigh/max 会被折叠为 high,映射值也不再上线。
|
|
14
|
+
export const BUDGET_THINKING_LEVELS = ['off', 'minimal', 'low', 'medium', 'high'];
|
|
8
15
|
const idPattern = /^[a-z][a-z0-9-]{0,63}$/;
|
|
9
16
|
const refPattern = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
|
|
17
|
+
const modelIdPattern = /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,199}$/;
|
|
18
|
+
const reservedNames = ['constructor', 'prototype', '__proto__'];
|
|
19
|
+
|
|
20
|
+
// 动态键一律走 defineProperty,避免 `__proto__` 之类的键污染原型链。
|
|
21
|
+
function setKey(target, key, value) {
|
|
22
|
+
Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
|
|
23
|
+
return target;
|
|
24
|
+
}
|
|
10
25
|
export function assertPlan(plan) {
|
|
11
|
-
|
|
12
|
-
|
|
26
|
+
if (!PLANS.includes(plan)) throw new Error('未知订阅类型');
|
|
27
|
+
return plan;
|
|
28
|
+
}
|
|
29
|
+
export function assertModelId(modelId) {
|
|
30
|
+
if (typeof modelId !== 'string' || !modelIdPattern.test(modelId) || reservedNames.includes(modelId)) throw new Error('模型 ID 不合法');
|
|
31
|
+
return modelId;
|
|
13
32
|
}
|
|
14
33
|
export function account(input) {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
34
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('账号格式错误');
|
|
35
|
+
const allowed = ['id', 'label', 'apiKeyRefs', 'accessKeyRef', 'secretKeyRef', 'cliProfile'];
|
|
36
|
+
if (Object.keys(input).some(k => !allowed.includes(k))) throw new Error('只接受凭据引用,不接受密钥');
|
|
37
|
+
if (typeof input.id !== 'string' || !idPattern.test(input.id) || ['constructor', 'prototype', '__proto__'].includes(input.id)) throw new Error('账号 ID 须为小写字母、数字或连字符,且不能使用保留名称');
|
|
38
|
+
if (typeof input.label !== 'string' || !input.label.trim() || input.label.length > 80) throw new Error('账号名称不合法');
|
|
39
|
+
const apiKeyRefs = {};
|
|
40
|
+
for (const plan of PLANS) {
|
|
41
|
+
const ref = input.apiKeyRefs?.[plan];
|
|
42
|
+
if (ref !== undefined && (!refPattern.test(ref) || typeof ref !== 'string')) throw new Error('推理凭据引用不合法');
|
|
43
|
+
if (ref) apiKeyRefs[plan] = ref;
|
|
44
|
+
}
|
|
45
|
+
for (const k of ['accessKeyRef', 'secretKeyRef']) if (input[k] !== undefined && (typeof input[k] !== 'string' || (input[k] !== '' && !refPattern.test(input[k])))) throw new Error('AK/SK 凭据引用不合法');
|
|
46
|
+
if (input.cliProfile !== undefined && (typeof input.cliProfile !== 'string' || !/^[\w.-]{1,80}$/.test(input.cliProfile))) throw new Error('ArkCli profile 名称不合法');
|
|
47
|
+
return { id: input.id, label: input.label.trim(), apiKeyRefs, accessKeyRef: input.accessKeyRef ?? '', secretKeyRef: input.secretKeyRef ?? '', ...(input.cliProfile ? { cliProfile: input.cliProfile } : {}) };
|
|
29
48
|
}
|
|
49
|
+
|
|
50
|
+
// ── 逐模型覆盖 ──────────────────────────────────────────────────────────────────
|
|
51
|
+
|
|
52
|
+
/** 规范化思考档位映射:false 或 { 档位: 上线拼写 },只有 off 可以为空。 */
|
|
53
|
+
export function normalizeReasoningEfforts(value) {
|
|
54
|
+
if (value === false) return false;
|
|
55
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('思考档位格式错误');
|
|
56
|
+
const efforts = {};
|
|
57
|
+
for (const [level, wire] of Object.entries(value)) {
|
|
58
|
+
if (!CORE_THINKING_LEVELS.includes(level)) throw new Error(`思考档位 ${level} 不受支持`);
|
|
59
|
+
if (wire === null) {
|
|
60
|
+
if (level !== 'off') throw new Error('思考档位中只有 off 允许为空值');
|
|
61
|
+
setKey(efforts, level, null);
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (typeof wire !== 'string' || !wire.trim()) throw new Error('思考档位映射必须是非空字符串');
|
|
65
|
+
setKey(efforts, level, wire);
|
|
66
|
+
}
|
|
67
|
+
const levels = Object.keys(efforts);
|
|
68
|
+
if (!levels.length) throw new Error('思考档位不能为空');
|
|
69
|
+
if (!levels.some(level => level !== 'off')) throw new Error('至少需要声明一个非 off 的思考档位');
|
|
70
|
+
return efforts;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 预算模式下的档位校验:Core 的 simple-options 按档位键取思考预算,xhigh/max 一律折叠为 high,
|
|
75
|
+
* 映射值不参与上线。因此该模式下只接受 off/minimal/low/medium/high,非 off 映射必须与键同名。
|
|
76
|
+
* 与 Core 已核实消费端一致,不做静默折叠。
|
|
77
|
+
*/
|
|
78
|
+
export function assertBudgetCompatibleEfforts(efforts, forceAdaptiveThinking) {
|
|
79
|
+
if (forceAdaptiveThinking !== false) return;
|
|
80
|
+
if (!efforts || efforts === false) return;
|
|
81
|
+
for (const [level, wire] of Object.entries(efforts)) {
|
|
82
|
+
if (!BUDGET_THINKING_LEVELS.includes(level)) throw new Error(`预算模式下思考档位 ${level} 会被折叠为 high,请改用 ${BUDGET_THINKING_LEVELS.join('/')}`);
|
|
83
|
+
if (level === 'off') { if (wire !== null) throw new Error('预算模式下 off 档位只能为空值'); continue; }
|
|
84
|
+
if (wire !== level) throw new Error(`预算模式下思考档位 ${level} 的映射值必须与档位同名,否则不会上线`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 规范化一份逐模型覆盖值。字段级规则与同对象内的相互约束在这里裁决;
|
|
90
|
+
* 依赖目录默认值的关系(例如 maxTokens 与有效 contextWindow 的比较)由上层用目录解析后校验。
|
|
91
|
+
*/
|
|
92
|
+
export function normalizeModelSettings(input) {
|
|
93
|
+
if (input === undefined || input === null) return {};
|
|
94
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('模型设置格式错误');
|
|
95
|
+
for (const key of Object.keys(input)) if (!MODEL_SETTING_FIELDS.includes(key)) throw new Error(`模型设置包含未知字段:${key}`);
|
|
96
|
+
const settings = {};
|
|
97
|
+
if ('enabled' in input) {
|
|
98
|
+
if (typeof input.enabled !== 'boolean') throw new Error('模型启用状态必须是布尔值');
|
|
99
|
+
settings.enabled = input.enabled;
|
|
100
|
+
}
|
|
101
|
+
for (const key of ['contextWindow', 'maxTokens']) {
|
|
102
|
+
if (!(key in input)) continue;
|
|
103
|
+
const value = input[key];
|
|
104
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) throw new Error(`${key} 必须是正安全整数`);
|
|
105
|
+
settings[key] = value;
|
|
106
|
+
}
|
|
107
|
+
if ('temperature' in input) {
|
|
108
|
+
const value = input.temperature;
|
|
109
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) throw new Error('temperature 必须是 0 到 1 之间的数值');
|
|
110
|
+
settings.temperature = value;
|
|
111
|
+
}
|
|
112
|
+
if ('forceAdaptiveThinking' in input) {
|
|
113
|
+
if (typeof input.forceAdaptiveThinking !== 'boolean') throw new Error('forceAdaptiveThinking 必须是布尔值');
|
|
114
|
+
settings.forceAdaptiveThinking = input.forceAdaptiveThinking;
|
|
115
|
+
}
|
|
116
|
+
if ('reasoningEfforts' in input) settings.reasoningEfforts = normalizeReasoningEfforts(input.reasoningEfforts);
|
|
117
|
+
if ('defaultReasoning' in input) {
|
|
118
|
+
const value = input.defaultReasoning;
|
|
119
|
+
if (value !== null) {
|
|
120
|
+
if (typeof value !== 'string' || !CORE_THINKING_LEVELS.includes(value)) throw new Error('默认思考档位不受支持');
|
|
121
|
+
if (settings.reasoningEfforts === false) throw new Error('该模型没有可选思考档位,不能指定默认思考档位');
|
|
122
|
+
if (settings.reasoningEfforts !== undefined && !(value in settings.reasoningEfforts)) throw new Error('默认思考档位未被思考档位映射支持');
|
|
123
|
+
}
|
|
124
|
+
settings.defaultReasoning = value;
|
|
125
|
+
}
|
|
126
|
+
if (settings.contextWindow !== undefined && settings.maxTokens !== undefined && settings.maxTokens > settings.contextWindow) throw new Error('maxTokens 不得超过 contextWindow');
|
|
127
|
+
if (settings.forceAdaptiveThinking === false) assertBudgetCompatibleEfforts(settings.reasoningEfforts, false);
|
|
128
|
+
return settings;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** 归一化整份 modelSettings:丢弃不存在的账号与未知套餐,模型 ID 与字段逐项校验。 */
|
|
132
|
+
function normalizeModelSettingsMap(value, accounts) {
|
|
133
|
+
const result = {};
|
|
134
|
+
if (value === undefined || value === null) return result;
|
|
135
|
+
if (typeof value !== 'object' || Array.isArray(value)) throw new Error('模型设置格式错误');
|
|
136
|
+
for (const [key, bucket] of Object.entries(value)) {
|
|
137
|
+
const separator = key.lastIndexOf(':');
|
|
138
|
+
if (separator <= 0) continue;
|
|
139
|
+
const accountId = key.slice(0, separator);
|
|
140
|
+
const plan = key.slice(separator + 1);
|
|
141
|
+
if (!PLANS.includes(plan)) continue;
|
|
142
|
+
if (!accounts.some(a => a.id === accountId)) continue;
|
|
143
|
+
if (!bucket || typeof bucket !== 'object' || Array.isArray(bucket)) throw new Error('模型设置格式错误');
|
|
144
|
+
const models = {};
|
|
145
|
+
for (const [modelId, settings] of Object.entries(bucket)) {
|
|
146
|
+
assertModelId(modelId);
|
|
147
|
+
const normalized = normalizeModelSettings(settings);
|
|
148
|
+
if (!Object.keys(normalized).length) continue;
|
|
149
|
+
setKey(models, modelId, normalized);
|
|
150
|
+
}
|
|
151
|
+
if (Object.keys(models).length) setKey(result, key, models);
|
|
152
|
+
}
|
|
153
|
+
return result;
|
|
154
|
+
}
|
|
155
|
+
|
|
30
156
|
export function initialState() {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
157
|
+
return {
|
|
158
|
+
version: STATE_VERSION,
|
|
159
|
+
accounts: [account({ id: 'default', label: '现有方舟账号', apiKeyRefs: { 'agent-plan': 'ARKCLI_AGENT_PLAN_API_KEY', 'coding-plan': 'ARKCLI_CODING_PLAN_API_KEY' }, accessKeyRef: 'VOLC_ACCESSKEY', secretKeyRef: 'VOLC_SECRETKEY' })],
|
|
160
|
+
active: { 'agent-plan': 'default', 'coding-plan': 'default' },
|
|
161
|
+
enabled: { 'agent-plan': true, 'coding-plan': true },
|
|
162
|
+
catalogs: {},
|
|
163
|
+
oauth: {},
|
|
164
|
+
modelSettings: {}
|
|
165
|
+
};
|
|
38
166
|
}
|
|
39
167
|
export function validateState(value) {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
168
|
+
const version = value?.version;
|
|
169
|
+
if (version !== 1 && version !== STATE_VERSION) throw new Error('账号状态格式不兼容');
|
|
170
|
+
if (!Array.isArray(value.accounts) || value.accounts.length > 50) throw new Error('账号状态格式不兼容');
|
|
171
|
+
const accounts = value.accounts.map(account);
|
|
172
|
+
if (new Set(accounts.map(a => a.id)).size !== accounts.length) throw new Error('账号 ID 重复');
|
|
173
|
+
const active = {};
|
|
174
|
+
for (const plan of PLANS) {
|
|
175
|
+
const id = value.active?.[plan];
|
|
176
|
+
if (id !== null && id !== undefined && !accounts.some(a => a.id === id)) throw new Error('所选账号不存在');
|
|
177
|
+
active[plan] = id ?? null;
|
|
178
|
+
}
|
|
179
|
+
// Catalogs are validated at the point of use, never executable configuration.
|
|
180
|
+
const catalogs = value.catalogs && typeof value.catalogs === 'object' && !Array.isArray(value.catalogs) ? value.catalogs : {};
|
|
181
|
+
const oauth = {};
|
|
182
|
+
for (const owner of accounts) {
|
|
183
|
+
const binding = value.oauth?.[owner.id];
|
|
184
|
+
if (!binding) continue;
|
|
185
|
+
const profiles = {};
|
|
186
|
+
for (const plan of PLANS) {
|
|
187
|
+
const profile = binding.profiles?.[plan];
|
|
188
|
+
if (profile !== undefined && (typeof profile !== 'string' || profile.length > 200 || /[\x00-\x1f]/.test(profile))) throw new Error('OAuth profile 绑定格式错误');
|
|
189
|
+
if (profile) profiles[plan] = profile;
|
|
190
|
+
}
|
|
191
|
+
oauth[owner.id] = { profiles, loggedAt: typeof binding.loggedAt === 'string' ? binding.loggedAt : '' };
|
|
192
|
+
}
|
|
193
|
+
// 版本 1 没有 enabled:有所选账号的套餐视为启用,原来未选择账号的套餐视为停用。
|
|
194
|
+
const enabled = {};
|
|
195
|
+
for (const plan of PLANS) {
|
|
196
|
+
const declared = version === 1 ? undefined : value.enabled?.[plan];
|
|
197
|
+
if (declared !== undefined && typeof declared !== 'boolean') throw new Error('套餐启用状态必须是布尔值');
|
|
198
|
+
enabled[plan] = declared ?? Boolean(active[plan]);
|
|
199
|
+
}
|
|
200
|
+
const modelSettings = normalizeModelSettingsMap(value.modelSettings, accounts);
|
|
201
|
+
return { version: STATE_VERSION, accounts, active, enabled, catalogs, oauth, modelSettings };
|
|
64
202
|
}
|
|
65
203
|
export const revision = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
66
204
|
export class StateStore {
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
205
|
+
constructor(path) { this.path = path; this.current = null; this.queue = Promise.resolve(); }
|
|
206
|
+
async load() {
|
|
207
|
+
try { this.current = validateState(JSON.parse(await readFile(this.path, 'utf8'))); }
|
|
208
|
+
catch (error) { if (error.code !== 'ENOENT') throw new Error('无法读取方舟账号状态;原文件未被覆盖'); this.current = initialState(); }
|
|
209
|
+
return this.current;
|
|
210
|
+
}
|
|
211
|
+
mutate(expectedRevision, change) {
|
|
212
|
+
const operation = this.queue.then(async () => {
|
|
213
|
+
if (expectedRevision !== revision(this.current)) throw new Error('设置已改变,请刷新后重试');
|
|
214
|
+
const next = validateState(change(structuredClone(this.current)));
|
|
215
|
+
await mkdir(dirname(this.path), { recursive: true });
|
|
216
|
+
const temp = `${this.path}.${process.pid}.tmp`;
|
|
217
|
+
await writeFile(temp, JSON.stringify(next, null, 2) + '\n', { mode: 0o600 });
|
|
218
|
+
await rename(temp, this.path);
|
|
219
|
+
this.current = next;
|
|
220
|
+
return next;
|
|
221
|
+
});
|
|
222
|
+
this.queue = operation.catch(() => {});
|
|
223
|
+
return operation;
|
|
224
|
+
}
|
|
87
225
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-volcengine-provider",
|
|
3
|
-
"displayName": "
|
|
4
|
-
"version": "0.
|
|
3
|
+
"displayName": "火山方舟 Provider",
|
|
4
|
+
"version": "0.2.0",
|
|
5
5
|
"description": "火山方舟 Agent Plan 与 Coding Plan:OAuth 登录、账号、模型与额度管理。",
|
|
6
6
|
"repository": {"type": "git", "url": "git+https://github.com/KouzakiUmi/dsh-volcengine-provider.git"},
|
|
7
7
|
"homepage": "https://github.com/KouzakiUmi/dsh-volcengine-provider#readme",
|