dsh-volcengine-provider 0.2.0 → 0.2.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.md +4 -4
- package/docs/arkcli-contract.md +4 -0
- package/docs/changelog.md +20 -0
- package/docs/client-journey-preview-empty.png +0 -0
- package/docs/client-journey-preview-mobile.png +0 -0
- package/docs/client-journey-preview.png +0 -0
- package/docs/client-preview-mobile.png +0 -0
- package/docs/client-preview.png +0 -0
- package/docs/development.md +1 -1
- package/docs/usage.md +19 -13
- package/docs/validation.md +33 -4
- package/lib/catalog.mjs +18 -5
- package/lib/client.js +343 -123
- package/lib/index.mjs +7 -0
- package/lib/manager.mjs +84 -21
- package/lib/oauth.mjs +4 -4
- package/lib/state.mjs +61 -10
- package/package.json +2 -2
package/lib/index.mjs
CHANGED
|
@@ -152,6 +152,13 @@ export function apply(ctx, config) {
|
|
|
152
152
|
if (registration) registration.replace(staged.routes);
|
|
153
153
|
else if (staged.routes.length) registration = ctx.llm.registerAdapter(staged.routes, managedAdapter);
|
|
154
154
|
} catch (error) { currentGeneration = previous; throw error; }
|
|
155
|
+
controller.appliedAccounts = Object.fromEntries(PLANS.map(plan => {
|
|
156
|
+
const owner = state.accounts.find(a => a.id === state.active[plan]);
|
|
157
|
+
const identity = owner && state.oauth[owner.id]?.identity;
|
|
158
|
+
return [plan, owner && staged.routes.includes(ROUTES[plan])
|
|
159
|
+
? { id: owner.id, displayName: identity?.name || (identity?.accountId ? `方舟账号 ${identity.accountId}` : owner.label) }
|
|
160
|
+
: null];
|
|
161
|
+
}));
|
|
155
162
|
controller.routingError = undefined;
|
|
156
163
|
} catch {
|
|
157
164
|
if (nextGeneration) await nextGeneration.lease.dispose(); else await nextFork.dispose();
|
package/lib/manager.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { dirname, join } from 'node:path';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
2
3
|
import { spawn } from 'node:child_process';
|
|
3
|
-
import { StateStore, account, assertBudgetCompatibleEfforts, assertModelId, assertPlan, normalizeModelSettings, PLANS, ROUTES, revision } from './state.mjs';
|
|
4
|
+
import { StateStore, account, assertBudgetCompatibleEfforts, assertModelId, assertPlan, normalizeModelSettings, normalizeIdentity, PLANS, ROUTES, revision } from './state.mjs';
|
|
4
5
|
import { catalogStatus, effectiveModel, getModelRows, normalizeCatalog } from './catalog.mjs';
|
|
5
6
|
import { ArkCli, locateCli } from './cli.mjs';
|
|
6
7
|
import { ArkOAuth } from './oauth.mjs';
|
|
@@ -33,7 +34,8 @@ export class ArkController {
|
|
|
33
34
|
this.resolveRef = resolveRef; this.cliFactory = cliFactory; this.fetchImpl = fetchImpl;
|
|
34
35
|
this.life = new AbortController(); this.disposed = false; this.cache = new Map(); this.inflight = new Map();
|
|
35
36
|
this.inferenceCache = new Map(); this.inferenceInflight = new Map(); this.cacheGeneration = 0;
|
|
36
|
-
this.
|
|
37
|
+
this.identityCache = new Map(); this.identityInflight = new Map();
|
|
38
|
+
this.oauth = new ArkOAuth({ spawn: spawnImpl, onSuccess: (id, rev, signal, homeId) => this.bindLogin(id, rev, signal, homeId) });
|
|
37
39
|
this.onChange = async () => {}; this.operations = Promise.resolve();
|
|
38
40
|
}
|
|
39
41
|
owner(id) {
|
|
@@ -42,14 +44,16 @@ export class ArkController {
|
|
|
42
44
|
if (!owner) throw new Error('账号不存在');
|
|
43
45
|
return owner;
|
|
44
46
|
}
|
|
45
|
-
async cli(owner) {
|
|
46
|
-
const
|
|
47
|
+
async cli(owner, binding = this.store.current.oauth?.[owner.id]) {
|
|
48
|
+
const root = join(dirname(this.store.path), 'accounts', owner.id);
|
|
49
|
+
const home = binding?.homeId ? join(root, 'sessions', binding.homeId) : root;
|
|
47
50
|
if (this.cliFactory) return this.cliFactory(owner, home);
|
|
48
51
|
return new ArkCli({ executable: await locateCli(this.arkCliPath), home });
|
|
49
52
|
}
|
|
50
53
|
clearCaches() {
|
|
51
54
|
this.cacheGeneration++;
|
|
52
55
|
this.cache.clear(); this.inflight.clear(); this.inferenceCache.clear(); this.inferenceInflight.clear();
|
|
56
|
+
this.identityCache.clear(); this.identityInflight.clear();
|
|
53
57
|
}
|
|
54
58
|
async inferenceKey(owner, plan, selection = { binding: this.store.current.oauth?.[owner.id] }) {
|
|
55
59
|
if (this.disposed) throw new Error('插件已卸载');
|
|
@@ -57,14 +61,14 @@ export class ArkController {
|
|
|
57
61
|
if (binding) {
|
|
58
62
|
const profile = binding.profiles[plan];
|
|
59
63
|
if (!profile) return undefined; // Never borrow a different identity/key pool after OAuth binding.
|
|
60
|
-
const cacheKey = revision({ accountId: owner.id, plan, profile, loggedAt: binding.loggedAt });
|
|
64
|
+
const cacheKey = revision({ accountId: owner.id, plan, profile, loggedAt: binding.loggedAt, homeId: binding.homeId });
|
|
61
65
|
const cached = this.inferenceCache.get(cacheKey);
|
|
62
66
|
if (cached && Date.now() - cached.at < 30000) return cached.value;
|
|
63
67
|
if (this.inferenceInflight.has(cacheKey)) return this.inferenceInflight.get(cacheKey);
|
|
64
68
|
const generation = this.cacheGeneration;
|
|
65
69
|
const task = (async () => {
|
|
66
70
|
try {
|
|
67
|
-
const key = await (await this.cli(owner)).apiKey(profile, this.life.signal);
|
|
71
|
+
const key = await (await this.cli(owner, binding)).apiKey(profile, this.life.signal);
|
|
68
72
|
if (typeof key !== 'string' || !key || /\s/.test(key) || key.length > 4096) throw new Error('ArkCli 未返回有效推理凭据');
|
|
69
73
|
if (this.disposed || this.life.signal.aborted) throw new Error('插件已卸载');
|
|
70
74
|
if (generation === this.cacheGeneration) this.inferenceCache.set(cacheKey, { at: Date.now(), value: key });
|
|
@@ -77,19 +81,54 @@ export class ArkController {
|
|
|
77
81
|
const ref = owner.apiKeyRefs[plan];
|
|
78
82
|
return ref ? await this.resolveRef(ref) : undefined;
|
|
79
83
|
}
|
|
84
|
+
async identityFor(owner, binding) {
|
|
85
|
+
if (!binding) return undefined;
|
|
86
|
+
if (binding.identity) return normalizeIdentity(binding.identity);
|
|
87
|
+
// Older metadata discarded whoami. Recover only the public identity, without rewriting credentials.
|
|
88
|
+
const key = revision({ id: owner.id, binding });
|
|
89
|
+
if (this.identityCache.has(key)) return this.identityCache.get(key);
|
|
90
|
+
if (this.identityInflight.has(key)) return this.identityInflight.get(key);
|
|
91
|
+
const generation = this.cacheGeneration;
|
|
92
|
+
const task = (async () => {
|
|
93
|
+
await Promise.resolve();
|
|
94
|
+
try {
|
|
95
|
+
const signal = AbortSignal.any([this.life.signal, AbortSignal.timeout(3000)]);
|
|
96
|
+
const raw = await (await this.cli(owner, binding)).whoami(signal);
|
|
97
|
+
if (raw?.logged_in !== true) return undefined;
|
|
98
|
+
const identity = normalizeIdentity({ name: raw.name, userId: raw.user_id, accountId: raw.account_id });
|
|
99
|
+
if (!this.disposed && generation === this.cacheGeneration) this.identityCache.set(key, identity);
|
|
100
|
+
return identity;
|
|
101
|
+
} catch { return undefined; }
|
|
102
|
+
finally { if (this.identityInflight.get(key) === task) this.identityInflight.delete(key); }
|
|
103
|
+
})();
|
|
104
|
+
this.identityInflight.set(key, task);
|
|
105
|
+
return task;
|
|
106
|
+
}
|
|
80
107
|
async read() {
|
|
81
108
|
const state = this.store.current;
|
|
82
109
|
if (!state) throw new Error(this.routingError || '无法读取账号元数据;原文件未覆盖');
|
|
83
110
|
const accounts = await Promise.all(state.accounts.map(async owner => {
|
|
84
111
|
const oauth = state.oauth[owner.id];
|
|
85
112
|
const hasApiKeys = {};
|
|
86
|
-
|
|
87
|
-
const
|
|
88
|
-
|
|
113
|
+
let credentialError = false;
|
|
114
|
+
const available = async ref => {
|
|
115
|
+
if (!ref) return false;
|
|
116
|
+
try { return Boolean(await this.resolveRef(ref)); }
|
|
117
|
+
catch { credentialError = true; return false; }
|
|
118
|
+
};
|
|
119
|
+
for (const plan of PLANS) hasApiKeys[plan] = oauth ? Boolean(oauth.profiles[plan]) : await available(owner.apiKeyRefs[plan]);
|
|
120
|
+
const hasQuotaKeys = oauth ? Object.keys(oauth.profiles).length > 0 : Boolean(await available(owner.accessKeyRef) && await available(owner.secretKeyRef));
|
|
121
|
+
const identity = await this.identityFor(owner, oauth);
|
|
122
|
+
const hasQuotaAccess = Object.fromEntries(PLANS.map(plan => [plan, oauth ? Boolean(oauth.profiles[plan]) : hasQuotaKeys]));
|
|
123
|
+
return { ...owner, displayName: identity?.name || (identity?.accountId ? `方舟账号 ${identity.accountId}` : owner.label),
|
|
124
|
+
...(identity ? { identity } : {}), ...(oauth ? { oauthProfiles: { ...oauth.profiles }, loggedAt: oauth.loggedAt } : {}),
|
|
125
|
+
...(credentialError ? { credentialError: '凭据服务检查失败;可编辑引用或稍后刷新重试。' } : {}),
|
|
126
|
+
hasApiKeys, hasQuotaKeys, hasQuotaAccess, authMode: oauth ? 'oauth' : 'references' };
|
|
89
127
|
}));
|
|
90
128
|
return {
|
|
91
129
|
revision: revision(state), accounts, active: { ...state.active }, enabled: { ...state.enabled }, routes: ROUTES,
|
|
92
130
|
...(this.routingError ? { routingError: this.routingError } : {}),
|
|
131
|
+
...(this.appliedAccounts ? { appliedAccounts: structuredClone(this.appliedAccounts) } : {}),
|
|
93
132
|
catalogs: state.accounts.flatMap(a => PLANS.map(plan => {
|
|
94
133
|
const status = catalogStatus(state, a.id, plan);
|
|
95
134
|
const models = getModelRows(state, a.id, plan);
|
|
@@ -105,21 +144,31 @@ export class ArkController {
|
|
|
105
144
|
})), login: this.oauth.status()
|
|
106
145
|
};
|
|
107
146
|
}
|
|
108
|
-
async bindLogin(id, rev, signal) {
|
|
147
|
+
async bindLogin(id, rev, signal, homeId) {
|
|
109
148
|
const owner = this.owner(id);
|
|
110
|
-
const cli = await this.cli(owner);
|
|
149
|
+
const cli = await this.cli(owner, homeId ? { homeId } : undefined);
|
|
111
150
|
const identity = await cli.whoami(signal);
|
|
112
151
|
if (identity?.logged_in !== true) throw new Error('CLI 未确认 OAuth 登录身份');
|
|
113
152
|
const profiles = planProfiles(await cli.status(signal));
|
|
114
153
|
if (signal.aborted || this.disposed) throw new Error('登录已取消');
|
|
115
|
-
|
|
154
|
+
const summary = normalizeIdentity({ name: identity.name, userId: identity.user_id, accountId: identity.account_id });
|
|
155
|
+
await this.store.mutate(rev, next => {
|
|
156
|
+
next.oauth[id] = { profiles, loggedAt: new Date().toISOString(), identity: summary, ...(homeId ? { homeId } : {}) };
|
|
157
|
+
// A new login may be a different cloud identity; its old remote catalog is no longer authoritative.
|
|
158
|
+
for (const plan of PLANS) delete next.catalogs[`${id}:${plan}`];
|
|
159
|
+
return next;
|
|
160
|
+
}, { signal });
|
|
116
161
|
this.clearCaches();
|
|
117
|
-
|
|
162
|
+
// Identity was already verified and committed. A routing failure is a separate, visible state.
|
|
163
|
+
try { await this.onChange(); }
|
|
164
|
+
catch { this.routingError ??= '登录身份已保存,但模型路由更新失败;此前可用路由仍保留。'; }
|
|
118
165
|
}
|
|
119
166
|
async quota(plan, id, force) {
|
|
120
167
|
assertPlan(plan); const owner = this.owner(id);
|
|
121
|
-
const
|
|
168
|
+
const binding = this.store.current.oauth[id];
|
|
169
|
+
const fingerprint = revision({ owner, binding });
|
|
122
170
|
const key = `${id}:${plan}:${fingerprint}`;
|
|
171
|
+
if (force) this.cache.delete(key);
|
|
123
172
|
const cached = this.cache.get(key);
|
|
124
173
|
if (!force && cached && Date.now() - cached.at < 60000) return structuredClone(cached.value);
|
|
125
174
|
if (this.inflight.has(key)) return this.inflight.get(key);
|
|
@@ -129,11 +178,10 @@ export class ArkController {
|
|
|
129
178
|
const base = { accountId: id, plan, updatedAt: new Date().toISOString() };
|
|
130
179
|
try {
|
|
131
180
|
let parsed;
|
|
132
|
-
const binding = this.store.current.oauth[id];
|
|
133
181
|
if (binding) {
|
|
134
182
|
const profile = binding.profiles[plan];
|
|
135
183
|
if (!profile) return { ...base, state: 'no-key', windows: [], error: '此 OAuth 账号未绑定该订阅' };
|
|
136
|
-
const cli = await this.cli(owner);
|
|
184
|
+
const cli = await this.cli(owner, binding);
|
|
137
185
|
const action = plan === 'agent-plan' ? 'usage.get_afp_usage' : 'usage.get_coding_plan_usage';
|
|
138
186
|
const raw = await cli.run(['api', action, '--params', '{}', '--profile', profile], { signal: this.life.signal });
|
|
139
187
|
// Raw OpenAPI owns the AFP daily window; usage plan intentionally omits it.
|
|
@@ -159,7 +207,18 @@ export class ArkController {
|
|
|
159
207
|
if (this.disposed) throw new Error('插件已卸载');
|
|
160
208
|
if (!request || typeof request !== 'object') throw new Error('请求格式错误');
|
|
161
209
|
const { op } = request;
|
|
162
|
-
if (op === 'read')
|
|
210
|
+
if (op === 'read') {
|
|
211
|
+
const read = this.operations.then(async () => {
|
|
212
|
+
if (await this.store.refresh()) {
|
|
213
|
+
this.clearCaches();
|
|
214
|
+
try { await this.onChange(); }
|
|
215
|
+
catch { this.routingError ??= '模型路由更新失败;设置已同步,实际路由仍为此前账号。'; }
|
|
216
|
+
}
|
|
217
|
+
return this.read();
|
|
218
|
+
});
|
|
219
|
+
this.operations = read.catch(() => {});
|
|
220
|
+
return read;
|
|
221
|
+
}
|
|
163
222
|
if (op === 'loginStatus') return this.oauth.status();
|
|
164
223
|
if (op === 'cancelLogin') return this.oauth.cancel(request.jobId);
|
|
165
224
|
if (op === 'quota') return this.quota(request.plan, request.accountId, request.force === true);
|
|
@@ -174,14 +233,18 @@ export class ArkController {
|
|
|
174
233
|
const { op, accountId, plan } = request;
|
|
175
234
|
if (op === 'startLogin') {
|
|
176
235
|
this.owner(accountId);
|
|
177
|
-
const
|
|
178
|
-
|
|
236
|
+
const homeId = randomUUID();
|
|
237
|
+
const cli = await this.cli(this.owner(accountId), { homeId });
|
|
238
|
+
return this.oauth.start({ accountId, executable: cli.executable, home: cli.home, homeId, revision: request.revision });
|
|
179
239
|
}
|
|
180
240
|
let catalog;
|
|
181
241
|
if (op === 'models') {
|
|
182
242
|
assertPlan(plan); const owner = this.owner(accountId);
|
|
183
|
-
const
|
|
184
|
-
|
|
243
|
+
const binding = this.store.current.oauth[accountId];
|
|
244
|
+
const profile = binding ? binding.profiles[plan] : owner.cliProfile;
|
|
245
|
+
if (!profile) throw new Error(binding
|
|
246
|
+
? '此 OAuth 账号未绑定该套餐;请确认个人套餐订阅后重新网页登录,填写其他 profile 不会切换身份'
|
|
247
|
+
: '请先为此账号网页登录,或填写其隔离 ArkCli profile 名称;也可继续使用本地模型快照');
|
|
185
248
|
const cli = await this.cli(owner);
|
|
186
249
|
catalog = normalizeCatalog(plan, await cli.models(plan, profile, this.life.signal));
|
|
187
250
|
}
|
package/lib/oauth.mjs
CHANGED
|
@@ -7,7 +7,7 @@ export function approvedLoginUrl(raw) {
|
|
|
7
7
|
try {
|
|
8
8
|
const url = new URL(raw);
|
|
9
9
|
if (url.protocol !== 'https:' || url.username || url.password || url.port) return undefined;
|
|
10
|
-
if (url.hostname === 'ark.volcengine.com' &&
|
|
10
|
+
if (url.hostname === 'ark.volcengine.com' && /^\/(?:region:cn-beijing\/)?arkcli\/login\/?$/.test(url.pathname)) return raw;
|
|
11
11
|
if (url.hostname === 'signin.volcengine.com' && url.pathname.startsWith('/authorize/')) return raw;
|
|
12
12
|
} catch { /* Not a URL. */ }
|
|
13
13
|
return undefined;
|
|
@@ -19,10 +19,10 @@ export class ArkOAuth {
|
|
|
19
19
|
this.current = null; this.disposed = false;
|
|
20
20
|
}
|
|
21
21
|
status() { return this.current ? structuredClone(this.current.public) : { jobId: null, state: 'idle', message: '' }; }
|
|
22
|
-
start({ accountId, executable, home, revision }) {
|
|
22
|
+
start({ accountId, executable, home, homeId, revision }) {
|
|
23
23
|
if (this.disposed) throw new Error('插件已卸载');
|
|
24
24
|
if (this.current && ACTIVE.has(this.current.public.state)) throw new Error('已有登录正在进行,请先完成或取消');
|
|
25
|
-
const job = { public: { jobId: randomUUID(), accountId, state: 'launching', message: '正在启动 ArkCli 官方 OAuth 登录窗口' }, home, revision, controller: new AbortController(), bytes: 0, tail: '' };
|
|
25
|
+
const job = { public: { jobId: randomUUID(), accountId, state: 'launching', message: '正在启动 ArkCli 官方 OAuth 登录窗口' }, home, homeId, revision, controller: new AbortController(), bytes: 0, tail: '' };
|
|
26
26
|
this.current = job;
|
|
27
27
|
job.timer = setTimeout(() => this.finish(job, 'error', '登录超时,请重新开始'), this.timeoutMs);
|
|
28
28
|
void this.run(job, executable);
|
|
@@ -69,7 +69,7 @@ export class ArkOAuth {
|
|
|
69
69
|
if (code !== 0) { this.finish(job, 'error', 'ArkCli 登录未完成;未读取或显示其原始输出'); return; }
|
|
70
70
|
job.public.state = 'verifying'; job.public.message = '正在核验登录身份与双订阅 profile';
|
|
71
71
|
try {
|
|
72
|
-
await this.onSuccess(job.public.accountId, job.revision, job.controller.signal);
|
|
72
|
+
await this.onSuccess(job.public.accountId, job.revision, job.controller.signal, job.homeId);
|
|
73
73
|
if (this.alive(job)) this.finish(job, 'success', 'OAuth 登录已完成;两套订阅分别绑定,额度状态请单独刷新');
|
|
74
74
|
} catch { this.finish(job, 'error', 'OAuth 已结束,但订阅身份核验失败或账号设置已改变;请刷新后重试'); }
|
|
75
75
|
})();
|
package/lib/state.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
2
|
-
import { mkdir, readFile, writeFile, rename } from 'node:fs/promises';
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, writeFile, rename, rm, open } from 'node:fs/promises';
|
|
3
3
|
import { dirname } from 'node:path';
|
|
4
4
|
|
|
5
5
|
export const STATE_VERSION = 2;
|
|
@@ -188,7 +188,9 @@ export function validateState(value) {
|
|
|
188
188
|
if (profile !== undefined && (typeof profile !== 'string' || profile.length > 200 || /[\x00-\x1f]/.test(profile))) throw new Error('OAuth profile 绑定格式错误');
|
|
189
189
|
if (profile) profiles[plan] = profile;
|
|
190
190
|
}
|
|
191
|
-
|
|
191
|
+
const identity = normalizeIdentity(binding.identity);
|
|
192
|
+
if (binding.homeId !== undefined && (typeof binding.homeId !== 'string' || !/^[a-f0-9-]{36}$/.test(binding.homeId))) throw new Error('OAuth 隔离目录标识错误');
|
|
193
|
+
oauth[owner.id] = { profiles, loggedAt: typeof binding.loggedAt === 'string' ? binding.loggedAt : '', ...(Object.keys(identity).length ? { identity } : {}), ...(binding.homeId ? { homeId: binding.homeId } : {}) };
|
|
192
194
|
}
|
|
193
195
|
// 版本 1 没有 enabled:有所选账号的套餐视为启用,原来未选择账号的套餐视为停用。
|
|
194
196
|
const enabled = {};
|
|
@@ -200,22 +202,71 @@ export function validateState(value) {
|
|
|
200
202
|
const modelSettings = normalizeModelSettingsMap(value.modelSettings, accounts);
|
|
201
203
|
return { version: STATE_VERSION, accounts, active, enabled, catalogs, oauth, modelSettings };
|
|
202
204
|
}
|
|
205
|
+
/** Only explicitly supported, non-secret identity fields may enter metadata or RPC. */
|
|
206
|
+
export function normalizeIdentity(value) {
|
|
207
|
+
const identity = {};
|
|
208
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return identity;
|
|
209
|
+
for (const key of ['name', 'userId', 'accountId']) {
|
|
210
|
+
const text = value[key];
|
|
211
|
+
if (typeof text === 'string' && text.trim() && text.length <= 200 && !/[\x00-\x1f\x7f]/.test(text)) identity[key] = text.trim();
|
|
212
|
+
}
|
|
213
|
+
return identity;
|
|
214
|
+
}
|
|
203
215
|
export const revision = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
204
216
|
export class StateStore {
|
|
205
|
-
constructor(path) { this.path = path; this.current = null; this.queue = Promise.resolve(); }
|
|
217
|
+
constructor(path) { this.path = path; this.current = null; this.diskRevision = null; this.queue = Promise.resolve(); }
|
|
206
218
|
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(); }
|
|
219
|
+
try { this.current = validateState(JSON.parse(await readFile(this.path, 'utf8'))); this.diskRevision = revision(this.current); }
|
|
220
|
+
catch (error) { if (error.code !== 'ENOENT') throw new Error('无法读取方舟账号状态;原文件未被覆盖'); this.current = initialState(); this.diskRevision = null; }
|
|
209
221
|
return this.current;
|
|
210
222
|
}
|
|
211
|
-
|
|
223
|
+
refresh() {
|
|
224
|
+
const operation = this.queue.then(async () => {
|
|
225
|
+
let disk = null;
|
|
226
|
+
try { disk = validateState(JSON.parse(await readFile(this.path, 'utf8'))); }
|
|
227
|
+
catch (error) { if (error.code !== 'ENOENT') throw new Error('无法读取方舟账号状态;原文件未被覆盖'); }
|
|
228
|
+
const diskRevision = disk ? revision(disk) : null;
|
|
229
|
+
if (diskRevision === this.diskRevision) return false;
|
|
230
|
+
this.current = disk ?? initialState(); this.diskRevision = diskRevision;
|
|
231
|
+
return true;
|
|
232
|
+
});
|
|
233
|
+
this.queue = operation.catch(() => {});
|
|
234
|
+
return operation;
|
|
235
|
+
}
|
|
236
|
+
mutate(expectedRevision, change, { signal } = {}) {
|
|
212
237
|
const operation = this.queue.then(async () => {
|
|
238
|
+
signal?.throwIfAborted();
|
|
213
239
|
if (expectedRevision !== revision(this.current)) throw new Error('设置已改变,请刷新后重试');
|
|
214
240
|
const next = validateState(change(structuredClone(this.current)));
|
|
215
241
|
await mkdir(dirname(this.path), { recursive: true });
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
242
|
+
signal?.throwIfAborted();
|
|
243
|
+
const lockPath = `${this.path}.lock`;
|
|
244
|
+
let lock;
|
|
245
|
+
try { lock = await open(lockPath, 'wx', 0o600); }
|
|
246
|
+
catch (error) {
|
|
247
|
+
if (error.code === 'EEXIST') throw new Error('其他实例正在写入账号设置,请稍后刷新重试;若进程异常退出,请确认无写入进程后清理状态文件旁的 .lock 文件');
|
|
248
|
+
throw error;
|
|
249
|
+
}
|
|
250
|
+
const temp = `${this.path}.${process.pid}.${randomUUID()}.tmp`;
|
|
251
|
+
try {
|
|
252
|
+
signal?.throwIfAborted();
|
|
253
|
+
let disk = null;
|
|
254
|
+
try { disk = validateState(JSON.parse(await readFile(this.path, 'utf8'))); }
|
|
255
|
+
catch (error) { if (error.code !== 'ENOENT') throw new Error('无法读取方舟账号状态;原文件未被覆盖'); }
|
|
256
|
+
if ((disk ? revision(disk) : null) !== this.diskRevision) {
|
|
257
|
+
throw new Error('设置已改变,请刷新后重试');
|
|
258
|
+
}
|
|
259
|
+
await writeFile(temp, JSON.stringify(next, null, 2) + '\n', { mode: 0o600, signal });
|
|
260
|
+
signal?.throwIfAborted();
|
|
261
|
+
await rename(temp, this.path);
|
|
262
|
+
this.diskRevision = revision(next);
|
|
263
|
+
} catch (error) {
|
|
264
|
+
await rm(temp, { force: true }).catch(() => {});
|
|
265
|
+
throw error;
|
|
266
|
+
} finally {
|
|
267
|
+
await lock.close();
|
|
268
|
+
await rm(lockPath, { force: true });
|
|
269
|
+
}
|
|
219
270
|
this.current = next;
|
|
220
271
|
return next;
|
|
221
272
|
});
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-volcengine-provider",
|
|
3
3
|
"displayName": "火山方舟 Provider",
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.2",
|
|
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",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"license": "MIT",
|
|
15
15
|
"publishConfig": {"access": "public", "registry": "https://registry.npmjs.org/"},
|
|
16
16
|
"engines": {"node": ">=22.19.0"},
|
|
17
|
-
"scripts": {"build": "node scripts/build.mjs", "test": "node --test test/*.test.mjs", "check": "node scripts/check.mjs && node
|
|
17
|
+
"scripts": {"build": "node scripts/build.mjs", "test": "node scripts/build.mjs && node --test test/*.test.mjs", "check": "node scripts/check.mjs && node scripts/build.mjs && node --test test/*.test.mjs"},
|
|
18
18
|
"peerDependencies": {
|
|
19
19
|
"@deepseek-ai/cordis": "^4.0.5",
|
|
20
20
|
"@deepseek-ai/schemastery": "^3.18.4",
|