mirror of
https://github.com/open-webui/computer.git
synced 2026-11-22 21:50:43 -05:00
refac
This commit is contained in:
1 parent
d50fbf9013
commit
f1a043728b
15 files changed
+111
-8
No files matched your search
@@ -23,7 +23,7 @@ export async function fetchJSON<T = unknown>(path: string, init?: RequestInit):
|
||||
const res = await fetchHandler(path, init);
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
throw new ApiError(res.status, data.detail || data.error || res.statusText);
|
||||
throw new ApiError(res.status, data.detail || data.error || data.message || res.statusText);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@
|
||||
let formCommand = $state('');
|
||||
let formArgs = $state('');
|
||||
let formCwd = $state('');
|
||||
let formEnv = $state('');
|
||||
|
||||
let saving = $state(false);
|
||||
let verifying = $state(false);
|
||||
@@ -43,6 +44,46 @@
|
||||
// Verify result
|
||||
let verifyResult = $state<{ ok: boolean; tools?: any[]; message?: string } | null>(null);
|
||||
|
||||
function splitArgs(value: string): string[] {
|
||||
const args: string[] = [];
|
||||
let current = '';
|
||||
let quote: string | null = null;
|
||||
let started = false;
|
||||
|
||||
const input = value.trim();
|
||||
for (let i = 0; i < input.length; i += 1) {
|
||||
const ch = input[i];
|
||||
const next = input[i + 1];
|
||||
if (quote) {
|
||||
started = true;
|
||||
if (ch === quote) quote = null;
|
||||
else if (ch === '\\' && (next === quote || next === '\\')) current += input[++i];
|
||||
else current += ch;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
started = true;
|
||||
quote = ch;
|
||||
} else if (/\s/.test(ch)) {
|
||||
if (started) {
|
||||
args.push(current);
|
||||
current = '';
|
||||
started = false;
|
||||
}
|
||||
} else {
|
||||
started = true;
|
||||
current += ch;
|
||||
}
|
||||
}
|
||||
|
||||
if (started) args.push(current);
|
||||
return args;
|
||||
}
|
||||
|
||||
function joinArgs(args: string[]): string {
|
||||
return args
|
||||
.map((arg) => (!arg || /\s|["']/.test(arg) ? `"${arg.replace(/(["\\])/g, '\\$1')}"` : arg))
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
servers = await listToolServers();
|
||||
@@ -67,6 +108,7 @@
|
||||
formCommand = '';
|
||||
formArgs = '';
|
||||
formCwd = '';
|
||||
formEnv = '';
|
||||
|
||||
verifyResult = null;
|
||||
showModal = true;
|
||||
@@ -84,8 +126,9 @@
|
||||
formDescription = s.description;
|
||||
formHeaders = s.headers ? JSON.stringify(s.headers, null, 2) : '';
|
||||
formCommand = s.command || '';
|
||||
formArgs = (s.args || []).join(' ');
|
||||
formArgs = joinArgs(s.args || []);
|
||||
formCwd = s.cwd || '';
|
||||
formEnv = s.env ? JSON.stringify(s.env, null, 2) : '';
|
||||
|
||||
verifyResult = null;
|
||||
showModal = true;
|
||||
@@ -119,6 +162,17 @@
|
||||
return;
|
||||
}
|
||||
}
|
||||
let parsedEnv: Record<string, string> | null = null;
|
||||
if (isStdio && formEnv.trim()) {
|
||||
try {
|
||||
const v = JSON.parse(formEnv);
|
||||
if (typeof v !== 'object' || v === null || Array.isArray(v)) throw 0;
|
||||
parsedEnv = v;
|
||||
} catch {
|
||||
toast.error($t('toolServers.envInvalid'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
saving = true;
|
||||
try {
|
||||
const data: Record<string, unknown> = {
|
||||
@@ -140,8 +194,9 @@
|
||||
description: formDescription.trim(),
|
||||
headers: parsedHeaders || null,
|
||||
command: formCommand.trim(),
|
||||
args: formArgs.trim() ? formArgs.trim().split(/\s+/) : [],
|
||||
cwd: formCwd.trim() || null
|
||||
args: splitArgs(formArgs),
|
||||
cwd: formCwd.trim() || null,
|
||||
env: parsedEnv
|
||||
};
|
||||
if (editServer) {
|
||||
if (formKey.trim()) data.key = formKey.trim();
|
||||
@@ -360,6 +415,21 @@
|
||||
spellcheck="false"
|
||||
class="block w-full bg-transparent text-[0.8125rem] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono"
|
||||
/>
|
||||
<label for="tool-server-env" class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-2"
|
||||
>{$t('toolServers.env')}</label
|
||||
>
|
||||
<p class="text-[0.625rem] text-gray-300 dark:text-gray-700 mb-0.5">
|
||||
{$t('toolServers.envHint')}
|
||||
</p>
|
||||
<textarea
|
||||
id="tool-server-env"
|
||||
placeholder={'{"MAIL_TOKEN": "xxxx"}'}
|
||||
bind:value={formEnv}
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
rows="2"
|
||||
class="block w-full bg-transparent text-[0.8125rem] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono resize-none"
|
||||
></textarea>
|
||||
{/if}
|
||||
|
||||
<!-- Spec path (OpenAPI only) -->
|
||||
|
||||
@@ -868,6 +868,9 @@
|
||||
"toolServers.args": "Argumente",
|
||||
"toolServers.cwd": "Arbeitsverzeichnis",
|
||||
"toolServers.cwdPlaceholder": "Optional (standardmäßig System)",
|
||||
"toolServers.env": "Umgebung",
|
||||
"toolServers.envHint": "Zusätzliche Umgebungsvariablen als JSON-Objekt. Werden mit dem geerbten PATH beim Start des Prozesses zusammengeführt.",
|
||||
"toolServers.envInvalid": "Umgebung muss ein gültiges JSON-Objekt sein",
|
||||
"toolServers.commandRequired": "Befehl ist für stdio-Server erforderlich",
|
||||
"toolServers.connectionFailed": "Verbindung fehlgeschlagen",
|
||||
"toolServers.apiKeyKeep": "•••••••• (leer lassen zum Beibehalten)",
|
||||
|
||||
@@ -905,6 +905,9 @@
|
||||
"toolServers.args": "Arguments",
|
||||
"toolServers.cwd": "Working Directory",
|
||||
"toolServers.cwdPlaceholder": "Optional (defaults to system)",
|
||||
"toolServers.env": "Environment",
|
||||
"toolServers.envHint": "Extra environment variables as JSON object. Merged with the inherited PATH when spawning the process.",
|
||||
"toolServers.envInvalid": "Environment must be a valid JSON object",
|
||||
"toolServers.commandRequired": "Command is required for stdio servers",
|
||||
"toolServers.connectionFailed": "Connection failed",
|
||||
"toolServers.apiKeyKeep": "•••••••• (leave blank to keep)",
|
||||
|
||||
@@ -868,6 +868,9 @@
|
||||
"toolServers.args": "Argumentos",
|
||||
"toolServers.cwd": "Directorio de trabajo",
|
||||
"toolServers.cwdPlaceholder": "Opcional (predeterminado del sistema)",
|
||||
"toolServers.env": "Entorno",
|
||||
"toolServers.envHint": "Variables de entorno adicionales como objeto JSON. Se combinan con el PATH heredado al lanzar el proceso.",
|
||||
"toolServers.envInvalid": "El entorno debe ser un objeto JSON válido",
|
||||
"toolServers.commandRequired": "El comando es obligatorio para servidores stdio",
|
||||
"toolServers.connectionFailed": "Conexión fallida",
|
||||
"toolServers.apiKeyKeep": "•••••••• (dejar vacío para mantener)",
|
||||
|
||||
@@ -868,6 +868,9 @@
|
||||
"toolServers.args": "Paramètres",
|
||||
"toolServers.cwd": "Répertoire de travail",
|
||||
"toolServers.cwdPlaceholder": "Facultatif (système par défaut)",
|
||||
"toolServers.env": "Environnement",
|
||||
"toolServers.envHint": "Variables d'environnement supplémentaires en JSON. Fusionnées avec le PATH hérité au lancement du processus.",
|
||||
"toolServers.envInvalid": "L'environnement doit être un objet JSON valide",
|
||||
"toolServers.commandRequired": "La commande est requise pour les serveurs stdio",
|
||||
"toolServers.connectionFailed": "Échec de la connexion",
|
||||
"toolServers.apiKeyKeep": "•••••••• (laisser vide pour conserver)",
|
||||
|
||||
@@ -868,6 +868,9 @@
|
||||
"toolServers.args": "引数",
|
||||
"toolServers.cwd": "作業ディレクトリ",
|
||||
"toolServers.cwdPlaceholder": "任意(既定はシステム)",
|
||||
"toolServers.env": "環境変数",
|
||||
"toolServers.envHint": "JSON オブジェクト形式の追加環境変数。プロセス起動時に継承された PATH とマージされます。",
|
||||
"toolServers.envInvalid": "環境変数は有効なJSONオブジェクトである必要があります",
|
||||
"toolServers.commandRequired": "stdio サーバーにはコマンドが必要です",
|
||||
"toolServers.connectionFailed": "接続に失敗しました",
|
||||
"toolServers.apiKeyKeep": "••••••••(空のままで保持)",
|
||||
|
||||
@@ -868,6 +868,9 @@
|
||||
"toolServers.args": "인수",
|
||||
"toolServers.cwd": "작업 디렉터리",
|
||||
"toolServers.cwdPlaceholder": "선택 사항(기본값은 시스템)",
|
||||
"toolServers.env": "환경 변수",
|
||||
"toolServers.envHint": "추가 환경 변수를 JSON 객체로 입력합니다. 프로세스를 시작할 때 상속된 PATH 와 병합됩니다.",
|
||||
"toolServers.envInvalid": "환경 변수는 유효한 JSON 객체여야 합니다",
|
||||
"toolServers.commandRequired": "stdio 서버에는 명령이 필요합니다",
|
||||
"toolServers.connectionFailed": "연결 실패",
|
||||
"toolServers.apiKeyKeep": "•••••••• (유지하려면 비워두세요)",
|
||||
|
||||
@@ -868,6 +868,9 @@
|
||||
"toolServers.args": "Argumentos",
|
||||
"toolServers.cwd": "Diretório de trabalho",
|
||||
"toolServers.cwdPlaceholder": "Opcional (padrão do sistema)",
|
||||
"toolServers.env": "Ambiente",
|
||||
"toolServers.envHint": "Variáveis de ambiente adicionais como objeto JSON. Mescladas com o PATH herdado ao iniciar o processo.",
|
||||
"toolServers.envInvalid": "O ambiente deve ser um objeto JSON válido",
|
||||
"toolServers.commandRequired": "Comando é obrigatório para servidores stdio",
|
||||
"toolServers.connectionFailed": "Falha na conexão",
|
||||
"toolServers.apiKeyKeep": "•••••••• (deixe vazio para manter)",
|
||||
|
||||
@@ -868,6 +868,9 @@
|
||||
"toolServers.args": "Аргументы",
|
||||
"toolServers.cwd": "Рабочий каталог",
|
||||
"toolServers.cwdPlaceholder": "Необязательно (по умолчанию системный)",
|
||||
"toolServers.env": "Окружение",
|
||||
"toolServers.envHint": "Дополнительные переменные окружения в виде JSON-объекта. Объединяются с унаследованным PATH при запуске процесса.",
|
||||
"toolServers.envInvalid": "Окружение должно быть корректным JSON-объектом",
|
||||
"toolServers.commandRequired": "Команда обязательна для stdio-серверов",
|
||||
"toolServers.connectionFailed": "Ошибка подключения",
|
||||
"toolServers.apiKeyKeep": "•••••••• (оставьте пустым для сохранения)",
|
||||
|
||||
@@ -868,6 +868,9 @@
|
||||
"toolServers.args": "参数",
|
||||
"toolServers.cwd": "工作目录",
|
||||
"toolServers.cwdPlaceholder": "可选(默认为系统)",
|
||||
"toolServers.env": "环境变量",
|
||||
"toolServers.envHint": "以 JSON 对象形式提供的附加环境变量。启动进程时会与继承的 PATH 合并。",
|
||||
"toolServers.envInvalid": "环境变量必须是有效的 JSON 对象",
|
||||
"toolServers.commandRequired": "stdio 服务器需要命令",
|
||||
"toolServers.connectionFailed": "连接失败",
|
||||
"toolServers.apiKeyKeep": "••••••••(留空以保持不变)",
|
||||
|
||||
@@ -868,6 +868,9 @@
|
||||
"toolServers.args": "引數",
|
||||
"toolServers.cwd": "工作目錄",
|
||||
"toolServers.cwdPlaceholder": "選填(預設為系統)",
|
||||
"toolServers.env": "環境變數",
|
||||
"toolServers.envHint": "以 JSON 物件形式提供的附加環境變數。啟動進程時會與繼承的 PATH 合併。",
|
||||
"toolServers.envInvalid": "環境變數必須是有效的 JSON 物件",
|
||||
"toolServers.commandRequired": "stdio 伺服器需要命令",
|
||||
"toolServers.connectionFailed": "連線失敗",
|
||||
"toolServers.apiKeyKeep": "••••••••(留空以保持不變)",
|
||||
|
||||
@@ -81,6 +81,9 @@ class MCPClient:
|
||||
env: Optional environment variables for the process.
|
||||
cwd: Optional working directory.
|
||||
"""
|
||||
command = command.strip()
|
||||
if len(command) > 1 and command[0] == command[-1] and command[0] in ("'", '"'):
|
||||
command = command[1:-1]
|
||||
params = StdioServerParameters(
|
||||
command=command,
|
||||
args=args or [],
|
||||
|
||||
+2
-2
@@ -25,11 +25,11 @@ dependencies = [
|
||||
|
||||
[project.optional-dependencies]
|
||||
pam = ["python-pam>=2.0"]
|
||||
mcp = ["mcp>=1.8"]
|
||||
mcp = ["mcp>=1.8,<2"]
|
||||
docs = ["pypdf>=4.0", "python-docx>=1.0", "openpyxl>=3.1"]
|
||||
agents = ["claude-agent-sdk>=0.1.62"]
|
||||
all = [
|
||||
"mcp>=1.8",
|
||||
"mcp>=1.8,<2",
|
||||
"pypdf>=4.0",
|
||||
"python-docx>=1.0",
|
||||
"openpyxl>=3.1",
|
||||
|
||||
@@ -345,8 +345,8 @@ requires-dist = [
|
||||
{ name = "fastapi", extras = ["standard"], specifier = ">=0.128.8" },
|
||||
{ name = "httpx", specifier = ">=0.28.1" },
|
||||
{ name = "loguru", specifier = ">=0.7.3" },
|
||||
{ name = "mcp", marker = "extra == 'all'", specifier = ">=1.8" },
|
||||
{ name = "mcp", marker = "extra == 'mcp'", specifier = ">=1.8" },
|
||||
{ name = "mcp", marker = "extra == 'all'", specifier = ">=1.8,<2" },
|
||||
{ name = "mcp", marker = "extra == 'mcp'", specifier = ">=1.8,<2" },
|
||||
{ name = "openpyxl", marker = "extra == 'all'", specifier = ">=3.1" },
|
||||
{ name = "openpyxl", marker = "extra == 'docs'", specifier = ">=3.1" },
|
||||
{ name = "pyjwt", specifier = ">=2.8" },
|
||||
|
||||
Reference in new issue
Block a user