dsh-volcengine-provider 0.2.15 → 0.2.17
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 +6 -2
- package/docs/changelog.md +15 -3
- package/docs/client-media-preview.png +0 -0
- package/docs/client-media-settings-preview.png +0 -0
- package/docs/client-settings-preview-dark.png +0 -0
- package/docs/client-settings-preview-empty.png +0 -0
- package/docs/client-settings-preview-mobile-dark.png +0 -0
- package/docs/client-settings-preview-models.png +0 -0
- package/docs/client-settings-preview.png +0 -0
- package/docs/development.md +3 -1
- package/docs/media-generation.md +71 -0
- package/docs/model-capabilities.md +9 -9
- package/docs/usage.md +25 -4
- package/docs/validation.md +40 -0
- package/lib/catalog-snapshot.json +28 -14
- package/lib/catalog.mjs +8 -1
- package/lib/cli.mjs +44 -1
- package/lib/client.js +748 -76
- package/lib/index.mjs +38 -5
- package/lib/manager.mjs +288 -35
- package/lib/media-config.mjs +39 -0
- package/lib/media-image-route.mjs +110 -0
- package/lib/media-image.mjs +212 -0
- package/lib/media.mjs +263 -0
- package/lib/oauth-expiry.mjs +47 -0
- package/lib/snapshot.mjs +105 -0
- package/lib/state.mjs +5 -2
- package/package.json +18 -2
package/lib/index.mjs
CHANGED
|
@@ -15,6 +15,9 @@ import { arkRemote } from './remote.mjs';
|
|
|
15
15
|
import { captureModelDefaults, getModelDefaults, applyModelDefaults, describeModelDefaults } from './model-defaults.mjs';
|
|
16
16
|
import { createAdapterLease, leasedStream } from './adapter-lease.mjs';
|
|
17
17
|
import { createArkAdapter } from './ark-adapter.mjs';
|
|
18
|
+
import { mediaToolEnabled } from './media.mjs';
|
|
19
|
+
import { registerVolcImagineTool } from './media-image.mjs';
|
|
20
|
+
import { registerImageFileRoute } from './media-image-route.mjs';
|
|
18
21
|
|
|
19
22
|
export const name = 'dsh-volcengine-provider';
|
|
20
23
|
export const inject = ['llm'];
|
|
@@ -152,11 +155,41 @@ export function apply(ctx, config) {
|
|
|
152
155
|
}
|
|
153
156
|
ctx.inject(['typert'], scope => scope.effect(() => scope.typert.register({ package: arkRemote.package, face: 'host', schemas: [], model: { services: [], events: [], objects: [] }, invocations: arkRemote.descriptors })));
|
|
154
157
|
ctx.plugin(ArkService);
|
|
155
|
-
ctx.on('credentials/reference-updated', () => controller.clearCaches());
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
158
|
+
ctx.on('credentials/reference-updated', () => controller.clearCaches({ quotas: true }));
|
|
159
|
+
// ── 图片生成工具与原始文件回源:风险确认前置,原始字节不经图片规范化 ──
|
|
160
|
+
const mediaEnabled = key => () => {
|
|
161
|
+
if (controller.disposed) return false;
|
|
162
|
+
try { return mediaToolEnabled(controller.media(), key); }
|
|
163
|
+
catch { return false; }
|
|
164
|
+
};
|
|
165
|
+
const toolContext = {
|
|
166
|
+
enabled: mediaEnabled,
|
|
167
|
+
credentials: accountId => controller.mediaContext().credentials(accountId),
|
|
168
|
+
resolveAttachments: () => ctx.get('attachments')
|
|
169
|
+
};
|
|
170
|
+
ctx.inject(['tools'], toolCtx => toolCtx.effect(() => {
|
|
171
|
+
const disposeImagine = registerVolcImagineTool(toolCtx, {
|
|
172
|
+
enabled: mediaEnabled('imageTool'),
|
|
173
|
+
credentials: toolContext.credentials,
|
|
174
|
+
defaultModel: () => controller.media().imageModel,
|
|
175
|
+
resolveAttachments: toolContext.resolveAttachments
|
|
176
|
+
});
|
|
177
|
+
return disposeImagine;
|
|
178
|
+
}, '火山方舟图片工具'));
|
|
179
|
+
ctx.inject(['webServer'], webCtx => webCtx.effect(() => registerImageFileRoute(webCtx, {
|
|
180
|
+
resolveAttachments: toolContext.resolveAttachments
|
|
181
|
+
}), '火山方舟图片原文件路由'));
|
|
182
|
+
controller.ready = controller.store.load()
|
|
183
|
+
.then(async () => {
|
|
184
|
+
// 中间层先于采集:上次进程的额度快照在首屏就能读,采集失败也不影响设置页。
|
|
185
|
+
await controller.quotaSnapshots.load();
|
|
186
|
+
await queueRoutingUpdate();
|
|
187
|
+
controller.startCollector();
|
|
188
|
+
})
|
|
189
|
+
.catch(() => {
|
|
190
|
+
controller.routingError ??= '初始化失败:请检查账号元数据和模型缓存;原文件未覆盖。';
|
|
191
|
+
ctx.logger.error('火山方舟 Provider 初始化失败;请在设置页查看状态');
|
|
192
|
+
});
|
|
160
193
|
ctx.on('dispose', async () => {
|
|
161
194
|
controller.dispose();
|
|
162
195
|
if (registration) registration();
|
package/lib/manager.mjs
CHANGED
|
@@ -6,6 +6,15 @@ import { catalogStatus, effectiveModel, getModelRows, normalizeCatalog, override
|
|
|
6
6
|
import { ArkCli, locateCli } from './cli.mjs';
|
|
7
7
|
import { ArkOAuth } from './oauth.mjs';
|
|
8
8
|
import { fetchUsage, parseAgentUsage, parseCodingUsage } from './quota.mjs';
|
|
9
|
+
import { defaultMediaState, mediaToolEnabled, normalizeMediaState } from './media.mjs';
|
|
10
|
+
import { QuotaSnapshotStore } from './snapshot.mjs';
|
|
11
|
+
import { readOAuthExpiry } from './oauth-expiry.mjs';
|
|
12
|
+
|
|
13
|
+
// 中间层参数:额度由 Host 定期采集,Client 只读快照。
|
|
14
|
+
const QUOTA_TTL = 60000;
|
|
15
|
+
const QUOTA_BACKOFF_MAX = 8;
|
|
16
|
+
const CATALOG_TTL = 15 * 60000;
|
|
17
|
+
const COLLECT_TICK = 15000;
|
|
9
18
|
|
|
10
19
|
export function planProfiles(status) {
|
|
11
20
|
if (!Array.isArray(status?.profiles_summary)) throw new Error('CLI 身份摘要缺少 profiles_summary,请核对 ArkCli 版本');
|
|
@@ -35,6 +44,13 @@ export class ArkController {
|
|
|
35
44
|
this.life = new AbortController(); this.disposed = false; this.cache = new Map(); this.inflight = new Map();
|
|
36
45
|
this.inferenceCache = new Map(); this.inferenceInflight = new Map(); this.cacheGeneration = 0;
|
|
37
46
|
this.identityCache = new Map(); this.identityInflight = new Map();
|
|
47
|
+
this.expiryCache = new Map();
|
|
48
|
+
// 失败负缓存与按账号串行锁:凭据/登录失效时避免反复 spawn ArkCli 拖慢宿主。
|
|
49
|
+
this.inferenceFailure = new Map(); this.executablePromise = undefined; this.quotaQueue = new Map();
|
|
50
|
+
// 中间层:Host 定期采集的额度快照(内存 + 同目录原子落盘),Client 只读不触发采集。
|
|
51
|
+
this.quotaSnapshots = new QuotaSnapshotStore({ path: join(dirname(statePath), 'quota-snapshot.json') });
|
|
52
|
+
this.quotaFailures = new Map(); this.catalogFailures = new Map(); this.catalogInflight = new Map();
|
|
53
|
+
this.collectorTimer = null; this.collecting = false;
|
|
38
54
|
this.oauth = new ArkOAuth({ spawn: spawnImpl, onSuccess: (id, rev, signal, homeId) => this.bindLogin(id, rev, signal, homeId) });
|
|
39
55
|
this.onChange = async () => {}; this.operations = Promise.resolve();
|
|
40
56
|
}
|
|
@@ -44,16 +60,44 @@ export class ArkController {
|
|
|
44
60
|
if (!owner) throw new Error('账号不存在');
|
|
45
61
|
return owner;
|
|
46
62
|
}
|
|
47
|
-
|
|
63
|
+
/** 账号隔离 CLI home:新绑定用会话目录,旧绑定沿用账号根目录。 */
|
|
64
|
+
homeFor(owner, binding = this.store.current.oauth?.[owner.id]) {
|
|
48
65
|
const root = join(dirname(this.store.path), 'accounts', owner.id);
|
|
49
|
-
|
|
66
|
+
return binding?.homeId ? join(root, 'sessions', binding.homeId) : root;
|
|
67
|
+
}
|
|
68
|
+
async cli(owner, binding = this.store.current.oauth?.[owner.id]) {
|
|
69
|
+
const home = this.homeFor(owner, binding);
|
|
50
70
|
if (this.cliFactory) return this.cliFactory(owner, home);
|
|
51
|
-
|
|
71
|
+
// 定位可执行文件的 PATH/require 探测只做一次;失败不缓存,保证装上 CLI 后能恢复。
|
|
72
|
+
this.executablePromise ??= locateCli(this.arkCliPath);
|
|
73
|
+
let executable;
|
|
74
|
+
try { executable = await this.executablePromise; }
|
|
75
|
+
catch (error) { this.executablePromise = undefined; throw error; }
|
|
76
|
+
return new ArkCli({ executable, home });
|
|
77
|
+
}
|
|
78
|
+
/** 同一账号的额度查询串行执行:两个套餐同时刷新时不并发 spawn 多个 ArkCli。 */
|
|
79
|
+
async withQuotaLock(id, task) {
|
|
80
|
+
const previous = this.quotaQueue.get(id) ?? Promise.resolve();
|
|
81
|
+
const next = previous.then(task, task);
|
|
82
|
+
const settled = next.then(() => {}, () => {});
|
|
83
|
+
this.quotaQueue.set(id, settled);
|
|
84
|
+
try { return await next; }
|
|
85
|
+
finally { if (this.quotaQueue.get(id) === settled) this.quotaQueue.delete(id); }
|
|
52
86
|
}
|
|
53
|
-
|
|
87
|
+
/**
|
|
88
|
+
* 清身份与推理缓存。额度快照默认保留(采集器会按 TTL 刷新);
|
|
89
|
+
* 凭据引用变化、重新登录、卸载这类身份级事件传 quotas: true 一并作废。
|
|
90
|
+
*/
|
|
91
|
+
clearCaches({ quotas = false, persist = true } = {}) {
|
|
54
92
|
this.cacheGeneration++;
|
|
55
93
|
this.cache.clear(); this.inflight.clear(); this.inferenceCache.clear(); this.inferenceInflight.clear();
|
|
56
|
-
this.identityCache.clear(); this.identityInflight.clear();
|
|
94
|
+
this.identityCache.clear(); this.identityInflight.clear(); this.inferenceFailure.clear();
|
|
95
|
+
this.expiryCache.clear();
|
|
96
|
+
if (quotas) {
|
|
97
|
+
this.quotaSnapshots.entries.clear();
|
|
98
|
+
// 卸载时只清内存,不再排队落盘:避免与调用方删除数据目录竞争。
|
|
99
|
+
if (persist) this.quotaSnapshots.save();
|
|
100
|
+
}
|
|
57
101
|
}
|
|
58
102
|
async inferenceKey(owner, plan, selection = { binding: this.store.current.oauth?.[owner.id] }) {
|
|
59
103
|
if (this.disposed) throw new Error('插件已卸载');
|
|
@@ -62,6 +106,9 @@ export class ArkController {
|
|
|
62
106
|
const profile = binding.profiles[plan];
|
|
63
107
|
if (!profile) return undefined; // Never borrow a different identity/key pool after OAuth binding.
|
|
64
108
|
const cacheKey = revision({ accountId: owner.id, plan, profile, loggedAt: binding.loggedAt, homeId: binding.homeId });
|
|
109
|
+
// 同一失败在 20 秒内直接复用:登录/协议失效时不要再为每条请求 spawn 一次 ArkCli。
|
|
110
|
+
const failure = this.inferenceFailure.get(cacheKey);
|
|
111
|
+
if (failure && Date.now() - failure.at < 20000) throw failure.error;
|
|
65
112
|
const cached = this.inferenceCache.get(cacheKey);
|
|
66
113
|
if (cached && Date.now() - cached.at < 30000) return cached.value;
|
|
67
114
|
if (this.inferenceInflight.has(cacheKey)) return this.inferenceInflight.get(cacheKey);
|
|
@@ -73,6 +120,15 @@ export class ArkController {
|
|
|
73
120
|
if (this.disposed || this.life.signal.aborted) throw new Error('插件已卸载');
|
|
74
121
|
if (generation === this.cacheGeneration) this.inferenceCache.set(cacheKey, { at: Date.now(), value: key });
|
|
75
122
|
return key;
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if (this.disposed || this.life.signal.aborted) throw error;
|
|
125
|
+
const wrapped = new Error(error?.arkKind === 'auth'
|
|
126
|
+
? '方舟登录凭据需要重新确认:请在插件设置页重新网页登录(ArkCli SSO)后重试'
|
|
127
|
+
: '方舟推理凭据获取失败:请检查登录状态、网络与 ArkCli 版本');
|
|
128
|
+
wrapped.cause = error;
|
|
129
|
+
wrapped.arkKind = error?.arkKind ?? 'unknown';
|
|
130
|
+
if (generation === this.cacheGeneration) this.inferenceFailure.set(cacheKey, { at: Date.now(), error: wrapped });
|
|
131
|
+
throw wrapped;
|
|
76
132
|
} finally { if (this.inferenceInflight.get(cacheKey) === task) this.inferenceInflight.delete(cacheKey); }
|
|
77
133
|
})();
|
|
78
134
|
this.inferenceInflight.set(cacheKey, task);
|
|
@@ -121,7 +177,7 @@ export class ArkController {
|
|
|
121
177
|
const identity = await this.identityFor(owner, oauth);
|
|
122
178
|
const hasQuotaAccess = Object.fromEntries(PLANS.map(plan => [plan, oauth ? Boolean(oauth.profiles[plan]) : hasQuotaKeys]));
|
|
123
179
|
return { ...owner, displayName: identity?.name || (identity?.accountId ? `方舟账号 ${identity.accountId}` : owner.label),
|
|
124
|
-
...(identity ? { identity } : {}), ...(oauth ? { oauthProfiles: { ...oauth.profiles }, loggedAt: oauth.loggedAt } : {}),
|
|
180
|
+
...(identity ? { identity } : {}), ...(oauth ? { oauthProfiles: { ...oauth.profiles }, loggedAt: oauth.loggedAt, oauthExpiresAt: await this.oauthExpiry(owner, oauth) } : {}),
|
|
125
181
|
...(credentialError ? { credentialError: '凭据服务检查失败;可编辑引用或稍后刷新重试。' } : {}),
|
|
126
182
|
hasApiKeys, hasQuotaKeys, hasQuotaAccess, authMode: oauth ? 'oauth' : 'references' };
|
|
127
183
|
}));
|
|
@@ -141,9 +197,25 @@ export class ArkController {
|
|
|
141
197
|
...(status.updatedAt ? { updatedAt: status.updatedAt } : {}),
|
|
142
198
|
models
|
|
143
199
|
};
|
|
144
|
-
})), login: this.oauth.status()
|
|
200
|
+
})), login: this.oauth.status(),
|
|
201
|
+
media: { ...state.media },
|
|
202
|
+
// 中间层:额度快照随 read 一起下发,设置页首屏不需要再发查询请求。
|
|
203
|
+
quotas: this.snapshotView().quotas
|
|
145
204
|
};
|
|
146
205
|
}
|
|
206
|
+
/**
|
|
207
|
+
* OAuth 登录态到期时间(ISO 字符串):只读 refresh_token 的 exp 元数据,按绑定缓存;
|
|
208
|
+
* 官方 SSO 续期不延长 refresh_token,该值即登录态权威到期。未知时 null。
|
|
209
|
+
*/
|
|
210
|
+
async oauthExpiry(owner, binding) {
|
|
211
|
+
if (!binding) return null;
|
|
212
|
+
const key = revision({ id: owner.id, homeId: binding.homeId ?? null, loggedAt: binding.loggedAt });
|
|
213
|
+
if (this.expiryCache.has(key)) return this.expiryCache.get(key);
|
|
214
|
+
const expiry = await readOAuthExpiry(this.homeFor(owner, binding));
|
|
215
|
+
const value = expiry === null ? null : new Date(expiry).toISOString();
|
|
216
|
+
if (!this.disposed) this.expiryCache.set(key, value);
|
|
217
|
+
return value;
|
|
218
|
+
}
|
|
147
219
|
async bindLogin(id, rev, signal, homeId) {
|
|
148
220
|
const owner = this.owner(id);
|
|
149
221
|
const cli = await this.cli(owner, homeId ? { homeId } : undefined);
|
|
@@ -158,50 +230,194 @@ export class ArkController {
|
|
|
158
230
|
for (const plan of PLANS) delete next.catalogs[`${id}:${plan}`];
|
|
159
231
|
return next;
|
|
160
232
|
}, { signal });
|
|
161
|
-
this.clearCaches();
|
|
233
|
+
this.clearCaches({ quotas: true });
|
|
162
234
|
// Identity was already verified and committed. A routing failure is a separate, visible state.
|
|
163
235
|
try { await this.onChange(); }
|
|
164
236
|
catch { this.routingError ??= '登录身份已保存,但模型路由更新失败;此前可用路由仍保留。'; }
|
|
165
237
|
}
|
|
238
|
+
/** 账号+套餐的采集指纹:身份、绑定或凭据引用变化后旧快照自动失效。 */
|
|
239
|
+
quotaFingerprint(id) {
|
|
240
|
+
const owner = this.store.current?.accounts.find(a => a.id === id);
|
|
241
|
+
if (!owner) return null;
|
|
242
|
+
return revision({ owner, binding: this.store.current.oauth?.[id] });
|
|
243
|
+
}
|
|
244
|
+
/** 中间层视图:Client 只读这里,不触发任何上游请求。 */
|
|
245
|
+
snapshotView() {
|
|
246
|
+
const quotas = {};
|
|
247
|
+
for (const [key, entry] of Object.entries(this.quotaSnapshots.map())) {
|
|
248
|
+
const [id] = key.split(':');
|
|
249
|
+
const fingerprint = this.quotaFingerprint(id);
|
|
250
|
+
if (!fingerprint) continue;
|
|
251
|
+
if (!this.quotaSnapshots.get(key, fingerprint)) continue;
|
|
252
|
+
quotas[key] = entry;
|
|
253
|
+
}
|
|
254
|
+
return { revision: revision(this.store.current), quotas };
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Client 读额度:有中间层快照就直接返回,过期只在后台补采,读取本身不等上游。
|
|
258
|
+
* force=true 才清掉快照并立即重采(对应「刷新额度」)。
|
|
259
|
+
*/
|
|
166
260
|
async quota(plan, id, force) {
|
|
167
|
-
assertPlan(plan);
|
|
261
|
+
assertPlan(plan); this.owner(id);
|
|
262
|
+
const key = `${id}:${plan}`;
|
|
263
|
+
const fingerprint = this.quotaFingerprint(id);
|
|
264
|
+
if (force) this.quotaSnapshots.delete(key);
|
|
265
|
+
const entry = force ? undefined : this.quotaSnapshots.get(key, fingerprint);
|
|
266
|
+
if (entry) {
|
|
267
|
+
if (Date.now() - entry.at >= QUOTA_TTL) void this.collectQuota(plan, id).catch(() => {});
|
|
268
|
+
return structuredClone(entry.value);
|
|
269
|
+
}
|
|
270
|
+
// 手动刷新要能突破退避:force 时忽略失败退避,立即重采。
|
|
271
|
+
return this.collectQuota(plan, id, { force });
|
|
272
|
+
}
|
|
273
|
+
/** 取上次成功值作底:刷新失败时保留窗口,只附加失败原因。 */
|
|
274
|
+
mergeQuotaSnapshot(key, fingerprint, value) {
|
|
275
|
+
const previous = this.quotaSnapshots.get(key, fingerprint)?.value;
|
|
276
|
+
if (value.state !== 'ok' && previous?.state === 'ok' && Array.isArray(previous.windows) && previous.windows.length) {
|
|
277
|
+
return { ...previous, refreshError: value.error ?? '额度更新失败', errorKind: value.errorKind, refreshFailedAt: value.updatedAt };
|
|
278
|
+
}
|
|
279
|
+
return value;
|
|
280
|
+
}
|
|
281
|
+
/** 真正拉取一次额度并写入中间层;失败按次数退避,避免登录失效时反复 spawn CLI。 */
|
|
282
|
+
collectQuota(plan, id, { force = false } = {}) {
|
|
283
|
+
assertPlan(plan);
|
|
284
|
+
const owner = this.owner(id);
|
|
168
285
|
const binding = this.store.current.oauth[id];
|
|
169
|
-
const fingerprint =
|
|
170
|
-
const key = `${id}:${plan}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
286
|
+
const fingerprint = this.quotaFingerprint(id);
|
|
287
|
+
const key = `${id}:${plan}`;
|
|
288
|
+
const running = this.inflight.get(key);
|
|
289
|
+
if (running) return running;
|
|
290
|
+
const failure = this.quotaFailures.get(key);
|
|
291
|
+
// 退避期内不重试(手动刷新例外):没有快照时返回上次失败结论,也不 spawn CLI。
|
|
292
|
+
if (!force && failure && failure.until > Date.now()) {
|
|
293
|
+
const cached = this.quotaSnapshots.get(key, fingerprint)?.value ?? failure.value;
|
|
294
|
+
if (cached) return Promise.resolve(structuredClone(cached));
|
|
295
|
+
}
|
|
296
|
+
const task = this.withQuotaLock(id, async () => {
|
|
177
297
|
await Promise.resolve();
|
|
298
|
+
let value;
|
|
178
299
|
const base = { accountId: id, plan, updatedAt: new Date().toISOString() };
|
|
179
300
|
try {
|
|
180
301
|
let parsed;
|
|
181
302
|
if (binding) {
|
|
182
303
|
const profile = binding.profiles[plan];
|
|
183
|
-
if (!profile)
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
304
|
+
if (!profile) value = { ...base, state: 'no-key', windows: [], error: '此 OAuth 账号未绑定该订阅' };
|
|
305
|
+
else {
|
|
306
|
+
const cli = await this.cli(owner, binding);
|
|
307
|
+
const action = plan === 'agent-plan' ? 'usage.get_afp_usage' : 'usage.get_coding_plan_usage';
|
|
308
|
+
// 额度查询是后台刷新:给比默认更短的超时,避免 CLI 卡住时占着账号串行锁。
|
|
309
|
+
const raw = await cli.run(['api', action, '--params', '{}', '--profile', profile], { signal: this.life.signal, timeout: 15000 });
|
|
310
|
+
// Raw OpenAPI owns the AFP daily window; usage plan intentionally omits it.
|
|
311
|
+
const payload = plan === 'agent-plan' && raw && !raw.Result && ['AFPFiveHour', 'AFPWeekly', 'AFPMonthly', 'AFPDaily'].some(field => Object.hasOwn(raw, field)) ? { Result: raw } : raw;
|
|
312
|
+
parsed = (plan === 'agent-plan' ? parseAgentUsage : parseCodingUsage)(payload);
|
|
313
|
+
}
|
|
190
314
|
} else {
|
|
191
315
|
const accessKeyId = owner.accessKeyRef ? await this.resolveRef(owner.accessKeyRef) : undefined;
|
|
192
316
|
const secretAccessKey = owner.secretKeyRef ? await this.resolveRef(owner.secretKeyRef) : undefined;
|
|
193
|
-
if (!accessKeyId || !secretAccessKey)
|
|
194
|
-
parsed = await fetchUsage(plan, { accessKeyId, secretAccessKey }, { ...(this.fetchImpl ? { fetchImpl: this.fetchImpl } : {}), signal: this.life.signal });
|
|
317
|
+
if (!accessKeyId || !secretAccessKey) value = { ...base, state: 'no-key', windows: [], error: '额度查询需要 IAM AK/SK,不是推理 API Key;也可使用网页登录' };
|
|
318
|
+
else parsed = await fetchUsage(plan, { accessKeyId, secretAccessKey }, { ...(this.fetchImpl ? { fetchImpl: this.fetchImpl } : {}), signal: this.life.signal });
|
|
319
|
+
}
|
|
320
|
+
if (!value) {
|
|
321
|
+
const { plan: planName, ...usage } = parsed;
|
|
322
|
+
value = { ...base, state: parsed.windows.length ? 'ok' : 'error', ...usage, ...(planName ? { planName } : {}), ...(!parsed.windows.length ? { error: '接口未返回可展示的额度窗口;未确认订阅或额度状态' } : {}) };
|
|
323
|
+
}
|
|
324
|
+
} catch (error) {
|
|
325
|
+
// 登录/协议失效时给出可操作结论;失败也进中间层与退避表,轮询重试不再反复 spawn ArkCli。
|
|
326
|
+
const kind = error?.arkKind ?? 'unknown';
|
|
327
|
+
value = {
|
|
328
|
+
...base,
|
|
329
|
+
state: kind === 'auth' ? 'no-key' : 'error',
|
|
330
|
+
windows: [],
|
|
331
|
+
errorKind: kind,
|
|
332
|
+
error: kind === 'auth'
|
|
333
|
+
? 'OAuth 登录凭据需要重新确认:请在账号区重新网页登录(ArkCli SSO)后重试'
|
|
334
|
+
: kind === 'network'
|
|
335
|
+
? '额度查询超时或网络不可用;稍后会自动重试'
|
|
336
|
+
: '额度读取失败;请检查该账号的鉴权、权限、网络及 CLI 版本'
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
const merged = this.mergeQuotaSnapshot(key, fingerprint, value);
|
|
340
|
+
if (!this.disposed) this.quotaSnapshots.set(key, fingerprint, merged);
|
|
341
|
+
if (merged.state === 'ok') this.quotaFailures.delete(key);
|
|
342
|
+
else {
|
|
343
|
+
const count = Math.min((this.quotaFailures.get(key)?.count ?? 0) + 1, 3);
|
|
344
|
+
this.quotaFailures.set(key, { count, until: Date.now() + QUOTA_TTL * Math.min(2 ** count, QUOTA_BACKOFF_MAX), value: structuredClone(merged) });
|
|
345
|
+
}
|
|
346
|
+
if (this.inflight.get(key) === task) this.inflight.delete(key);
|
|
347
|
+
return structuredClone(merged);
|
|
348
|
+
});
|
|
349
|
+
this.inflight.set(key, task);
|
|
350
|
+
return task;
|
|
351
|
+
}
|
|
352
|
+
/** 采集模型目录并写回状态文件;失败退避,冲突交给下一轮重试。 */
|
|
353
|
+
collectCatalog(plan, id) {
|
|
354
|
+
assertPlan(plan);
|
|
355
|
+
const owner = this.owner(id);
|
|
356
|
+
const binding = this.store.current.oauth[id];
|
|
357
|
+
const profile = binding ? binding.profiles[plan] : owner.cliProfile;
|
|
358
|
+
const key = `${id}:${plan}`;
|
|
359
|
+
if (!profile) return Promise.resolve(undefined);
|
|
360
|
+
const running = this.catalogInflight.get(key);
|
|
361
|
+
if (running) return running;
|
|
362
|
+
const failure = this.catalogFailures.get(key);
|
|
363
|
+
if (failure && failure.until > Date.now()) return Promise.resolve(undefined);
|
|
364
|
+
const task = (async () => {
|
|
365
|
+
try {
|
|
366
|
+
const catalog = normalizeCatalog(plan, await (await this.cli(owner)).models(plan, profile, this.life.signal));
|
|
367
|
+
if (this.disposed) return undefined;
|
|
368
|
+
// 采集写入可能撞上用户编辑:跳过后下一轮再试,不覆盖别人刚保存的设置。
|
|
369
|
+
await this.store.mutate(revision(this.store.current), next => { next.catalogs[key] = catalog; return next; });
|
|
370
|
+
this.catalogFailures.delete(key);
|
|
371
|
+
try { await this.onChange(); }
|
|
372
|
+
catch { this.routingError ??= '模型路由更新失败;设置已同步,实际路由仍为此前账号。'; }
|
|
373
|
+
return catalog;
|
|
374
|
+
} catch (error) {
|
|
375
|
+
// 与用户编辑撞 revision 不是故障:跳过这一轮,不进入长退避。
|
|
376
|
+
if (!/设置已改变/.test(String(error?.message ?? ''))) {
|
|
377
|
+
const count = Math.min((this.catalogFailures.get(key)?.count ?? 0) + 1, 4);
|
|
378
|
+
this.catalogFailures.set(key, { count, until: Date.now() + CATALOG_TTL * Math.min(2 ** (count - 1), 4) });
|
|
195
379
|
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
if (!this.disposed && generation === this.cacheGeneration) this.cache.set(key, { at: Date.now(), value });
|
|
199
|
-
return structuredClone(value);
|
|
200
|
-
} catch {
|
|
201
|
-
return { ...base, state: 'error', windows: [], error: '额度读取失败;请检查该账号的鉴权、权限、网络及 CLI 版本' };
|
|
202
|
-
} finally { if (this.inflight.get(key) === task) this.inflight.delete(key); }
|
|
380
|
+
throw error;
|
|
381
|
+
} finally { if (this.catalogInflight.get(key) === task) this.catalogInflight.delete(key); }
|
|
203
382
|
})();
|
|
204
|
-
this.
|
|
383
|
+
this.catalogInflight.set(key, task);
|
|
384
|
+
return task;
|
|
385
|
+
}
|
|
386
|
+
/** 一轮采集:只处理已启用且有选中账号的套餐;额度每 QUOTA_TTL、目录每 CATALOG_TTL 刷新。 */
|
|
387
|
+
async collectOnce() {
|
|
388
|
+
if (this.disposed || this.collecting || !this.store.current) return;
|
|
389
|
+
this.collecting = true;
|
|
390
|
+
try {
|
|
391
|
+
const state = this.store.current;
|
|
392
|
+
const jobs = [];
|
|
393
|
+
for (const plan of PLANS) {
|
|
394
|
+
if (state.enabled?.[plan] === false) continue;
|
|
395
|
+
const id = state.active?.[plan];
|
|
396
|
+
if (!id || !state.accounts.some(a => a.id === id)) continue;
|
|
397
|
+
const fingerprint = this.quotaFingerprint(id);
|
|
398
|
+
const quota = this.quotaSnapshots.get(`${id}:${plan}`, fingerprint);
|
|
399
|
+
if (!quota || Date.now() - quota.at >= QUOTA_TTL) jobs.push(this.collectQuota(plan, id).catch(() => {}));
|
|
400
|
+
const catalog = state.catalogs?.[`${id}:${plan}`];
|
|
401
|
+
const updatedAt = catalog?.updatedAt ? Date.parse(catalog.updatedAt) : NaN;
|
|
402
|
+
if (!Number.isFinite(updatedAt) || Date.now() - updatedAt >= CATALOG_TTL) jobs.push(this.collectCatalog(plan, id).catch(() => {}));
|
|
403
|
+
}
|
|
404
|
+
this.quotaSnapshots.prune(key => {
|
|
405
|
+
const [id] = key.split(':');
|
|
406
|
+
return Boolean(this.quotaFingerprint(id));
|
|
407
|
+
});
|
|
408
|
+
await Promise.allSettled(jobs);
|
|
409
|
+
} finally { this.collecting = false; }
|
|
410
|
+
}
|
|
411
|
+
/** 启动后台采集;与设置页是否打开无关。 */
|
|
412
|
+
startCollector() {
|
|
413
|
+
if (this.collectorTimer || this.disposed) return;
|
|
414
|
+
void this.collectOnce();
|
|
415
|
+
this.collectorTimer = setInterval(() => { void this.collectOnce(); }, COLLECT_TICK);
|
|
416
|
+
if (typeof this.collectorTimer.unref === 'function') this.collectorTimer.unref();
|
|
417
|
+
}
|
|
418
|
+
stopCollector() {
|
|
419
|
+
if (this.collectorTimer) clearInterval(this.collectorTimer);
|
|
420
|
+
this.collectorTimer = null;
|
|
205
421
|
}
|
|
206
422
|
async invoke(request) {
|
|
207
423
|
if (this.disposed) throw new Error('插件已卸载');
|
|
@@ -220,6 +436,8 @@ export class ArkController {
|
|
|
220
436
|
return read;
|
|
221
437
|
}
|
|
222
438
|
if (op === 'loginStatus') return this.oauth.status();
|
|
439
|
+
// 轻量读取中间层:只读内存快照与状态 revision,不触发任何上游请求。
|
|
440
|
+
if (op === 'snapshots') return this.snapshotView();
|
|
223
441
|
if (op === 'cancelLogin') return this.oauth.cancel(request.jobId);
|
|
224
442
|
if (op === 'submitLoginCode') return this.oauth.submitCode(request.jobId, request.code);
|
|
225
443
|
if (op === 'quota') return this.quota(request.plan, request.accountId, request.force === true);
|
|
@@ -307,10 +525,45 @@ export class ArkController {
|
|
|
307
525
|
for (const id of overrideKeys(request.modelId)) delete bucket[id];
|
|
308
526
|
if (Object.keys(bucket).length) next.modelSettings[key] = bucket; else delete next.modelSettings[key];
|
|
309
527
|
}
|
|
528
|
+
else if (op === 'setMedia') {
|
|
529
|
+
next.media = normalizeMediaState({
|
|
530
|
+
...next.media,
|
|
531
|
+
...(request.riskAcknowledged !== undefined ? { riskAcknowledged: request.riskAcknowledged === true } : {}),
|
|
532
|
+
...(request.imageTool !== undefined ? { imageTool: request.imageTool === true } : {}),
|
|
533
|
+
...(request.imageModel !== undefined ? { imageModel: request.imageModel } : {})
|
|
534
|
+
});
|
|
535
|
+
}
|
|
310
536
|
else throw new Error('未知操作');
|
|
311
537
|
return next;
|
|
312
538
|
});
|
|
313
539
|
this.clearCaches(); await this.onChange(); return this.read();
|
|
314
540
|
}
|
|
315
|
-
|
|
541
|
+
media() {
|
|
542
|
+
return this.store.current?.media ?? defaultMediaState();
|
|
543
|
+
}
|
|
544
|
+
mediaEnabled(key) {
|
|
545
|
+
return mediaToolEnabled(this.media(), key);
|
|
546
|
+
}
|
|
547
|
+
/** 媒体工具运行时上下文:附件服务、账号清单与推理凭据。 */
|
|
548
|
+
mediaContext() {
|
|
549
|
+
const state = this.store.current;
|
|
550
|
+
const accountIds = state ? state.accounts.map(a => a.id) : [];
|
|
551
|
+
return {
|
|
552
|
+
media: this.media(),
|
|
553
|
+
accountIds,
|
|
554
|
+
credentials: async accountId => {
|
|
555
|
+
const current = this.store.current;
|
|
556
|
+
if (!current) throw new Error('账号状态不可用');
|
|
557
|
+
const active = current.active['agent-plan'];
|
|
558
|
+
if (active === null || active === undefined) throw new Error('Agent Plan 未选择账号,请先在设置页选择账号');
|
|
559
|
+
const id = accountId ?? active;
|
|
560
|
+
const owner = this.owner(id);
|
|
561
|
+
const binding = current.oauth[id];
|
|
562
|
+
const key = await this.inferenceKey(owner, 'agent-plan', { binding });
|
|
563
|
+
if (!key) throw new Error(binding ? '此账号未绑定 Agent Plan profile' : `凭据引用 ${owner.apiKeyRefs['agent-plan']} 无法解析`);
|
|
564
|
+
return { accountId: id, key };
|
|
565
|
+
}
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
dispose() { this.disposed = true; this.stopCollector(); this.oauth.dispose(); this.life.abort(); this.clearCaches({ quotas: true, persist: false }); this.quotaSnapshots.close(); }
|
|
316
569
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// 图片生成的 Host / Client 共享契约;本文件必须保持浏览器安全,不引入 Node 模块。
|
|
2
|
+
export const IMAGE_MODEL_OPTIONS = [
|
|
3
|
+
{ id: 'doubao-seedream-5-0-pro', label: 'Doubao Seedream 5.0 Pro' },
|
|
4
|
+
{ id: 'doubao-seedream-5.5', label: 'Doubao Seedream 5.5' },
|
|
5
|
+
{ id: 'doubao-seedream-5.0-flash', label: 'Doubao Seedream 5.0 Flash' }
|
|
6
|
+
];
|
|
7
|
+
export const SUPPORTED_IMAGE_MODELS = IMAGE_MODEL_OPTIONS.map(option => option.id);
|
|
8
|
+
export const DEFAULT_IMAGE_MODEL = SUPPORTED_IMAGE_MODELS[0];
|
|
9
|
+
export const MEDIA_TOOL_KEYS = ['imageTool'];
|
|
10
|
+
|
|
11
|
+
export function defaultMediaState() {
|
|
12
|
+
return { riskAcknowledged: false, imageTool: false, imageModel: DEFAULT_IMAGE_MODEL };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function normalizeMediaState(value) {
|
|
16
|
+
const base = defaultMediaState();
|
|
17
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return base;
|
|
18
|
+
for (const key of ['riskAcknowledged', ...MEDIA_TOOL_KEYS]) {
|
|
19
|
+
if (value[key] !== undefined && typeof value[key] !== 'boolean') throw new Error('媒体工具开关必须是布尔值');
|
|
20
|
+
if (typeof value[key] === 'boolean') base[key] = value[key];
|
|
21
|
+
}
|
|
22
|
+
if (value.imageModel !== undefined) {
|
|
23
|
+
if (typeof value.imageModel !== 'string' || !SUPPORTED_IMAGE_MODELS.includes(value.imageModel)) {
|
|
24
|
+
throw new Error(`默认图片模型必须是 ${SUPPORTED_IMAGE_MODELS.join(' / ')} 之一`);
|
|
25
|
+
}
|
|
26
|
+
base.imageModel = value.imageModel;
|
|
27
|
+
}
|
|
28
|
+
// 旧版 videoTool 字段在读取时丢弃;撤销风险确认会关闭图片工具。
|
|
29
|
+
if (!base.riskAcknowledged) for (const key of MEDIA_TOOL_KEYS) base[key] = false;
|
|
30
|
+
return base;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function mediaToolEnabled(media, key) {
|
|
34
|
+
return media?.riskAcknowledged === true && media?.[key] === true;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function assertMediaEnabled(enabled, toolName) {
|
|
38
|
+
if (!enabled()) throw new Error(`${toolName} 未启用:请先在 设置 → 火山方舟 Provider → 图片生成 中开启图片工具`);
|
|
39
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// 原始图片文件附件的受控回源:GET /plugins/dsh-volcengine-provider/image/file?…
|
|
2
|
+
// 引用由工具结果公开给当前会话;路由只接受回环来源与同源/宿主 Origin。
|
|
3
|
+
import { MAX_IMAGE_RESULT_BYTES } from './media.mjs';
|
|
4
|
+
|
|
5
|
+
export const IMAGE_FILE_PATH = '/plugins/dsh-volcengine-provider/image/file';
|
|
6
|
+
const ATTACHMENT_ID = /^sha256:[a-f0-9]{64}$/u;
|
|
7
|
+
const IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif']);
|
|
8
|
+
|
|
9
|
+
function fail(response, status, error) {
|
|
10
|
+
response.statusCode = status;
|
|
11
|
+
response.setHeader('content-type', 'application/json; charset=utf-8');
|
|
12
|
+
response.setHeader('cache-control', 'no-store');
|
|
13
|
+
response.setHeader('x-content-type-options', 'nosniff');
|
|
14
|
+
response.end(JSON.stringify({ error }));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function loopbackHostname(hostHeader) {
|
|
18
|
+
const value = String(hostHeader ?? '').trim().toLowerCase();
|
|
19
|
+
const host = value.startsWith('[') ? value.slice(1, value.indexOf(']')) : value.split(':')[0];
|
|
20
|
+
return ['127.0.0.1', 'localhost', '::1'].includes(host) ? host : undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function isTrustedRequest(remoteAddress, headers, method) {
|
|
24
|
+
const remote = String(remoteAddress ?? '');
|
|
25
|
+
if (!['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(remote)) return false;
|
|
26
|
+
if (!loopbackHostname(headers?.host)) return false;
|
|
27
|
+
const origin = typeof headers?.origin === 'string' ? headers.origin : undefined;
|
|
28
|
+
const site = typeof headers?.['sec-fetch-site'] === 'string' ? headers['sec-fetch-site'] : undefined;
|
|
29
|
+
if (site === 'cross-site') return false;
|
|
30
|
+
if (origin === 'dsh-app://app') return true;
|
|
31
|
+
if (String(method ?? 'GET').toUpperCase() === 'GET' && origin === undefined) return true;
|
|
32
|
+
try { return new URL(origin).host === new URL(`http://${headers.host}`).host; }
|
|
33
|
+
catch { return false; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function readReference(url) {
|
|
37
|
+
const keys = ['attachmentId', 'name', 'bytes', 'mediaType'];
|
|
38
|
+
if (keys.some(key => url.searchParams.getAll(key).length !== 1)) return undefined;
|
|
39
|
+
const attachmentId = url.searchParams.get('attachmentId');
|
|
40
|
+
const bytes = Number(url.searchParams.get('bytes'));
|
|
41
|
+
const mediaType = url.searchParams.get('mediaType');
|
|
42
|
+
const name = String(url.searchParams.get('name') ?? '').slice(0, 200);
|
|
43
|
+
if (!ATTACHMENT_ID.test(attachmentId) || !IMAGE_TYPES.has(mediaType)) return undefined;
|
|
44
|
+
if (!Number.isSafeInteger(bytes) || bytes <= 0 || bytes > MAX_IMAGE_RESULT_BYTES) return undefined;
|
|
45
|
+
if (!name || /[\x00-\x1f\x7f]/u.test(name)) return undefined;
|
|
46
|
+
return { ref: { attachmentId, name, bytes }, mediaType };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function safeName(name) {
|
|
50
|
+
return name.replace(/[^\w.-]+/gu, '_').slice(0, 120) || 'image.bin';
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function drained(response) {
|
|
54
|
+
await new Promise((resolve, reject) => {
|
|
55
|
+
response.once('finish', resolve);
|
|
56
|
+
response.once('close', resolve);
|
|
57
|
+
response.once('error', reject);
|
|
58
|
+
}).catch(() => {});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function registerImageFileRoute(webCtx, options) {
|
|
62
|
+
const active = new Set();
|
|
63
|
+
let disposed = false;
|
|
64
|
+
const unregister = webCtx.webServer.register({
|
|
65
|
+
kind: 'exact', path: IMAGE_FILE_PATH,
|
|
66
|
+
async handler(request, response) {
|
|
67
|
+
const method = String(request.method ?? 'GET').toUpperCase();
|
|
68
|
+
if (method !== 'GET') return fail(response, 405, 'method not allowed');
|
|
69
|
+
if (!isTrustedRequest(request.socket?.remoteAddress, request.headers, method)) return fail(response, 403, 'forbidden');
|
|
70
|
+
if (disposed) return fail(response, 503, 'plugin disposed');
|
|
71
|
+
const parsed = readReference(new URL(request.url ?? '', 'http://localhost'));
|
|
72
|
+
if (!parsed) return fail(response, 400, '图片附件参数不合法');
|
|
73
|
+
const attachments = options.resolveAttachments();
|
|
74
|
+
if (!attachments || typeof attachments.readFileStream !== 'function') return fail(response, 503, '附件服务不可用');
|
|
75
|
+
const controller = new AbortController();
|
|
76
|
+
active.add(controller);
|
|
77
|
+
try {
|
|
78
|
+
const stream = await attachments.readFileStream(parsed.ref, controller.signal);
|
|
79
|
+
response.statusCode = 200;
|
|
80
|
+
response.setHeader('content-type', parsed.mediaType);
|
|
81
|
+
response.setHeader('content-length', String(parsed.ref.bytes));
|
|
82
|
+
response.setHeader('cache-control', 'private, max-age=3600');
|
|
83
|
+
response.setHeader('x-content-type-options', 'nosniff');
|
|
84
|
+
const disposition = new URL(request.url ?? '', 'http://localhost').searchParams.get('download') === '1' ? 'attachment' : 'inline';
|
|
85
|
+
response.setHeader('content-disposition', `${disposition}; filename="${safeName(parsed.ref.name)}"`);
|
|
86
|
+
let total = 0;
|
|
87
|
+
for await (const chunk of stream) {
|
|
88
|
+
if (disposed || controller.signal.aborted) break;
|
|
89
|
+
total += chunk.byteLength;
|
|
90
|
+
if (total > parsed.ref.bytes) throw new Error('图片附件超出声明长度');
|
|
91
|
+
if (!response.write(chunk)) await new Promise(resolve => response.once('drain', resolve));
|
|
92
|
+
}
|
|
93
|
+
if (total !== parsed.ref.bytes && !controller.signal.aborted) throw new Error('图片附件长度不一致');
|
|
94
|
+
response.end();
|
|
95
|
+
await drained(response);
|
|
96
|
+
} catch {
|
|
97
|
+
if (!response.headersSent) fail(response, 500, '附件读取失败');
|
|
98
|
+
else response.destroy();
|
|
99
|
+
} finally {
|
|
100
|
+
active.delete(controller);
|
|
101
|
+
controller.abort();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
return () => {
|
|
106
|
+
disposed = true;
|
|
107
|
+
for (const controller of active) controller.abort();
|
|
108
|
+
unregister();
|
|
109
|
+
};
|
|
110
|
+
}
|