Files
order-notification-automation/src/modules/assistant/providers.cjs
T

372 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
const crypto = require('node:crypto');
const { PROTOCOLS, PRESETS, catalogue } = require('./provider-catalog.cjs');
const fail = (message, status = 400) => Object.assign(new Error(message), { status });
function text(value, label, max = 200) {
if (
typeof value !== 'string' ||
!value.trim() ||
value.length > max ||
/[\x00-\x1f\x7f]/.test(value)
)
throw fail(label + '格式不正确。');
return value.trim();
}
function endpoint(value) {
const address = text(value, '模型 API 地址', 1000).replace(/\/+$/, '');
let u;
try {
u = new URL(address);
} catch {
throw fail('模型 API 地址无效。');
}
if (
u.username ||
u.password ||
u.search ||
u.hash ||
!(
u.protocol === 'https:' ||
(u.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(u.hostname))
)
)
throw fail('模型 API 请使用 HTTPS,或本机 HTTP 地址。');
return u.href.replace(/\/+$/, '');
}
function modelRows(rows) {
if (!Array.isArray(rows) || rows.length > 100) throw fail('每个供应商最多配置 100 个模型。');
const seen = new Set();
return rows.map((row) => {
if (
!row ||
typeof row !== 'object' ||
Array.isArray(row) ||
Object.keys(row).some(
(k) => !['id', 'name', 'contextWindow', 'maxTokens', 'inputModalities'].includes(k),
)
)
throw fail('模型配置格式不正确。');
const id = text(row.id, '模型 ID', 200),
name = row.name === undefined ? id : text(row.name, '模型名称', 200);
if (seen.has(id)) throw fail('模型 ID 不得重复。');
seen.add(id);
const saved = { id, name };
if (row.inputModalities !== undefined) {
if (
!Array.isArray(row.inputModalities) ||
!row.inputModalities.length ||
row.inputModalities.some((x) => !['text', 'image'].includes(x))
)
throw fail('模型输入能力无效。');
saved.inputModalities = [...new Set(row.inputModalities)];
}
for (const key of ['contextWindow', 'maxTokens'])
if (row[key] !== undefined) {
if (!Number.isSafeInteger(row[key]) || row[key] < 1 || row[key] > 10000000)
throw fail('模型上下文和输出上限须为 1–10000000 的整数。');
saved[key] = row[key];
}
if (saved.contextWindow && saved.maxTokens > saved.contextWindow)
throw fail('输出上限不得超过模型上下文。');
return saved;
});
}
function publicRow(row) {
const { apiKey, ...safe } = row;
return { ...safe, hasApiKey: !!apiKey };
}
class ProviderRegistry {
constructor(store) {
this.store = store;
store.db.exec(
`CREATE TABLE IF NOT EXISTS assistant_providers(id TEXT PRIMARY KEY,version INTEGER NOT NULL,payload BLOB NOT NULL);CREATE TABLE IF NOT EXISTS assistant_provider_defaults(id INTEGER PRIMARY KEY CHECK(id=1),version INTEGER NOT NULL,payload BLOB NOT NULL);`,
);
store.transaction(() => {
if (!this.defaults().legacyMigrated) {
const settings = store.secretSettings();
this.syncLegacy(settings);
}
});
}
defaults() {
const row = this.store.db.prepare('SELECT * FROM assistant_provider_defaults WHERE id=1').get();
return row
? { ...this.store.decode('provider-defaults', row.payload), version: row.version }
: { version: 0, defaultSelection: null, legacyMigrated: false };
}
writeDefaults(value) {
const { version, ...payload } = value;
this.store.db
.prepare(
'INSERT INTO assistant_provider_defaults VALUES(1,?,?) ON CONFLICT(id) DO UPDATE SET version=excluded.version,payload=excluded.payload',
)
.run(version, this.store.encode('provider-defaults', payload));
}
read(id) {
if (typeof id !== 'string' || !/^[-\w]{1,80}$/.test(id)) throw fail('供应商 ID 无效。');
const row = this.store.db.prepare('SELECT * FROM assistant_providers WHERE id=?').get(id);
if (!row) throw fail('供应商已移除,请重新选择。', 409);
return { id, ...this.store.decode('provider:' + id, row.payload), version: row.version };
}
write(row) {
const { id, version, ...payload } = row;
this.store.db
.prepare(
'INSERT INTO assistant_providers VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET version=excluded.version,payload=excluded.payload',
)
.run(id, version, this.store.encode('provider:' + id, payload));
}
list() {
const defaults = this.defaults();
return {
version: defaults.version,
providers: this.store.db
.prepare('SELECT id FROM assistant_providers ORDER BY rowid')
.all()
.map((row) => publicRow(this.read(row.id))),
defaultSelection: defaults.defaultSelection,
catalog: catalogue(),
};
}
save(input) {
return this.store.transaction(() => {
if (
!input ||
typeof input !== 'object' ||
Array.isArray(input) ||
Object.keys(input).some(
(k) =>
![
'id',
'version',
'name',
'preset',
'protocol',
'apiBase',
'enabled',
'apiKey',
'hasApiKey',
'models',
].includes(k),
)
)
throw fail('供应商配置格式不正确。');
const old = input.id ? this.read(input.id) : null;
if (input.version !== (old?.version ?? 0))
throw fail('供应商配置已更新,请刷新后重试。', 409);
if (
!old &&
this.store.db.prepare('SELECT COUNT(*) AS n FROM assistant_providers').get().n >= 30
)
throw fail('最多配置 30 个供应商。', 409);
const name = text(input.name, '供应商名称');
if (
!PRESETS.some((p) => p.id === input.preset) ||
!PROTOCOLS.includes(input.protocol) ||
typeof input.enabled !== 'boolean'
)
throw fail('请选择有效供应商、协议与启用状态。');
const apiBase = endpoint(input.apiBase);
if (
typeof input.apiKey !== 'string' ||
input.apiKey.length > 4096 ||
/[\x00-\x1f\x7f]/.test(input.apiKey)
)
throw fail('请输入有效模型密钥。');
if (
!input.apiKey &&
old?.apiKey &&
(apiBase !== old.apiBase || input.protocol !== old.protocol)
)
throw fail('更换协议或 API 地址后请重新填写密钥。');
this.write({
id: old?.id || crypto.randomUUID(),
version: (old?.version ?? 0) + 1,
name,
preset: input.preset,
protocol: input.protocol,
apiBase,
enabled: input.enabled,
apiKey: input.apiKey || old?.apiKey || '',
models: modelRows(input.models),
});
const defaults = this.defaults();
this.writeDefaults({ ...defaults, version: defaults.version + 1 });
return this.list();
});
}
chooseDefault(input) {
return this.store.transaction(() => {
const defaults = this.defaults();
if (!input || input.version !== defaults.version)
throw fail('供应商目录已更新,请刷新后重试。', 409);
const selected = this.resolve(input);
this.writeDefaults({
...defaults,
version: defaults.version + 1,
defaultSelection: { providerId: selected.providerId, modelId: selected.model },
});
return this.list();
});
}
remove(id, input) {
return this.store.transaction(() => {
const row = this.read(id);
if (!input || input.version !== row.version)
throw fail('供应商配置已更新,请刷新后重试。', 409);
this.store.db.prepare('DELETE FROM assistant_providers WHERE id=?').run(id);
const defaults = this.defaults();
this.writeDefaults({
...defaults,
version: defaults.version + 1,
...(id === 'deepseek'
? { legacyVersion: Math.max(defaults.legacyVersion || 0, row.version) }
: {}),
defaultSelection:
defaults.defaultSelection?.providerId === id ? null : defaults.defaultSelection,
});
return this.list();
});
}
resolve(selection) {
const selected = selection === undefined ? this.defaults().defaultSelection : selection;
if (
!selected ||
typeof selected.providerId !== 'string' ||
typeof selected.modelId !== 'string'
)
throw fail('请选择可用模型。', 409);
const row = this.read(selected.providerId),
model = row.models.find((m) => m.id === selected.modelId);
if (!row.enabled || !row.apiKey || !model)
throw fail('所选供应商或模型不可用,请重新选择。', 409);
return {
providerId: row.id,
providerName: row.name,
providerVersion: row.version,
preset: row.preset,
protocol: row.protocol,
apiBase: row.apiBase,
apiKey: row.apiKey,
model: model.id,
modelName: model.name,
...(model.inputModalities ? { inputModalities: [...model.inputModalities] } : {}),
contextWindow: model.contextWindow || 131072,
maxTokens: model.maxTokens || Math.min(model.contextWindow || 131072, 32768),
};
}
syncLegacy(settings) {
return this.store.transaction(() => {
const defaults = this.defaults();
let old;
try {
old = this.read('deepseek');
} catch (e) {
if (e.status !== 409) throw e;
}
if (
!old &&
this.store.db.prepare('SELECT COUNT(*) AS n FROM assistant_providers').get().n >= 30
)
throw fail('最多配置 30 个供应商。', 409);
const apiBase = settings.apiBase || 'https://api.deepseek.com/anthropic',
model = settings.model || 'deepseek-flash';
const next = {
id: 'deepseek',
version: Math.max(old?.version || 0, defaults.legacyVersion || 0) + 1,
name: old?.name || 'DeepSeek',
preset: 'deepseek',
protocol: 'anthropic-messages',
apiBase,
apiKey: settings.apiKey || '',
enabled: old?.enabled ?? true,
models: [{ id: model, name: model }],
};
this.write(next);
this.writeDefaults({
...defaults,
version: defaults.version + 1,
legacyMigrated: true,
legacyVersion: next.version,
defaultSelection:
!defaults.legacyMigrated || defaults.defaultSelection?.providerId === 'deepseek'
? { providerId: 'deepseek', modelId: model }
: defaults.defaultSelection,
});
return this.list();
});
}
async discover(id, { version, signal } = {}) {
const row = this.read(id);
if (version !== row.version) throw fail('供应商配置已更新,请刷新后重试。', 409);
if (!row.apiKey) throw fail('请先保存供应商密钥。', 409);
const url = new URL(endpoint(row.apiBase));
if (
row.preset === 'deepseek' &&
row.protocol === 'anthropic-messages' &&
url.pathname.endsWith('/anthropic')
)
url.pathname = url.pathname.slice(0, -10) || '/';
url.pathname =
url.pathname.replace(/\/$/, '') +
(row.protocol === 'anthropic-messages' &&
!url.pathname.endsWith('/v1') &&
row.preset !== 'deepseek'
? '/v1'
: '') +
'/models';
const headers =
row.protocol === 'anthropic-messages' && row.preset !== 'deepseek'
? { 'x-api-key': row.apiKey, 'anthropic-version': '2023-06-01' }
: { authorization: 'Bearer ' + row.apiKey };
let response, reader;
const timeout = AbortSignal.timeout(10000),
combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
try {
response = await fetch(url, { method: 'GET', headers, signal: combined, redirect: 'error' });
reader = response.body?.getReader();
if (!response.ok || Number(response.headers.get('content-length') || 0) > 1024 * 1024)
throw fail('模型目录请求失败或响应过大。', 502);
if (!reader) throw fail('模型目录响应为空。', 502);
const chunks = [];
let size = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
size += value.length;
if (size > 1024 * 1024) throw fail('模型目录响应过大。', 502);
chunks.push(value);
}
const data = JSON.parse(Buffer.concat(chunks).toString('utf8'));
if (!Array.isArray(data.data) || !data.data.length || data.data.length > 100)
throw fail('模型目录格式不支持,请手动配置模型。', 502);
const models = modelRows(
data.data.map((m) => ({
id: m.id,
name: m.name || m.display_name || m.id,
...(m.context_window || m.contextWindow
? { contextWindow: m.context_window || m.contextWindow }
: {}),
...(m.max_tokens || m.maxTokens ? { maxTokens: m.max_tokens || m.maxTokens } : {}),
...(m.input || m.input_modalities || m.modalities?.input
? { inputModalities: m.input || m.input_modalities || m.modalities.input }
: {}),
})),
);
if (this.read(id).version !== version)
throw fail('获取期间供应商配置已更新,请刷新后重试。', 409);
return { providerId: id, version, models };
} catch (e) {
if (e.status) throw e;
if (signal?.aborted) throw fail('已取消获取模型目录。', 499);
if (timeout.aborted) throw fail('获取模型目录超时。', 504);
throw fail('模型目录请求失败或格式不支持。', 502);
} finally {
try {
await reader?.cancel();
} catch {}
}
}
}
module.exports = { ProviderRegistry, endpoint, modelRows };