402 lines
20 KiB
JavaScript
402 lines
20 KiB
JavaScript
'use strict';
|
||
window.AssistantProviderSettings = {
|
||
async render(container, { api, esc, notify, user, formatDate, isActive = () => true }) {
|
||
const [data, initial] = await Promise.all([api('/assistant'), api('/assistant/providers')]);
|
||
if (!isActive()) return;
|
||
let directory = initial,
|
||
editing = null,
|
||
busy = false,
|
||
disposed = false,
|
||
unregisterEditor = null;
|
||
const live = () => !disposed && isActive() && container.isConnected;
|
||
container.innerHTML =
|
||
'<div class="settings-width assistant-provider-settings"><section class="card mb-3"><div class="card-header"><h2 class="card-title">模型供应商</h2><a class="btn btn-sm ms-auto" href="#assistant">返回 DSH 助手</a></div><div class="card-body"><div id="provider-list"></div><div id="provider-editor"></div><div id="provider-feedback" class="small mt-3" role="status"></div></div></section><section class="card mb-3"><div class="card-header"><h2 class="card-title">默认模型</h2></div><div class="card-body" id="provider-default-host"></div></section><div id="assistant-runtime-host"></div><div id="assistant-settings-error" class="small text-danger" role="alert"></div></div>';
|
||
const feedback = (text, error = false) => {
|
||
if (live()) {
|
||
const host = container.querySelector('#provider-feedback');
|
||
host.className = 'small mt-3 ' + (error ? 'text-danger' : 'text-success');
|
||
host.textContent = text;
|
||
}
|
||
},
|
||
failure = (e) => feedback(e.message, true);
|
||
const modelText = (models) =>
|
||
(models || [])
|
||
.map((m) =>
|
||
[
|
||
m.id,
|
||
m.name === m.id ? '' : m.name || '',
|
||
m.contextWindow || '',
|
||
m.maxTokens || '',
|
||
m.inputModalities?.join(',') || '',
|
||
]
|
||
.join('|')
|
||
.replace(/\|+$/, ''),
|
||
)
|
||
.join('\n');
|
||
const parseModels = (text) =>
|
||
text
|
||
.split(/\r?\n/)
|
||
.map((s) => s.trim())
|
||
.filter(Boolean)
|
||
.map((line) => {
|
||
const [id, name, context, max, modalities, ...extra] = line
|
||
.split('|')
|
||
.map((s) => s.trim());
|
||
if (extra.length)
|
||
throw Error('模型每行最多五项:ID、显示名、上下文、输出上限、输入能力。');
|
||
return {
|
||
id,
|
||
...(name ? { name } : {}),
|
||
...(context ? { contextWindow: Number(context) } : {}),
|
||
...(max ? { maxTokens: Number(max) } : {}),
|
||
...(modalities ? { inputModalities: modalities.split(',').map((x) => x.trim()) } : {}),
|
||
};
|
||
});
|
||
function defaultForm(reset = false) {
|
||
const host = container.querySelector('#provider-default-host'),
|
||
prior = reset ? null : host.querySelector('select')?.value,
|
||
available = directory.providers.filter((p) => p.enabled !== false && p.hasApiKey !== false),
|
||
current = directory.defaultSelection ? JSON.stringify(directory.defaultSelection) : '';
|
||
host.innerHTML =
|
||
'<form id="assistant-default-form"><label class="form-label" for="provider-default">默认模型</label><div class="d-flex flex-wrap gap-2"><select id="provider-default" class="form-select flex-fill"><option value="">请选择可用模型</option>' +
|
||
available
|
||
.map(
|
||
(p) =>
|
||
'<optgroup label="' +
|
||
esc(p.name) +
|
||
'">' +
|
||
p.models
|
||
.map(
|
||
(m) =>
|
||
'<option value="' +
|
||
esc(JSON.stringify({ providerId: p.id, modelId: m.id })) +
|
||
'">' +
|
||
esc(p.name + ' / ' + (m.name || m.id)) +
|
||
'</option>',
|
||
)
|
||
.join('') +
|
||
'</optgroup>',
|
||
)
|
||
.join('') +
|
||
'</select>' +
|
||
(user.role === 'admin'
|
||
? '<button class="btn btn-primary" type="submit">保存默认模型</button>'
|
||
: '') +
|
||
'</div><p class="form-hint mt-2">新会话默认使用此模型,个人会话可独立选择。供应商或模型移除后需要重新选择。</p></form>';
|
||
const select = host.querySelector('select');
|
||
select.value = [...select.options].some((o) => o.value === prior) ? prior : current;
|
||
if (!select.value) select.value = '';
|
||
if (user.role !== 'admin') select.disabled = true;
|
||
host.querySelector('form').onsubmit = async (e) => {
|
||
e.preventDefault();
|
||
if (!select.value || user.role !== 'admin' || busy) return;
|
||
const button = e.submitter;
|
||
button.disabled = true;
|
||
try {
|
||
directory = await api('/assistant/providers/default', {
|
||
version: directory.version,
|
||
...JSON.parse(select.value),
|
||
});
|
||
if (live()) {
|
||
defaultForm(true);
|
||
feedback('默认模型已保存。');
|
||
}
|
||
} catch (error) {
|
||
failure(error);
|
||
} finally {
|
||
if (button.isConnected) button.disabled = false;
|
||
}
|
||
};
|
||
}
|
||
async function requestEdit(p) {
|
||
if (busy) return;
|
||
const action = () => edit(p);
|
||
if (window.PageLifecycle?.guard)
|
||
await window.PageLifecycle.guard(action, { scope: 'assistant-provider' });
|
||
else action();
|
||
}
|
||
function draw() {
|
||
const list = container.querySelector('#provider-list');
|
||
list.innerHTML =
|
||
directory.providers
|
||
.map(
|
||
(p) =>
|
||
`<div class="provider-row" data-provider-row="${esc(p.id)}"><div class="flex-fill"><strong>${esc(p.name)}</strong><div class="small text-secondary">${esc(p.protocol || '已配置模型')} · ${p.models.length} 个模型${user.role === 'admin' ? ' · ' + (p.enabled ? (p.hasApiKey ? '密钥已保存' : '待配置密钥') : '已停用') : ''}</div></div>${user.role === 'admin' ? '<button type="button" class="btn btn-sm" data-provider-edit="' + esc(p.id) + '">编辑</button><button type="button" class="btn btn-sm" data-provider-remove="' + esc(p.id) + '">删除</button>' : ''}</div>`,
|
||
)
|
||
.join('') || '<p class="text-secondary">暂无可用供应商,请管理员添加。</p>';
|
||
if (user.role === 'admin')
|
||
list.insertAdjacentHTML(
|
||
'beforeend',
|
||
'<button class="btn btn-outline-primary mt-3" type="button" id="provider-add" aria-label="添加供应商">+ 添加供应商</button>',
|
||
);
|
||
list
|
||
.querySelectorAll('[data-provider-edit]')
|
||
.forEach(
|
||
(button) =>
|
||
(button.onclick = () =>
|
||
requestEdit(directory.providers.find((p) => p.id === button.dataset.providerEdit))),
|
||
);
|
||
list
|
||
.querySelectorAll('[data-provider-remove]')
|
||
.forEach(
|
||
(button) =>
|
||
(button.onclick = () =>
|
||
remove(directory.providers.find((p) => p.id === button.dataset.providerRemove))),
|
||
);
|
||
list.querySelector('#provider-add')?.addEventListener('click', () => requestEdit(null));
|
||
defaultForm();
|
||
}
|
||
async function remove(p) {
|
||
if (busy) return;
|
||
if (
|
||
window.PageLifecycle?.guard &&
|
||
!(await window.PageLifecycle.guard(
|
||
() => {
|
||
unregisterEditor?.();
|
||
editing = null;
|
||
container.querySelector('#provider-editor').replaceChildren();
|
||
},
|
||
{ scope: 'assistant-provider' },
|
||
))
|
||
)
|
||
return;
|
||
const dialog = document.createElement('dialog');
|
||
dialog.className = 'page-leave-dialog';
|
||
dialog.setAttribute('aria-label', '删除供应商');
|
||
dialog.innerHTML =
|
||
'<h3>删除供应商</h3><p>' +
|
||
esc(p.name) +
|
||
' 将从可选模型中移除。已有对话和审计保留,关联模型需要重新选择。</p><div class="btn-list"><button class="btn" type="button">取消</button><button class="btn btn-danger" type="button">确认删除供应商</button></div>';
|
||
container.append(dialog);
|
||
dialog.showModal();
|
||
const answer = await new Promise((resolve) => {
|
||
dialog.oncancel = (e) => {
|
||
e.preventDefault();
|
||
resolve(false);
|
||
};
|
||
dialog.onclose = () => resolve(false);
|
||
const buttons = dialog.querySelectorAll('button');
|
||
buttons[0].onclick = () => resolve(false);
|
||
buttons[1].onclick = () => resolve(true);
|
||
});
|
||
dialog.close();
|
||
dialog.remove();
|
||
if (!answer || !live()) return;
|
||
busy = true;
|
||
try {
|
||
directory = await api('/assistant/providers/' + p.id + '/delete', { version: p.version });
|
||
if (live()) {
|
||
editing = null;
|
||
container.querySelector('#provider-editor').replaceChildren();
|
||
draw();
|
||
feedback('供应商已删除。');
|
||
}
|
||
} catch (error) {
|
||
failure(error);
|
||
} finally {
|
||
busy = false;
|
||
}
|
||
}
|
||
function edit(p) {
|
||
if (busy) return;
|
||
unregisterEditor?.();
|
||
editing = p?.id || 'new';
|
||
const presets = directory.catalog?.presets || [],
|
||
preset = p ||
|
||
presets.find((p) => p.id === 'deepseek') || {
|
||
preset: 'custom',
|
||
protocol: 'openai-completions',
|
||
apiBase: '',
|
||
models: [],
|
||
},
|
||
host = container.querySelector('#provider-editor');
|
||
host.innerHTML = `<form id="provider-edit-form" class="provider-editor mt-3"><h3>${p ? '编辑供应商' : '添加供应商'}</h3><div class="row g-3"><div class="col-md-6"><label class="form-label" for="provider-preset">供应商类型</label><select id="provider-preset" class="form-select">${presets.map((x) => '<option value="' + esc(x.id) + '">' + esc(x.name) + '</option>').join('')}</select></div><div class="col-md-6"><label class="form-label" for="provider-name">供应商名称</label><input id="provider-name" class="form-control" maxlength="200" required value="${esc(p?.name || preset.name || '')}"></div><div class="col-md-6"><label class="form-label" for="provider-protocol">API 协议</label><select id="provider-protocol" class="form-select"><option value="openai-completions">OpenAI Chat Completions</option><option value="openai-responses">OpenAI Responses</option><option value="anthropic-messages">Anthropic Messages</option></select></div><div class="col-md-6"><label class="form-label" for="provider-base">API 根地址</label><input id="provider-base" class="form-control" maxlength="1000" required value="${esc(p?.apiBase || preset.apiBase || '')}"></div><div class="col-12"><label class="form-label" for="provider-key">API 密钥</label><input id="provider-key" class="form-control" type="password" autocomplete="new-password" maxlength="4096" placeholder="${p?.hasApiKey ? '已保存;留空保留,更换协议或地址需重填' : '输入此供应商的 API Key'}"><div class="form-hint">仅保存到加密存储,页面不会读回已保存的密钥。</div></div><div class="col-12"><label class="form-label" for="provider-models">模型列表</label><textarea id="provider-models" class="form-control font-monospace" rows="5">${esc(modelText(p?.models || preset.models))}</textarea><div class="form-hint">每行:模型 ID | 显示名 | 上下文窗口 | 最大输出 | 输入能力;后 4 项可省略。输入能力可填 text 或 text,image,须由供应商文档或目录确认。获取模型后先检查草稿,再保存。</div></div><div class="col-12"><label class="form-check"><input id="provider-enabled" class="form-check-input" type="checkbox" ${p?.enabled === false ? '' : 'checked'}><span class="form-check-label">启用此供应商</span></label></div></div><div class="btn-list mt-3"><button class="btn" type="button" id="provider-cancel" data-lifecycle-approved="1">取消</button><button class="btn" type="button" id="provider-discover" ${p ? '' : 'disabled'}>获取模型</button><button class="btn btn-primary ms-auto" type="submit">保存供应商</button></div><div id="provider-editor-feedback" class="small mt-2" role="alert"></div></form>`;
|
||
const form = host.querySelector('form'),
|
||
get = (id) => form.querySelector('#provider-' + id),
|
||
message = (text, error = false) => {
|
||
if (live() && form.isConnected) {
|
||
get('editor-feedback').className =
|
||
'small mt-2 ' + (error ? 'text-danger' : 'text-success');
|
||
get('editor-feedback').textContent = text;
|
||
}
|
||
};
|
||
get('preset').value = p?.preset || preset.id || 'custom';
|
||
get('protocol').value = p?.protocol || preset.protocol;
|
||
form.dataset.lifecycle = 'custom';
|
||
const snapshot = () =>
|
||
JSON.stringify(
|
||
[...form.querySelectorAll('input,select,textarea')].map((e) =>
|
||
e.type === 'checkbox' ? e.checked : e.value,
|
||
),
|
||
),
|
||
baseline = snapshot();
|
||
unregisterEditor = window.PageLifecycle?.register({
|
||
scope: 'assistant-provider',
|
||
sensitive: true,
|
||
dirty: () => form.isConnected && snapshot() !== baseline,
|
||
});
|
||
function lockFields() {
|
||
const fields = [...form.querySelectorAll('input,select,textarea,button')].map((field) => ({
|
||
field,
|
||
disabled: field.disabled,
|
||
}));
|
||
for (const { field } of fields) field.disabled = true;
|
||
return () => {
|
||
if (form.isConnected) for (const { field, disabled } of fields) field.disabled = disabled;
|
||
};
|
||
}
|
||
get('preset').onchange = () => {
|
||
const selected = presets.find((x) => x.id === get('preset').value);
|
||
if (!selected) return;
|
||
get('name').value = selected.name;
|
||
get('protocol').value = selected.protocol;
|
||
get('base').value = selected.apiBase || '';
|
||
get('models').value = modelText(selected.models);
|
||
};
|
||
get('cancel').onclick = () => {
|
||
const cancel = () => {
|
||
unregisterEditor?.();
|
||
editing = null;
|
||
host.replaceChildren();
|
||
};
|
||
if (window.PageLifecycle?.guard)
|
||
void window.PageLifecycle.guard(cancel, { scope: 'assistant-provider' });
|
||
else cancel();
|
||
};
|
||
get('discover').onclick = async () => {
|
||
if (!p || busy) return;
|
||
if (
|
||
get('base').value.replace(/\/+$/, '') !== p.apiBase.replace(/\/+$/, '') ||
|
||
get('protocol').value !== p.protocol ||
|
||
get('key').value
|
||
) {
|
||
message('请先保存新的协议、地址或密钥,再获取模型。', true);
|
||
return;
|
||
}
|
||
busy = true;
|
||
const unlock = lockFields();
|
||
try {
|
||
const result = await api(
|
||
'/assistant/providers/' + p.id + '/models',
|
||
{ version: p.version },
|
||
{ managedOutcome: true },
|
||
);
|
||
if (live() && editing === p.id && form.isConnected) {
|
||
get('models').value = modelText(result.models);
|
||
message('模型目录已填入草稿,请检查后保存。');
|
||
}
|
||
} catch (error) {
|
||
message(error.message, true);
|
||
} finally {
|
||
busy = false;
|
||
unlock();
|
||
}
|
||
};
|
||
form.onsubmit = async (event) => {
|
||
event.preventDefault();
|
||
if (busy) return;
|
||
busy = true;
|
||
const button = event.submitter;
|
||
let unlock = () => {};
|
||
try {
|
||
const body = {
|
||
...(p ? { id: p.id } : {}),
|
||
version: p?.version || 0,
|
||
name: get('name').value,
|
||
preset: get('preset').value,
|
||
protocol: get('protocol').value,
|
||
apiBase: get('base').value,
|
||
apiKey: get('key').value,
|
||
enabled: get('enabled').checked,
|
||
models: parseModels(get('models').value),
|
||
};
|
||
unlock = lockFields();
|
||
const result = await api('/assistant/providers', body);
|
||
if (!live()) return;
|
||
directory = result;
|
||
editing = null;
|
||
unregisterEditor?.();
|
||
get('key').value = '';
|
||
host.replaceChildren();
|
||
draw();
|
||
feedback('供应商已保存。');
|
||
} catch (error) {
|
||
message(error.message, true);
|
||
} finally {
|
||
busy = false;
|
||
unlock();
|
||
}
|
||
};
|
||
}
|
||
function runtimeForm() {
|
||
const host = container.querySelector('#assistant-runtime-host');
|
||
if (user.role !== 'admin') {
|
||
host.innerHTML = '<p class="text-secondary">供应商与运行权限由管理员维护。</p>';
|
||
return;
|
||
}
|
||
const s = data.settings;
|
||
host.innerHTML = `<section class="card mb-3"><div class="card-header"><h2 class="card-title">运行与权限</h2></div><form id="assistant-settings-form"><div class="card-body"><label class="form-label" for="assistant-runtime">官方 CLI 运行包路径</label><input id="assistant-runtime" class="form-control" value="${esc(s.runtimePath)}" maxlength="1000"><div class="row g-3 mt-1"><div class="col-md-6"><label class="form-label" for="assistant-timeout">回复超时(秒)</label><input id="assistant-timeout" class="form-control" type="number" min="15" max="180" value="${s.timeoutSeconds}"></div><div class="col-md-6"><label class="form-label" for="assistant-limit">每日对话轮次上限</label><input id="assistant-limit" class="form-control" type="number" min="1" max="1000" value="${s.dailyLimit}"></div></div><label class="form-check mt-2"><input id="assistant-allow-actions" class="form-check-input" type="checkbox" ${s.allowActions ? 'checked' : ''}><span class="form-check-label">开放固定操作卡片(仍按工作台权限执行)</span></label><details class="mt-3"><summary>管理员隔离代码修复</summary><label class="form-check mt-2"><input id="assistant-code-repair" class="form-check-input" type="checkbox" ${s.allowCodeRepair ? 'checked' : ''}><span class="form-check-label">允许管理员提出并审查隔离代码修复</span></label><label class="form-label mt-2" for="assistant-repository">源码 Git 仓库路径</label><input id="assistant-repository" class="form-control" maxlength="1000" value="${esc(s.repairRepository || '')}"><div class="form-hint">固定测试通过后仍待人工审查,不自动合并部署。</div></details><div id="assistant-runtime-status" class="small mt-3" role="status"></div></div><div class="card-footer btn-list"><button class="btn" type="button" id="assistant-check">检查运行包</button><button class="btn btn-primary ms-auto" type="submit">保存助手设置</button></div></form></section>`;
|
||
const get = (id) => host.querySelector('#assistant-' + id);
|
||
get('check').onclick = async () => {
|
||
get('check').disabled = true;
|
||
try {
|
||
const checked = await api('/assistant/check', {});
|
||
if (live())
|
||
get('runtime-status').textContent =
|
||
checked.message +
|
||
(checked.modelConfigured
|
||
? ' 默认模型配置完整,实际调用时验证。'
|
||
: ' 请先添加供应商并选择可用默认模型。');
|
||
} catch (error) {
|
||
if (live()) get('runtime-status').textContent = error.message;
|
||
} finally {
|
||
if (live()) get('check').disabled = false;
|
||
}
|
||
};
|
||
host.querySelector('form').onsubmit = async (event) => {
|
||
event.preventDefault();
|
||
const button = event.submitter;
|
||
button.disabled = true;
|
||
try {
|
||
const saved = await api('/assistant/settings', {
|
||
version: data.settings.version,
|
||
runtimePath: get('runtime').value,
|
||
timeoutSeconds: Number(get('timeout').value),
|
||
dailyLimit: Number(get('limit').value),
|
||
enabled: data.settings.enabled,
|
||
allowActions: get('allow-actions').checked,
|
||
allowCodeRepair: get('code-repair').checked,
|
||
repairRepository: get('repository').value,
|
||
});
|
||
if (!live()) return;
|
||
data.settings = saved;
|
||
await window.PageLifecycle.afterSave(
|
||
async () => {
|
||
const fresh = await api('/assistant');
|
||
if (live()) data.settings = fresh.settings;
|
||
},
|
||
'助手设置已保存。',
|
||
feedback,
|
||
live,
|
||
);
|
||
} catch (error) {
|
||
if (live())
|
||
container.querySelector('#assistant-settings-error').textContent = error.message;
|
||
} finally {
|
||
if (button.isConnected) button.disabled = false;
|
||
}
|
||
};
|
||
}
|
||
draw();
|
||
runtimeForm();
|
||
window.PageLifecycle?.onDispose(() => {
|
||
disposed = true;
|
||
unregisterEditor?.();
|
||
container.querySelectorAll('dialog').forEach((d) => {
|
||
d.close();
|
||
d.remove();
|
||
});
|
||
});
|
||
},
|
||
};
|