From 4720ff19e711d01f48d2b732dcbac63205221f5d Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Fri, 13 Nov 2026 17:36:00 +0900 Subject: [PATCH] refac --- backend/open_webui/config.py | 12 - backend/open_webui/main.py | 96 +--- backend/open_webui/routers/audio/realtime.py | 2 +- backend/open_webui/routers/chats.py | 8 +- backend/open_webui/routers/configs.py | 4 - backend/open_webui/routers/models.py | 2 +- backend/open_webui/routers/openai.py | 95 +++- backend/open_webui/routers/tasks.py | 65 +-- backend/open_webui/routers/templates.py | 68 ++- backend/open_webui/routers/terminals.py | 36 +- backend/open_webui/routers/tether.py | 36 +- backend/open_webui/routers/tools.py | 14 + backend/open_webui/routers/users.py | 13 - backend/open_webui/socket/main.py | 64 --- backend/open_webui/utils/actions.py | 14 +- backend/open_webui/utils/agents/transport.py | 4 +- backend/open_webui/utils/automations.py | 1 + backend/open_webui/utils/chat.py | 352 +++++-------- .../open_webui/utils/context_compaction.py | 4 +- backend/open_webui/utils/embeddings.py | 15 +- backend/open_webui/utils/middleware.py | 119 +---- backend/open_webui/utils/models.py | 11 + backend/open_webui/utils/subagents.py | 6 - backend/open_webui/utils/terminals.py | 104 ++-- backend/open_webui/utils/tether.py | 80 ++- backend/open_webui/utils/timers.py | 2 - backend/open_webui/utils/tool_approval.py | 1 - backend/open_webui/utils/tools.py | 223 ++++++--- src/lib/apis/configs/index.ts | 37 -- src/lib/apis/index.ts | 471 +----------------- src/lib/apis/openai/index.ts | 95 +--- src/lib/apis/terminal/index.ts | 29 +- src/lib/components/AddConnectionModal.svelte | 132 +++-- .../components/AddTerminalServerModal.svelte | 102 ++-- src/lib/components/AddToolServerModal.svelte | 290 +++++------ src/lib/components/AutomationModal.svelte | 5 +- src/lib/components/admin/Functions.svelte | 46 +- .../admin/Settings/Connections.svelte | 21 +- .../admin/Settings/Evaluations.svelte | 16 +- .../admin/Settings/Integrations.svelte | 40 +- .../components/admin/Settings/Models.svelte | 37 +- .../Models/Manage/ManageOllama.svelte | 28 +- .../Models/Manage/ManageProviderModels.svelte | 7 +- .../admin/Settings/Pipelines.svelte | 36 +- .../admin/Users/Groups/Permissions.svelte | 21 - .../channel/MessageInput/MentionList.svelte | 2 +- src/lib/components/chat/Chat.svelte | 218 ++++---- src/lib/components/chat/FileNav.svelte | 14 +- src/lib/components/chat/MessageInput.svelte | 46 +- .../MessageInput/Commands/AtCommands.svelte | 7 +- .../chat/MessageInput/Commands/Skills.svelte | 5 +- .../Commands/SlashCommands.svelte | 5 +- .../chat/MessageInput/IntegrationsMenu.svelte | 37 +- .../chat/MessageInput/ModelControls.svelte | 2 +- .../chat/MessageInput/TerminalMenu.svelte | 106 +--- .../chat/Messages/ToolOutputFile.svelte | 19 +- .../chat/ModelSelector/ModelItem.svelte | 41 -- .../chat/ModelSelector/ModelItemMenu.svelte | 2 +- .../chat/ModelSelector/Selector.svelte | 42 +- .../chat/Settings/Connections.svelte | 171 ------- .../Settings/Connections/Connection.svelte | 93 ---- .../chat/Settings/Integrations.svelte | 202 -------- .../Settings/Integrations/Terminals.svelte | 104 ---- .../Integrations/Terminals/Connection.svelte | 97 ---- .../chat/Settings/Tools/Connection.svelte | 6 +- src/lib/components/chat/SettingsModal.svelte | 77 +-- src/lib/components/chat/Tabs.svelte | 179 +++---- src/lib/components/chat/TerminalDock.svelte | 5 +- .../components/chat/ToolServersModal.svelte | 11 +- .../components/chat/UserTerminalsModal.svelte | 2 +- .../common/InterfaceSettings.svelte | 9 +- .../common/RichTextInput/Collaboration.ts | 236 ++++++--- .../layout/Sidebar/Folders/FolderModal.svelte | 13 +- src/lib/components/workspace/Models.svelte | 30 +- .../workspace/Models/Capabilities.svelte | 3 +- .../workspace/Models/CreateModel.svelte | 9 +- .../workspace/Models/EditModel.svelte | 9 +- .../workspace/Models/ModelEditor.svelte | 16 +- src/lib/constants/permissions.ts | 1 - src/lib/i18n/locales/ar-BH/translation.json | 178 +++++-- src/lib/i18n/locales/ar/translation.json | 178 +++++-- src/lib/i18n/locales/az-AZ/translation.json | 166 ++++-- src/lib/i18n/locales/bg-BG/translation.json | 166 ++++-- src/lib/i18n/locales/bn-BD/translation.json | 166 ++++-- src/lib/i18n/locales/bo-TB/translation.json | 163 ++++-- src/lib/i18n/locales/bs-BA/translation.json | 169 +++++-- src/lib/i18n/locales/ca-ES/translation.json | 169 +++++-- src/lib/i18n/locales/ceb-PH/translation.json | 166 ++++-- src/lib/i18n/locales/cs-CZ/translation.json | 172 +++++-- src/lib/i18n/locales/da-DK/translation.json | 166 ++++-- src/lib/i18n/locales/de-DE/translation.json | 166 ++++-- src/lib/i18n/locales/dg-DG/translation.json | 166 ++++-- src/lib/i18n/locales/el-GR/translation.json | 166 ++++-- src/lib/i18n/locales/en-GB/translation.json | 166 ++++-- src/lib/i18n/locales/en-US/translation.json | 172 +++++-- src/lib/i18n/locales/es-ES/translation.json | 169 +++++-- src/lib/i18n/locales/et-EE/translation.json | 166 ++++-- src/lib/i18n/locales/eu-ES/translation.json | 166 ++++-- src/lib/i18n/locales/fa-IR/translation.json | 260 ++++++---- src/lib/i18n/locales/fi-FI/translation.json | 166 ++++-- src/lib/i18n/locales/fil-PH/translation.json | 166 ++++-- src/lib/i18n/locales/fo-FO/translation.json | 166 ++++-- src/lib/i18n/locales/fr-CA/translation.json | 169 +++++-- src/lib/i18n/locales/fr-FR/translation.json | 169 +++++-- src/lib/i18n/locales/gl-ES/translation.json | 166 ++++-- src/lib/i18n/locales/he-IL/translation.json | 169 +++++-- src/lib/i18n/locales/hi-IN/translation.json | 166 ++++-- src/lib/i18n/locales/hr-HR/translation.json | 169 +++++-- src/lib/i18n/locales/hu-HU/translation.json | 166 ++++-- src/lib/i18n/locales/id-ID/translation.json | 164 ++++-- src/lib/i18n/locales/ie-GA/translation.json | 166 ++++-- src/lib/i18n/locales/it-IT/translation.json | 169 +++++-- src/lib/i18n/locales/ja-JP/translation.json | 164 ++++-- src/lib/i18n/locales/ka-GE/translation.json | 166 ++++-- src/lib/i18n/locales/kab-DZ/translation.json | 166 ++++-- src/lib/i18n/locales/ko-KR/translation.json | 163 ++++-- src/lib/i18n/locales/lt-LT/translation.json | 172 +++++-- src/lib/i18n/locales/lv-LV/translation.json | 169 +++++-- src/lib/i18n/locales/ms-MY/translation.json | 164 ++++-- src/lib/i18n/locales/nb-NO/translation.json | 166 ++++-- src/lib/i18n/locales/nl-NL/translation.json | 166 ++++-- src/lib/i18n/locales/pa-IN/translation.json | 166 ++++-- src/lib/i18n/locales/pl-PL/translation.json | 172 +++++-- src/lib/i18n/locales/pt-BR/translation.json | 169 +++++-- src/lib/i18n/locales/pt-PT/translation.json | 169 +++++-- src/lib/i18n/locales/ro-RO/translation.json | 169 +++++-- src/lib/i18n/locales/ru-RU/translation.json | 172 +++++-- src/lib/i18n/locales/sk-SK/translation.json | 172 +++++-- src/lib/i18n/locales/sl-SI/translation.json | 172 +++++-- src/lib/i18n/locales/sr-RS/translation.json | 169 +++++-- src/lib/i18n/locales/sv-SE/translation.json | 166 ++++-- src/lib/i18n/locales/ta-IN/translation.json | 166 ++++-- src/lib/i18n/locales/th-TH/translation.json | 163 ++++-- src/lib/i18n/locales/tk-TM/translation.json | 166 ++++-- src/lib/i18n/locales/tr-TR/translation.json | 166 ++++-- src/lib/i18n/locales/ug-CN/translation.json | 166 ++++-- src/lib/i18n/locales/uk-UA/translation.json | 172 +++++-- src/lib/i18n/locales/ur-PK/translation.json | 166 ++++-- .../i18n/locales/uz-Cyrl-UZ/translation.json | 166 ++++-- .../i18n/locales/uz-Latn-UZ/translation.json | 166 ++++-- src/lib/i18n/locales/vi-VN/translation.json | 163 ++++-- src/lib/i18n/locales/zh-CN/translation.json | 164 ++++-- src/lib/i18n/locales/zh-TW/translation.json | 163 ++++-- src/lib/stores/folderStates.ts | 9 +- src/lib/stores/index.ts | 10 +- src/lib/utils/channelMentions.ts | 4 +- src/lib/utils/terminal.ts | 50 +- src/routes/(app)/+layout.svelte | 83 +-- .../(app)/admin/functions/create/+page.svelte | 9 +- .../(app)/admin/functions/edit/+page.svelte | 22 +- .../(app)/workspace/models/+page.svelte | 7 +- src/routes/+layout.svelte | 277 +--------- src/routes/s/[id]/+page.svelte | 7 +- 153 files changed, 9782 insertions(+), 6185 deletions(-) delete mode 100644 src/lib/components/chat/Settings/Connections.svelte delete mode 100644 src/lib/components/chat/Settings/Connections/Connection.svelte delete mode 100644 src/lib/components/chat/Settings/Integrations.svelte delete mode 100644 src/lib/components/chat/Settings/Integrations/Terminals.svelte delete mode 100644 src/lib/components/chat/Settings/Integrations/Terminals/Connection.svelte diff --git a/backend/open_webui/config.py b/backend/open_webui/config.py index 6a10bd03fa..7d3caf0d9f 100644 --- a/backend/open_webui/config.py +++ b/backend/open_webui/config.py @@ -219,11 +219,6 @@ if CUSTOM_NAME: pass -# Direct connections - -ENABLE_DIRECT_CONNECTIONS = os.getenv('ENABLE_DIRECT_CONNECTIONS', 'False').lower() == 'true' -ENABLE_DIRECT_INTEGRATIONS = os.getenv('ENABLE_DIRECT_INTEGRATIONS', 'False').lower() == 'true' - # OLLAMA_BASE_URL ENABLE_OLLAMA_API = os.getenv('ENABLE_OLLAMA_API', 'True').lower() == 'true' @@ -1936,10 +1931,6 @@ USER_PERMISSIONS_CHAT_TEMPORARY_ENFORCED = ( ) -USER_PERMISSIONS_FEATURES_DIRECT_TOOL_SERVERS = ( - os.getenv('USER_PERMISSIONS_FEATURES_DIRECT_TOOL_SERVERS', 'False').lower() == 'true' -) - USER_PERMISSIONS_FEATURES_WEB_SEARCH = os.getenv('USER_PERMISSIONS_FEATURES_WEB_SEARCH', 'True').lower() == 'true' USER_PERMISSIONS_FEATURES_IMAGE_GENERATION = ( @@ -2048,7 +2039,6 @@ DEFAULT_USER_PERMISSIONS = { 'folders': USER_PERMISSIONS_FEATURES_FOLDERS, 'channels': USER_PERMISSIONS_FEATURES_CHANNELS, 'encrypted_channels': USER_PERMISSIONS_FEATURES_ENCRYPTED_CHANNELS, - 'direct_tool_servers': USER_PERMISSIONS_FEATURES_DIRECT_TOOL_SERVERS, # Chat features 'web_search': USER_PERMISSIONS_FEATURES_WEB_SEARCH, 'image_generation': USER_PERMISSIONS_FEATURES_IMAGE_GENERATION, @@ -2967,8 +2957,6 @@ DEFAULT_CONFIG = { 'skills.content_max_chars': SKILL_CONTENT_MAX_CHARS, 'skills.preview_max_chars': SKILL_PREVIEW_MAX_CHARS, 'chats.view_max_chars': VIEW_CHAT_MAX_CHARS, - 'direct.enable': ENABLE_DIRECT_CONNECTIONS, - 'direct.integrations.enable': ENABLE_DIRECT_INTEGRATIONS, 'ollama.enable': ENABLE_OLLAMA_API, 'ollama.base_urls': OLLAMA_BASE_URLS, 'ollama.api_configs': OLLAMA_API_CONFIGS, diff --git a/backend/open_webui/main.py b/backend/open_webui/main.py index 8b09289101..86184b0b33 100644 --- a/backend/open_webui/main.py +++ b/backend/open_webui/main.py @@ -199,7 +199,6 @@ from open_webui.socket.main import ( periodic_session_pool_cleanup, periodic_socket_authentication, periodic_usage_pool_cleanup, - redis_event_listener, sio, ) from open_webui.socket.main import ( @@ -268,6 +267,7 @@ from open_webui.utils.models import ( get_all_models, get_filtered_models, ) +from open_webui.routers.openai import get_tether_model, get_tether_models from open_webui.utils.payload import apply_model_controls from open_webui.utils.oauth import ( OAuthClientInformationFull, @@ -437,7 +437,6 @@ async def lifespan(app: FastAPI): app.state.redis_task_heartbeat = asyncio.create_task(redis_task_heartbeat(app)) if WEBSOCKET_MANAGER == 'redis': - app.state.redis_event_listener = asyncio.create_task(redis_event_listener()) # socket.io only starts listening on its first connect; event call answers need it earlier sio.manager_initialized = True sio.manager.initialize() @@ -535,9 +534,6 @@ async def lifespan(app: FastAPI): if hasattr(app.state, 'redis_task_heartbeat'): app.state.redis_task_heartbeat.cancel() - if hasattr(app.state, 'redis_event_listener'): - app.state.redis_event_listener.cancel() - app.state.periodic_socket_authentication.cancel() app.state.periodic_usage_pool_cleanup.cancel() app.state.periodic_session_pool_cleanup.cancel() @@ -898,6 +894,12 @@ async def get_models( # models the caller can actually see. models = await get_filtered_models(models, user) + # The user's own connections, reached through their Tether. Shared models win on id clashes. + if refresh: + await get_tether_models.cache.clear() + known = {model['id'] for model in models} + models.extend(model for model in (await get_tether_models(user)).values() if model['id'] not in known) + for model in models: info = model.get('info') if isinstance(model.get('info'), dict) else {} meta = info.get('meta') if isinstance(info.get('meta'), dict) else {} @@ -1089,17 +1091,6 @@ async def embeddings(request: Request, form_data: dict, user=Depends(get_verifie return await generate_embeddings(request, form_data, user) -async def _set_direct_model(request: Request, model_item: dict, user) -> None: - model_meta = (model_item.get('info') or {}).get('meta') or {} - knowledge_items = model_meta.get('knowledge') - if knowledge_items: - from open_webui.utils.access_control.files import get_accessible_folder_files - - model_meta['knowledge'] = await get_accessible_folder_files(knowledge_items, user) - request.state.direct = True - request.state.model = model_item - - @app.post('/api/chat/completions') @app.post('/api/v1/chat/completions') # Experimental: Compatibility with OpenAI API async def chat_completion( @@ -1112,7 +1103,6 @@ async def chat_completion( model_id = form_data.get('model', None) request.state.model_id = model_id - model_item = form_data.pop('model_item', {}) tasks = form_data.pop('background_tasks', None) from open_webui.utils.terminals import get_folder_terminal_defaults, initialize_terminal_directory @@ -1145,18 +1135,21 @@ async def chat_completion( agent_model = next((item for item in candidates if item['id'] == model_id), None) if agent_model is None: raise HTTPException(400, 'Agent model is unavailable in the selected terminal') - model_item = {} # Never trust client-supplied model metadata or direct-provider flags. metadata = {} try: model_info = None fallback_model = None missing_base_model = False - if not model_item.get('direct', False): - if agent_model is None and model_id not in request.app.state.MODELS: + tether_model = None + if agent_model is None and model_id not in request.app.state.MODELS: + # The user's own connection, reached through their Tether. + tether_model = await get_tether_model(request, user, model_id) + if tether_model is None: raise Exception('Model not found') - model = agent_model or request.app.state.MODELS[model_id] + model = agent_model or tether_model or request.app.state.MODELS[model_id] + if tether_model is None: model_info = await Models.get_model_by_id(model_id) missing_base_model = bool( model_info and model_info.base_model_id and model_info.base_model_id not in request.app.state.MODELS @@ -1191,9 +1184,6 @@ async def chat_completion( await check_model_access(user, fallback_model) except Exception as e: raise e - else: - model = model_item - await _set_direct_model(request, model, user) # Read before the fallback below can rebind model to a different one. model_capabilities = ((model.get('info') or {}).get('meta') or {}).get('capabilities') or {} @@ -1281,22 +1271,6 @@ async def chat_completion( chat_variables = normalize_chat_variables(chat_variables) - # Drop tool_servers if caller lacks features.direct_tool_servers — - # mirrors the storage-side strip in user/settings/update. - tool_servers = form_data.pop('tool_servers', None) - if ( - tool_servers - and user.role != 'admin' - and not await has_permission( - user.id, - 'features.direct_tool_servers', - await Config.get('user.permissions'), - ) - ): - tool_servers = None - if tool_servers and not await Config.get('direct.integrations.enable', False): - tool_servers = None - automation_id = form_data.pop('automation_id', None) from open_webui.utils.tool_permissions import resolve_tool_approval_mode @@ -1324,7 +1298,6 @@ async def chat_completion( 'folder_id': form_data.pop('folder_id', None), 'filter_ids': form_data.pop('filter_ids', []), 'tool_ids': form_data.get('tool_ids', None), - 'tool_servers': tool_servers, 'files': form_data.get('files', None), 'features': form_data.get('features', {}), 'variables': form_data.get('variables', {}), @@ -1342,7 +1315,6 @@ async def chat_completion( 'chat_variables': copy.deepcopy(chat_variables), }, 'model': model, - 'direct': model_item.get('direct', False), 'params': { 'stream_delta_chunk_size': stream_delta_chunk_size, 'reasoning_tags': reasoning_tags, @@ -1669,20 +1641,17 @@ async def chat_completion( response_meta.pop('response_ended_at', None) message['meta'] = response_meta message['done'] = False - if not metadata.get('direct'): - target = ( - model_info - if form_data['model'] == model_id - else await Models.get_model_by_id(form_data['model']) - ) - controls = target.params.model_dump().get('model_controls', {}) if target else {} - if model.get('agent'): - controls = model.get('info', {}).get('params', {}).get('model_controls', {}) - form_data['params'] = apply_model_controls( - copy.deepcopy(form_data.get('params') or {}), - controls, - model_controls.get(form_data['model'], {}), - ) + target = ( + model_info if form_data['model'] == model_id else await Models.get_model_by_id(form_data['model']) + ) + controls = target.params.model_dump().get('model_controls', {}) if target else {} + if model.get('agent'): + controls = model.get('info', {}).get('params', {}).get('model_controls', {}) + form_data['params'] = apply_model_controls( + copy.deepcopy(form_data.get('params') or {}), + controls, + model_controls.get(form_data['model'], {}), + ) ctx = None if is_new_chat: await initialize_terminal_directory( @@ -2187,11 +2156,6 @@ async def chat_completed(request: Request, form_data: dict, user=Depends(get_ver await verify_chat_ownership(form_data.get('chat_id'), user) try: - model_item = form_data.pop('model_item', {}) - - if model_item.get('direct', False): - await _set_direct_model(request, model_item, user) - return await chat_completed_handler(request, form_data, user) except Exception as e: raise HTTPException( @@ -2205,11 +2169,6 @@ async def chat_action(request: Request, action_id: str, form_data: dict, user=De await verify_chat_ownership(form_data.get('chat_id'), user) try: - model_item = form_data.pop('model_item', {}) - - if model_item.get('direct', False): - await _set_direct_model(request, model_item, user) - return await chat_action_handler(request, action_id, form_data, user) except Exception as e: raise HTTPException( @@ -2408,8 +2367,6 @@ async def get_app_config(request: Request): 'ui.enable_login_form', 'auth.enable_api_keys', 'ui.enable_password_change_form', - 'direct.enable', - 'direct.integrations.enable', 'terminal_server.connections', 'folders.enable', 'folders.max_file_count', @@ -2514,9 +2471,6 @@ async def get_app_config(request: Request): 'enable_pyodide_file_persistence': ENABLE_PYODIDE_FILE_PERSISTENCE, 'enable_public_active_users_count': ENABLE_PUBLIC_ACTIVE_USERS_COUNT, 'enable_easter_eggs': ENABLE_EASTER_EGGS, - 'enable_direct_connections': config.get('direct.enable'), - 'enable_direct_integrations': ENABLE_TOOL_SERVERS - and config.get('direct.integrations.enable', False), 'enable_plugins': ENABLE_PLUGINS, 'enable_tools': ENABLE_TOOLS, 'enable_functions': ENABLE_FUNCTIONS, diff --git a/backend/open_webui/routers/audio/realtime.py b/backend/open_webui/routers/audio/realtime.py index 463148efc1..eea7605420 100644 --- a/backend/open_webui/routers/audio/realtime.py +++ b/backend/open_webui/routers/audio/realtime.py @@ -425,7 +425,7 @@ async def realtime_call(ws: WebSocket): if not ws.app.state.MODELS: await get_all_models(ws, user=user) model = ws.app.state.MODELS.get(model_id) - if not model or model.get('direct'): + if not model: raise ValueError('Bridge requires a server-configured chat model') model_info = await Models.get_model_by_id(model_id) if ( diff --git a/backend/open_webui/routers/chats.py b/backend/open_webui/routers/chats.py index 8d2c585a3b..01ad242128 100644 --- a/backend/open_webui/routers/chats.py +++ b/backend/open_webui/routers/chats.py @@ -1513,12 +1513,16 @@ async def update_chat_by_id( and set(form_data.chat) <= {'models', 'terminal_id', 'working_directory'} and await Chats.has_chat_access(id, user, db=db, permission='write', chat=chat) ): - folder = await Folders.get_folder_by_id_and_user_id(chat.folder_id, user.id, db=db) if chat.folder_id else None + folder = ( + await Folders.get_folder_by_id_and_user_id(chat.folder_id, user.id, db=db) if chat.folder_id else None + ) if not folder or set(form_data.chat) != {'title'}: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) title = form_data.chat['title'] if not isinstance(title, str) or not title.strip(): - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT('Invalid title')) + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT('Invalid title') + ) form_data.chat['title'] = title.strip() if chat: set_message_authors(form_data.chat, user) diff --git a/backend/open_webui/routers/configs.py b/backend/open_webui/routers/configs.py index 7e5244ab37..0b848ac26b 100644 --- a/backend/open_webui/routers/configs.py +++ b/backend/open_webui/routers/configs.py @@ -38,8 +38,6 @@ router = APIRouter() log = logging.getLogger(__name__) CONNECTIONS_CONFIG_KEYS = { - 'ENABLE_DIRECT_CONNECTIONS': 'direct.enable', - 'ENABLE_DIRECT_INTEGRATIONS': 'direct.integrations.enable', 'ENABLE_BASE_MODELS_CACHE': 'models.base_models_cache', } CODE_EXECUTION_CONFIG_KEYS = { @@ -145,8 +143,6 @@ async def set_interface_visibility(request: Request, form_data: InterfaceVisibil class ConnectionsConfigForm(BaseModel): - ENABLE_DIRECT_CONNECTIONS: bool - ENABLE_DIRECT_INTEGRATIONS: bool = False ENABLE_BASE_MODELS_CACHE: bool diff --git a/backend/open_webui/routers/models.py b/backend/open_webui/routers/models.py index 91558b0c04..918700b290 100644 --- a/backend/open_webui/routers/models.py +++ b/backend/open_webui/routers/models.py @@ -85,7 +85,7 @@ async def _check_model_controls(form, previous, user, request): if not request.app.state.MODELS: await get_all_models(request, user=user) base = request.app.state.MODELS.get(form.base_model_id or form.id, {}) - if 'pipe' in base or base.get('direct') or base.get('owned_by') == 'arena': + if 'pipe' in base or base.get('owned_by') == 'arena': raise HTTPException(400, 'Model controls require a server-managed provider model.') diff --git a/backend/open_webui/routers/openai.py b/backend/open_webui/routers/openai.py index e174ea71f1..76a4507b49 100644 --- a/backend/open_webui/routers/openai.py +++ b/backend/open_webui/routers/openai.py @@ -37,11 +37,12 @@ from open_webui.models.access_grants import AccessGrants from open_webui.models.config import Config from open_webui.models.groups import Groups from open_webui.models.models import Models +from open_webui.utils.tether import RelayClient, get_tether_connections from open_webui.models.users import UserModel from open_webui.utils.access_control import check_model_access, has_connection_access, has_permission from open_webui.utils.anthropic import ANTHROPIC_VERSION, get_anthropic_models, is_anthropic_url from open_webui.utils.auth import get_admin_user, get_verified_user -from open_webui.utils.headers import get_headers_and_cookies, include_user_info_headers +from open_webui.utils.headers import bearer_auth_header, get_headers_and_cookies, include_user_info_headers from open_webui.utils.json_codec import JSONCodec from open_webui.utils.misc import convert_logit_bias_input_to_json, get_provider_function, merge_tool_call_batches from open_webui.utils.model_ids import strip_provider_model_prefix @@ -254,8 +255,55 @@ async def get_openai_connection(idx: int) -> tuple[str, str, dict]: return url, key, api_config +@cached(ttl=MODELS_CACHE_TTL, key_builder=lambda _func, user: f'openai_tether_models_{user.id}') +async def get_tether_models(user) -> dict[str, dict]: + """Models of the OpenAI-compatible connections the user added in Tether, listed through it.""" + + async def fetch(presence, item) -> list[dict]: + base_url = f'tether://{presence["connection_id"]}' + async with RelayClient(user.id, item['service'], timeout=10) as client: + async with client.get(f'{base_url}/models') as response: + if response.status >= 400: + raise RuntimeError(f'HTTP {response.status}') + ids = [model['id'] for model in (await response.json()).get('data', []) if model.get('id')] + return [ + { + 'id': model_id, + 'name': model_id, + 'object': 'model', + 'created': int(time.time()), + 'owned_by': 'openai', + 'connection_type': 'local', + 'tags': [{'name': f'{presence["name"]} · {item["name"]}'}], + 'owner_id': user.id, + 'base_url': base_url, + 'service': item['service'], + } + for model_id in ids + ] + + sources = await get_tether_connections(user.id, 'openai') + results = await asyncio.gather(*(fetch(*source) for source in sources), return_exceptions=True) + models = {} + for (presence, item), result in zip(sources, results): + if isinstance(result, BaseException): + log.info('Could not list models from %s on %s: %s', item['name'], presence['name'], result) + continue + for model in result: + models.setdefault(model['id'], model) + return models + + +async def get_tether_model(request: Request, user, model_id) -> dict | None: + """The user's own model with this id, unless a shared model already has it.""" + if not user or not isinstance(model_id, str) or request.app.state.MODELS.get(model_id) is not None: + return None + return (await get_tether_models(user)).get(model_id) + + async def clear_models_cache(request: Request): await get_all_models.cache.clear() + await get_tether_models.cache.clear() redis = getattr(request.app.state, 'redis', None) if redis is not None: await redis.delete(BASE_MODELS_CACHE_KEY) @@ -1432,6 +1480,8 @@ async def generate_chat_completion( if not hasattr(request.state, 'model_id'): request.state.model_id = model_id model_info = await Models.get_model_by_id(model_id) + # The user's own connection, reached through their Tether. Only they can resolve it. + tether_model = None if model_info else await get_tether_model(request, user, model_id) # Check model info and override the payload if model_info: @@ -1452,25 +1502,32 @@ async def generate_chat_completion( payload = await apply_system_prompt_to_body(system, payload, metadata, user) await check_model_access(user, model_info, bypass_filter) - else: + elif tether_model is None: await check_model_access(user, None, bypass_filter) - # Check if model is already in app state cache to avoid expensive get_all_models() call - models = request.app.state.OPENAI_MODELS - if not models or model_id not in models: - await get_all_models(request, user=user) - models = request.app.state.OPENAI_MODELS - model = models.get(model_id) - - if model: - idx = model['urlIdx'] + # `relay` is closed with the response; the shared pool session never is. + session = relay = None + if tether_model is not None: + # Tether adds the key; the URL and key never reach this server. + model, url, key, api_config = tether_model, tether_model['base_url'], '', {} + session = relay = RelayClient(user.id, tether_model['service']) else: - raise HTTPException( - status_code=404, - detail=ERROR_MESSAGES.MODEL_NOT_FOUND(), - ) + # Check if model is already in app state cache to avoid expensive get_all_models() call + models = request.app.state.OPENAI_MODELS + if not models or model_id not in models: + await get_all_models(request, user=user) + models = request.app.state.OPENAI_MODELS + model = models.get(model_id) - url, key, api_config = await get_openai_connection(idx) + if model: + idx = model['urlIdx'] + else: + raise HTTPException( + status_code=404, + detail=ERROR_MESSAGES.MODEL_NOT_FOUND(), + ) + + url, key, api_config = await get_openai_connection(idx) prefix_id = api_config.get('prefix_id', None) payload['model'] = strip_provider_model_prefix(payload['model'], prefix_id) @@ -1580,7 +1637,7 @@ async def generate_chat_completion( response = None try: - session = await get_session() + session = session or await get_session() r = await session.request( method='POST', @@ -1637,7 +1694,7 @@ async def generate_chat_completion( streaming = True return StreamingResponse( - stream_wrapper(r), + stream_wrapper(r, relay), status_code=r.status, headers=_clean_proxy_headers(r.headers), ) @@ -1679,7 +1736,7 @@ async def generate_chat_completion( ) finally: if not streaming: - await cleanup_response(r) + await cleanup_response(r, relay) async def embeddings(request: Request, form_data: dict, user): diff --git a/backend/open_webui/routers/tasks.py b/backend/open_webui/routers/tasks.py index 039396fcc8..7684a1479a 100644 --- a/backend/open_webui/routers/tasks.py +++ b/backend/open_webui/routers/tasks.py @@ -21,6 +21,7 @@ from open_webui.models.config import Config from open_webui.routers.pipelines import process_pipeline_inlet_filter from open_webui.utils.auth import get_admin_user, get_verified_user from open_webui.utils.chat import generate_chat_completion +from open_webui.utils.models import add_tether_model from open_webui.utils.payload import apply_params_to_form_data from open_webui.utils.task import ( autocomplete_generation_template, @@ -146,13 +147,7 @@ async def generate_title(request: Request, form_data: dict, user=Depends(get_ver content={'detail': 'Title generation is disabled'}, ) - if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'): - models = { - **dict(request.app.state.MODELS.items()), - request.state.model['id']: request.state.model, - } - else: - models = request.app.state.MODELS + models = await add_tether_model(request, user, form_data.get('model')) model_id = form_data['model'] if not model_id: @@ -221,13 +216,7 @@ async def generate_follow_ups(request: Request, form_data: dict, user=Depends(ge content={'detail': 'Follow-up generation is disabled'}, ) - if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'): - models = { - **dict(request.app.state.MODELS.items()), - request.state.model['id']: request.state.model, - } - else: - models = request.app.state.MODELS + models = await add_tether_model(request, user, form_data.get('model')) model_id = form_data['model'] if model_id not in models: @@ -288,13 +277,7 @@ async def generate_chat_tags(request: Request, form_data: dict, user=Depends(get content={'detail': 'Tags generation is disabled'}, ) - if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'): - models = { - **dict(request.app.state.MODELS.items()), - request.state.model['id']: request.state.model, - } - else: - models = request.app.state.MODELS + models = await add_tether_model(request, user, form_data.get('model')) model_id = form_data['model'] if model_id not in models: @@ -347,13 +330,7 @@ async def generate_chat_tags(request: Request, form_data: dict, user=Depends(get @router.post('/image_prompt/completions') async def generate_image_prompt(request: Request, form_data: dict, user=Depends(get_verified_user)): - if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'): - models = { - **dict(request.app.state.MODELS.items()), - request.state.model['id']: request.state.model, - } - else: - models = request.app.state.MODELS + models = await add_tether_model(request, user, form_data.get('model')) model_id = form_data['model'] if model_id not in models: @@ -424,13 +401,7 @@ async def generate_queries(request: Request, form_data: dict, user=Depends(get_v log.info('Reusing cached queries') return request.state.cached_queries - if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'): - models = { - **dict(request.app.state.MODELS.items()), - request.state.model['id']: request.state.model, - } - else: - models = request.app.state.MODELS + models = await add_tether_model(request, user, form_data.get('model')) model_id = form_data['model'] if model_id not in models: @@ -500,13 +471,7 @@ async def generate_autocompletion(request: Request, form_data: dict, user=Depend detail=ERROR_MESSAGES.INPUT_TOO_LONG(autocomplete_input_max_length), ) - if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'): - models = { - **dict(request.app.state.MODELS.items()), - request.state.model['id']: request.state.model, - } - else: - models = request.app.state.MODELS + models = await add_tether_model(request, user, form_data.get('model')) model_id = form_data['model'] if model_id not in models and not model_id.startswith('agent:'): @@ -561,13 +526,7 @@ async def generate_autocompletion(request: Request, form_data: dict, user=Depend @router.post('/emoji/completions') async def generate_emoji(request: Request, form_data: dict, user=Depends(get_verified_user)): - if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'): - models = { - **dict(request.app.state.MODELS.items()), - request.state.model['id']: request.state.model, - } - else: - models = request.app.state.MODELS + models = await add_tether_model(request, user, form_data.get('model')) model_id = form_data['model'] if model_id not in models: @@ -615,13 +574,7 @@ async def generate_emoji(request: Request, form_data: dict, user=Depends(get_ver @router.post('/moa/completions') async def generate_moa_response(request: Request, form_data: dict, user=Depends(get_verified_user)): - if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'): - models = { - **dict(request.app.state.MODELS.items()), - request.state.model['id']: request.state.model, - } - else: - models = request.app.state.MODELS + models = await add_tether_model(request, user, form_data.get('model')) model_id = form_data['model'] diff --git a/backend/open_webui/routers/templates.py b/backend/open_webui/routers/templates.py index 007106fdfe..a0fccd9fd0 100644 --- a/backend/open_webui/routers/templates.py +++ b/backend/open_webui/routers/templates.py @@ -1,4 +1,5 @@ """Template management and context-authorized terminal lifecycle operations.""" + from urllib.parse import quote from uuid import UUID @@ -9,8 +10,13 @@ from open_webui.models.config import Config from open_webui.utils.access_control import validate_access_grants from open_webui.utils.auth import get_verified_user from open_webui.utils.terminals import ( - has_connection_write_access, get_connection, server_request, template_terminal_id, template_connection, - get_terminal_context, find_terminal_connection, + has_connection_write_access, + get_connection, + server_request, + template_terminal_id, + template_connection, + get_terminal_context, + find_terminal_connection, ) router = APIRouter() @@ -38,6 +44,7 @@ def path(template_id, suffix=''): async def changed(user_id, terminal_id, previous=()): from open_webui.socket.main import emit_to_users + current = await AccessGrants.get_grants_by_resource('terminal', terminal_id) recipients = {user_id} recipients.update(await AccessGrants.get_user_ids_by_access_grants([*previous, *current], 'read')) @@ -72,13 +79,14 @@ async def create_template(body: CreateForm, user=Depends(get_verified_user)): connection = await get_connection(user, body.connection_id) if not await has_connection_write_access(user, connection): raise HTTPException(403, 'Creation is not allowed') - row = await server_request(connection, 'api/v1/terminals/templates', method='POST', - body={'id': str(body.id), 'data': body.data}) + row = await server_request( + connection, 'api/v1/terminals/templates', method='POST', body={'id': str(body.id), 'data': body.data} + ) selector = template_terminal_id(connection['id'], row['id']) try: - await AccessGrants.set_access_grants('terminal', selector, [ - {'principal_type': 'user', 'principal_id': user.id, 'permission': 'read'} - ]) + await AccessGrants.set_access_grants( + 'terminal', selector, [{'principal_type': 'user', 'principal_id': user.id, 'permission': 'read'}] + ) except Exception: await server_request(connection, path(row['id']), method='DELETE') raise @@ -113,18 +121,24 @@ async def delete_template(terminal_id: str, user=Depends(get_verified_user)): @router.get('/{terminal_id}/access') async def get_shares(terminal_id: str, user=Depends(get_verified_user)): await template_connection(user, terminal_id, 'write') - return [grant for grant in await AccessGrants.get_grants_by_resource('terminal', terminal_id) - if grant.permission == 'read'] + return [ + grant + for grant in await AccessGrants.get_grants_by_resource('terminal', terminal_id) + if grant.permission == 'read' + ] @router.post('/{terminal_id}/access') async def set_shares(terminal_id: str, body: ShareForm, user=Depends(get_verified_user)): await template_connection(user, terminal_id, 'write') - if any(g.get('principal_type') not in ('user', 'group') or g.get('principal_id') in (None, '', '*') - for g in body.access_grants): + if any( + g.get('principal_type') not in ('user', 'group') or g.get('principal_id') in (None, '', '*') + for g in body.access_grants + ): raise HTTPException(400, 'Public terminal sharing is not allowed') - grants = await validate_access_grants(await Config.get('user.permissions'), user.id, user.role, - body.access_grants, resource_type='terminal') + grants = await validate_access_grants( + await Config.get('user.permissions'), user.id, user.role, body.access_grants, resource_type='terminal' + ) previous = await AccessGrants.get_grants_by_resource('terminal', terminal_id) await AccessGrants.set_access_grants('terminal', terminal_id, grants) await changed(user.id, terminal_id, previous) @@ -132,13 +146,23 @@ async def set_shares(terminal_id: str, body: ShareForm, user=Depends(get_verifie @router.get('/{terminal_id}/instance') -async def current_instance(terminal_id: str, request: Request, chat_id: str | None = None, - model_id: str | None = None, user=Depends(get_verified_user)): - connection = await find_terminal_connection(user, terminal_id, {'chat_id': chat_id, 'model_id': model_id}, request=request) +async def current_instance( + terminal_id: str, + request: Request, + chat_id: str | None = None, + model_id: str | None = None, + user=Depends(get_verified_user), +): + connection = await find_terminal_connection( + user, terminal_id, {'chat_id': chat_id, 'model_id': model_id}, request=request + ) if not connection or not connection.get('template_id'): raise HTTPException(404, 'Template not found') - result = await server_request(connection, path(connection['template_id'], '/instance'), - params={k: v for k, v in connection['terminal_context'].items() if v is not None}) + result = await server_request( + connection, + path(connection['template_id'], '/instance'), + params={k: v for k, v in connection['terminal_context'].items() if v is not None}, + ) return result @@ -170,8 +194,12 @@ async def list_instances(terminal_id: str, user=Depends(get_verified_user)): async def instance_action(terminal_id, action, body, user): connection, template = await template_connection(user, terminal_id, 'write') context = get_terminal_context(template, body.user_id or user.id, body.model_dump(exclude_none=True)) - result = await server_request(connection, path(template['id'], '/instance' if action == 'delete' else '/' + action), - method='DELETE' if action == 'delete' else 'POST', body=context) + result = await server_request( + connection, + path(template['id'], '/instance' if action == 'delete' else '/' + action), + method='DELETE' if action == 'delete' else 'POST', + body=context, + ) await changed(user.id, terminal_id) return result diff --git a/backend/open_webui/routers/terminals.py b/backend/open_webui/routers/terminals.py index 753a1316db..cd1a3f65e9 100644 --- a/backend/open_webui/routers/terminals.py +++ b/backend/open_webui/routers/terminals.py @@ -174,8 +174,12 @@ async def browser_http(request: Request, server_id: str, sid: str, browser_token else: path = f'browser/view/{sid}/{data["capability"]}/{path}' return await _proxy_terminal( - server_id, path, request, user, - context=browser_context(data), browser_auth=data['relay'], + server_id, + path, + request, + user, + context=browser_context(data), + browser_auth=data['relay'], ) @@ -236,7 +240,11 @@ async def browser_ws(ws: WebSocket, server_id: str, sid: str, browser_token: str tasks = [] try: async with get_terminal_client( - base, connection.get('instance_user_id', user.id), cookies=data['relay'].get('cookies', {}), trust_env=True + base, + connection.get('instance_user_id', user.id), + service=connection.get('service', 'open_terminal'), + cookies=data['relay'].get('cookies', {}), + trust_env=True, ) as client: async with client.ws_connect( url, @@ -281,7 +289,8 @@ async def list_terminal_servers(request: Request, user=Depends(get_verified_user 'config': {'chat_uploads': terminal_chat_uploads(connection)}, } for connection in connections - if connection.get('enabled', True) and (connection.get('template_id') or await has_connection_access(user, connection, user_group_ids)) + if connection.get('enabled', True) + and (connection.get('template_id') or await has_connection_access(user, connection, user_group_ids)) ] @@ -298,7 +307,10 @@ async def proxy_terminal( user=Depends(get_verified_user), ): return await _proxy_terminal( - server_id, path, request, user, + server_id, + path, + request, + user, context={ 'chat_id': request.path_params.get('chat_id') or request.headers.get('x-session-id'), 'model_id': request.headers.get('x-terminal-model-id'), @@ -387,8 +399,13 @@ async def _proxy_terminal(server_id, path, request, user, *, context, browser_au if connection.get('template_id') and safe_path == 'files/preview' and request.method == 'POST': browser_token = create_browser_token( - server_id, user.id, session_id or '', {'id': 'files', 'token': ''}, - headers, cookies, resource='files', + server_id, + user.id, + session_id or '', + {'id': 'files', 'token': ''}, + headers, + cookies, + resource='files', ) base = request.url.path.removesuffix('/files/preview') return {'url': f'{base}/browser/view/files/{quote(browser_token, safe="")}/'} @@ -396,6 +413,7 @@ async def _proxy_terminal(server_id, path, request, user, *, context, browser_au session = get_terminal_client( base_url, connection.get('instance_user_id', user.id), + service=connection.get('service', 'open_terminal'), timeout=aiohttp.ClientTimeout(total=300, connect=10), trust_env=True, ) @@ -640,7 +658,9 @@ async def _proxy_terminal_websocket( request = Request({**ws.scope, 'type': 'http', 'method': 'GET'}) opened = False - session = get_terminal_client(base_url, connection.get('instance_user_id', user.id)) + session = get_terminal_client( + base_url, connection.get('instance_user_id', user.id), service=connection.get('service', 'open_terminal') + ) try: async with session.ws_connect( upstream_url, diff --git a/backend/open_webui/routers/tether.py b/backend/open_webui/routers/tether.py index ce278e1e14..91e0cca9ad 100644 --- a/backend/open_webui/routers/tether.py +++ b/backend/open_webui/routers/tether.py @@ -8,15 +8,31 @@ from uuid import UUID, uuid4 from fastapi import APIRouter, WebSocket from open_webui.models.auth_sessions import AuthSessions from open_webui.utils.auth import decode_token, get_verified_user_by_token -from open_webui.utils.tether import CHUNK, WINDOW, Connection, hub, decode, get_max_concurrent_streams, get_services +from open_webui.utils.tether import ( + CHUNK, + WINDOW, + Connection, + hub, + decode, + get_connections, + get_max_concurrent_streams, + get_services, +) router = APIRouter() -@router.websocket('/connect') -async def connect(ws: WebSocket): +async def changed(user_id): + """A device connected, left or changed what it offers: drop cached models and tell open pages.""" + from open_webui.routers.openai import get_tether_models from open_webui.socket.main import emit_to_users + await get_tether_models.cache.clear() + await emit_to_users('events', {'data': {'type': 'terminals:changed'}}, [user_id]) + + +@router.websocket('/connect') +async def connect(ws: WebSocket): await ws.accept() connection = None watcher = None @@ -32,6 +48,7 @@ async def connect(ws: WebSocket): # Version 1 predates service lists and only offered a terminal. services = get_services(hello.get('services', ['open_terminal'] if hello['version'] == 1 else None)) notifications = hello.get('notifications') is True + connections = get_connections(hello.get('connections')) token = hello.get('token', '') user = await get_verified_user_by_token(token, getattr(ws.app.state, 'redis', None)) claims = decode_token(token) @@ -57,6 +74,7 @@ async def connect(ws: WebSocket): window=window, max_concurrent_streams=max_concurrent_streams, services=services, + connections=connections, ) connection = Connection(ws, presence) key = hub.key(user.id, connection_id) @@ -72,7 +90,7 @@ async def connect(ws: WebSocket): presence_lock = asyncio.Lock() if hub.redis: await hub.redis.set(key, record, ex=60) - await emit_to_users('events', {'data': {'type': 'terminals:changed'}}, [user.id]) + await changed(user.id) async def watch(): while True: @@ -112,11 +130,14 @@ async def connect(ws: WebSocket): update = json.loads(message['text']) if update.get('type') == 'services': services = get_services(update.get('services')) + connections = get_connections(update.get('connections')) name = update.get('name', presence['name']) if not isinstance(name, str) or not 1 <= len(name.strip()) <= 100: raise ValueError('A device name of 1–100 characters is required') async with presence_lock: - updated_record = json.dumps({**presence, 'services': services, 'name': name.strip()}) + updated_record = json.dumps( + {**presence, 'services': services, 'connections': connections, 'name': name.strip()} + ) if hub.redis: replaced = await hub.redis.eval( "if redis.call('get', KEYS[1]) == ARGV[1] then redis.call('set', KEYS[1], ARGV[2], 'EX', 60); return 1 else return 0 end", @@ -128,9 +149,10 @@ async def connect(ws: WebSocket): if not replaced: raise ValueError('Tether connection was replaced') presence['services'] = services + presence['connections'] = connections presence['name'] = name.strip() record = updated_record - await emit_to_users('events', {'data': {'type': 'terminals:changed'}}, [user.id]) + await changed(user.id) continue updated = decode_token(update.get('token', '')) current = await get_verified_user_by_token( @@ -164,7 +186,7 @@ async def connect(ws: WebSocket): key, record, ) - await emit_to_users('events', {'data': {'type': 'terminals:changed'}}, [connection.presence['user']]) + await changed(connection.presence['user']) for stream_id, worker in list(connection.routes.items()): stream = hub.streams.get(stream_id) if stream: diff --git a/backend/open_webui/routers/tools.py b/backend/open_webui/routers/tools.py index 0c46cdda18..dfff1cfbf5 100644 --- a/backend/open_webui/routers/tools.py +++ b/backend/open_webui/routers/tools.py @@ -32,6 +32,7 @@ from open_webui.models.tools import ( Tools, ToolUserResponse, ) +from open_webui.utils.tools import get_tether_tool_servers from open_webui.utils.access_control import ( filter_allowed_access_grants, has_connection_access, @@ -207,6 +208,19 @@ async def get_tools( ) ] + # Tool servers the user added in Tether, reached through it. + for server in await get_tether_tool_servers(user): + tools.append( + ToolUserResponse( + id=f'server:tether:{server["id"]}', + user_id=user.id, + name=server['name'], + meta={'description': ''}, + updated_at=int(time.time()), + created_at=int(time.time()), + ) + ) + if query: q = query.casefold() tools = [tool for tool in tools if q in (tool.name or '').casefold()] diff --git a/backend/open_webui/routers/users.py b/backend/open_webui/routers/users.py index 1c55b77f01..664b9c7e62 100644 --- a/backend/open_webui/routers/users.py +++ b/backend/open_webui/routers/users.py @@ -259,7 +259,6 @@ class FeaturesPermissions(BaseModel): channels: bool = True encrypted_channels: bool = False folders: bool = True - direct_tool_servers: bool = False web_search: bool = True image_generation: bool = True @@ -510,18 +509,6 @@ async def update_user_settings_by_session_user( ): ui_settings.pop('system', None) - if ( - user.role != 'admin' - and ui_settings is not None - and 'toolServers' in ui_settings - and not await has_permission( - user.id, - 'features.direct_tool_servers', - await Config.get('user.permissions'), - ) - ): - ui_settings.pop('toolServers', None) - ui_notifications = ui_settings.get('notifications') if isinstance(ui_settings, dict) else None if ( user.role != 'admin' diff --git a/backend/open_webui/socket/main.py b/backend/open_webui/socket/main.py index 0669257e3e..6aed3f1003 100644 --- a/backend/open_webui/socket/main.py +++ b/backend/open_webui/socket/main.py @@ -222,11 +222,6 @@ YDOC_MANAGER = YdocManager( redis_key_prefix=f'{REDIS_KEY_PREFIX}:ydoc:documents', ) -REDIS_EVENT_CHANNEL = f'{REDIS_KEY_PREFIX}:direct_completion' - -EVENT_QUEUES: dict[str, asyncio.Queue] = {} -EVENT_PUBLISH_LOCK = asyncio.Lock() - def get_session_pool_batches(): """All session pool entries, in bounded batches for the Redis backing.""" @@ -1454,65 +1449,6 @@ async def disconnect(sid, reason=None): await remove_document_session(sid) -async def redis_event_listener() -> None: - """Route events received over Redis to their local queues.""" - reconnect_interval = REDIS_PUBSUB_RECONNECT_INTERVAL - - while True: - pubsub = None - try: - # RedisCluster can't route a pubsub subscribe until initialize() fills its slot cache. - await REDIS.initialize() - - pubsub = REDIS.pubsub() - await pubsub.subscribe(REDIS_EVENT_CHANNEL) - reconnect_interval = REDIS_PUBSUB_RECONNECT_INTERVAL - - async for message in pubsub.listen(): - if message['type'] != 'message': - continue - event = JSONCodec.loads(message['data']) - queue = EVENT_QUEUES.get(event['channel']) - if queue is not None: - await queue.put(event['data']) - log.warning('Redis event listener stopped. Retrying.') - except asyncio.CancelledError: - raise - except Exception: - log.exception('Redis event listener failed. Retrying.') - finally: - if pubsub: - with suppress(Exception): - await pubsub.aclose() - - await asyncio.sleep(reconnect_interval) - reconnect_interval = min(reconnect_interval * 2, REDIS_PUBSUB_MAX_RECONNECT_INTERVAL) - - -@sio.on('*') -async def socket_event_handler(event: Any, sid: str, *args: Any) -> None: - """Route user-owned stream events to a local queue or another worker.""" - if not isinstance(event, str) or event.count(':') != 2 or not args: - return - - # The lock keeps arrival order; the sid re-check drops every event after a failed check - session_check = asyncio.create_task(get_socket_session_user(sid)) - async with SOCKET_EVENT_LOCKS.setdefault(('session', sid), asyncio.Lock()): - user = await session_check - if not user or sid not in LOCAL_AUTHENTICATED_SIDS or user.get('id') != event.split(':', 1)[0]: - return - - queue = EVENT_QUEUES.get(event) - if queue is not None: - await queue.put(args[0]) - elif WEBSOCKET_MANAGER == 'redis': - try: - async with EVENT_PUBLISH_LOCK: - await REDIS.publish(REDIS_EVENT_CHANNEL, dumps_bytes({'channel': event, 'data': args[0]})) - except RedisError as e: - log.debug('Failed to relay socket event %s: %s', event, e) - - async def _make_channel_emitter(request_info): """Event emitter that routes pipeline output to a channel message. diff --git a/backend/open_webui/utils/actions.py b/backend/open_webui/utils/actions.py index a39d44bda5..e435dd1eb2 100644 --- a/backend/open_webui/utils/actions.py +++ b/backend/open_webui/utils/actions.py @@ -9,7 +9,7 @@ from open_webui.models.functions import Functions from open_webui.models.users import UserModel from open_webui.socket.main import get_event_call, get_event_emitter from open_webui.utils.middleware import process_tool_result -from open_webui.utils.models import check_model_access, get_all_models +from open_webui.utils.models import check_model_access, get_all_models, add_tether_model from open_webui.utils.plugin import get_function_module_from_cache logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL) @@ -32,12 +32,7 @@ async def chat_action(request: Request, action_id: str, form_data: dict, user: A if not request.app.state.MODELS: await get_all_models(request, user=user) - if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'): - models = { - request.state.model['id']: request.state.model, - } - else: - models = request.app.state.MODELS + models = await add_tether_model(request, user, form_data.get('model')) data = form_data model_id = data['model'] @@ -53,9 +48,8 @@ async def chat_action(request: Request, action_id: str, form_data: dict, user: A if action.type != 'action' or not action.is_active: raise Exception(f'Action not available: {action_id}') - # Direct connections carry a client-supplied model the caller already owns, - # so scope the model-bound checks to server-resolved models. - if not getattr(request.state, 'direct', False) and user.role != 'admin': + # The checks apply to shared models; the caller's own models are theirs. + if model.get('owner_id') != user.id and user.role != 'admin': await check_model_access(user, model) # model['actions'] entries are '' or '.'; # the function id is always the prefix. diff --git a/backend/open_webui/utils/agents/transport.py b/backend/open_webui/utils/agents/transport.py index 3dcfb50a58..b1509cafbc 100644 --- a/backend/open_webui/utils/agents/transport.py +++ b/backend/open_webui/utils/agents/transport.py @@ -16,6 +16,7 @@ from open_webui.utils.tether import get_terminal_client class TerminalTransport: def __init__(self, connection, headers, cookies, user_id): self.url = get_terminal_server_url(connection) + self.service = connection.get('service', 'open_terminal') self.headers, self.cookies, self.user_id = headers, cookies, user_id self.session_id = None self.socket = None @@ -38,7 +39,7 @@ class TerminalTransport: async def request(self, method, path, body=None): async with get_terminal_client( - self.url, self.user_id, timeout=aiohttp.ClientTimeout(total=30), trust_env=True + self.url, self.user_id, service=self.service, timeout=aiohttp.ClientTimeout(total=30), trust_env=True ) as client: async with client.request( method, @@ -77,6 +78,7 @@ class TerminalTransport: async with get_terminal_client( self.url, self.user_id, + service=self.service, timeout=aiohttp.ClientTimeout(total=None, connect=30), trust_env=True, cookies=self.cookies, diff --git a/backend/open_webui/utils/automations.py b/backend/open_webui/utils/automations.py index 942ef6399a..e920b2c0f6 100644 --- a/backend/open_webui/utils/automations.py +++ b/backend/open_webui/utils/automations.py @@ -207,6 +207,7 @@ async def validate_automation_terminal(request, user, data: dict, automation_id: return if terminal['server_id'].startswith('template:'): from open_webui.utils.terminals import template_connection, require_model_access + _, template = await template_connection(user, terminal['server_id']) scope = (template.get('data') or {}).get('scope') if (data.get('target') or {}).get('type') == 'channel' and (is_agent or scope == 'chat'): diff --git a/backend/open_webui/utils/chat.py b/backend/open_webui/utils/chat.py index f34556df6f..fd0a4db51a 100644 --- a/backend/open_webui/utils/chat.py +++ b/backend/open_webui/utils/chat.py @@ -1,10 +1,8 @@ -import asyncio import json import logging import random import sys import time -import uuid from typing import Any, Optional from aiocache import cached @@ -24,7 +22,6 @@ from open_webui.routers.pipelines import ( process_pipeline_outlet_filter, ) from open_webui.socket.main import ( - EVENT_QUEUES, get_event_call, get_event_emitter, ) @@ -34,7 +31,7 @@ from open_webui.utils.filter import ( process_filter_functions, ) from open_webui.utils.json_codec import JSONCodec -from open_webui.utils.models import check_model_access, get_all_models +from open_webui.utils.models import check_model_access, get_all_models, add_tether_model from open_webui.utils.payload import apply_system_prompt_to_body, convert_chat_completions_payload_to_ollama from open_webui.utils.response import ( convert_ollama_response_to_chat_completions, @@ -106,105 +103,6 @@ async def register_temporary_chat_session(redis, chat_id, user_id, session_id, s # When the question has been asked, let silence not be the # answer. But if the answer must wait, let it come honest. -async def generate_direct_chat_completion( - request: Request, - form_data: dict, - user: Any, - models: dict, -): - log.info('generate_direct_chat_completion') - - metadata = form_data.pop('metadata', {}) - - user_id = metadata.get('user_id') - session_id = metadata.get('session_id') - request_id = str(uuid.uuid4()) # Generate a unique request ID - - event_caller = await get_event_call(metadata) - if event_caller is None: - raise Exception( - 'Direct connection requires an active WebSocket session; ' - 'cannot generate completion in this context (e.g. background task).' - ) - - channel = f'{user_id}:{session_id}:{request_id}' - logging.info('WebSocket channel: %s', channel) - - if form_data.get('stream'): - queue = asyncio.Queue() - EVENT_QUEUES[channel] = queue - - # Start processing chat completion in background - try: - res = await event_caller( - { - 'type': 'request:chat:completion', - 'data': { - 'form_data': form_data, - 'model': models[form_data['model']], - 'channel': channel, - 'session_id': session_id, - }, - } - ) - - log.info('res: %s', res) - - status = res.get('status', False) - except BaseException: - EVENT_QUEUES.pop(channel, None) - raise - - if status: - # Define a generator to stream responses - async def event_generator(): - try: - while True: - data = await queue.get() # Wait for new messages - if isinstance(data, dict): - if 'done' in data and data['done']: - break # Stop streaming when 'done' is received - - yield f'data: {JSONCodec.dumps(data)}\n\n' - elif isinstance(data, str): - if 'data:' in data: - yield f'{data}\n\n' - else: - yield f'data: {data}\n\n' - except Exception as e: - log.debug('Error in event generator: %s', e) - pass - finally: - EVENT_QUEUES.pop(channel, None) - - # Define a background task to run the event generator - async def background(): - EVENT_QUEUES.pop(channel, None) - - # Return the streaming response - return StreamingResponse(event_generator(), media_type='text/event-stream', background=background) - else: - EVENT_QUEUES.pop(channel, None) - raise Exception(str(res)) - else: - res = await event_caller( - { - 'type': 'request:chat:completion', - 'data': { - 'form_data': form_data, - 'model': models[form_data['model']], - 'channel': channel, - 'session_id': session_id, - }, - } - ) - - if 'error' in res and res['error']: - raise Exception(res['error']) - - return res - - async def generate_chat_completion( request: Request, form_data: dict, @@ -231,146 +129,130 @@ async def generate_chat_completion( **request.state.metadata, } - if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'): - # Merge the direct connection model into server models so that - # task functions (title, tags, etc.) can resolve a server-side - # task model while still having the direct model available. - # dict(...items()) is one HGETALL on a Redis-backed pool; ``{**pool}`` - # would issue HKEYS plus one HGET per model. - models = { - **dict(request.app.state.MODELS.items()), - request.state.model['id']: request.state.model, - } - log.debug('direct connection to model: %s', request.state.model['id']) - else: - models = request.app.state.MODELS - model_id = form_data['model'] + models = await add_tether_model(request, user, model_id) # Single lookup — membership check plus getitem would be two Redis # round trips on a Redis-backed model pool. model = models.get(model_id) if model is None: raise Exception('Model not found') - if getattr(request.state, 'direct', False) and model_id == getattr(request.state, 'model', {}).get('id'): - return await generate_direct_chat_completion(request, form_data, user=user, models=models) - else: - # Check if user has access to the model - if not bypass_filter and user.role == 'user': - try: - await check_model_access(user, model) - except Exception as e: - raise e + # Check if user has access to the model + if not bypass_filter and user.role == 'user': + try: + await check_model_access(user, model) + except Exception as e: + raise e - # Arena model — sub-model was already resolved by process_chat_payload. - # Inject selected_model_id into the response for the frontend. - metadata = form_data.get('metadata', {}) - selected_model_id = metadata.pop('selected_model_id', None) - # Also clear from request.state.metadata to prevent the merge at - # lines 177-179 from re-adding it on the recursive call. - if hasattr(request.state, 'metadata'): - request.state.metadata.pop('selected_model_id', None) + # Arena model — sub-model was already resolved by process_chat_payload. + # Inject selected_model_id into the response for the frontend. + metadata = form_data.get('metadata', {}) + selected_model_id = metadata.pop('selected_model_id', None) + # Also clear from request.state.metadata to prevent the merge at + # lines 177-179 from re-adding it on the recursive call. + if hasattr(request.state, 'metadata'): + request.state.metadata.pop('selected_model_id', None) - # Fallback: if generate_chat_completion is called with an arena model - # from a path that did NOT go through process_chat_payload (e.g., - # background tasks for title/follow-up/tags generation), resolve now. - if not selected_model_id and model.get('owned_by') == 'arena': - model_ids = model.get('info', {}).get('meta', {}).get('model_ids') - filter_mode = model.get('info', {}).get('meta', {}).get('filter_mode') - if model_ids and filter_mode == 'exclude': - model_ids = [ - available_model['id'] - for available_model in list(request.app.state.MODELS.values()) - if available_model.get('owned_by') != 'arena' and available_model['id'] not in model_ids - ] + # Fallback: if generate_chat_completion is called with an arena model + # from a path that did NOT go through process_chat_payload (e.g., + # background tasks for title/follow-up/tags generation), resolve now. + if not selected_model_id and model.get('owned_by') == 'arena': + model_ids = model.get('info', {}).get('meta', {}).get('model_ids') + filter_mode = model.get('info', {}).get('meta', {}).get('filter_mode') + if model_ids and filter_mode == 'exclude': + model_ids = [ + available_model['id'] + for available_model in list(request.app.state.MODELS.values()) + if available_model.get('owned_by') != 'arena' and available_model['id'] not in model_ids + ] - if isinstance(model_ids, list) and model_ids: - selected_model_id = random.choice(model_ids) - else: - model_ids = [ - available_model['id'] - for available_model in list(request.app.state.MODELS.values()) - if available_model.get('owned_by') != 'arena' - ] - selected_model_id = random.choice(model_ids) - - form_data['model'] = selected_model_id - - # bypass_filter recursion below skips the line-200 check; gate the resolved model here. - if not bypass_filter and user.role == 'user': - selected_model = request.app.state.MODELS.get(selected_model_id) - if selected_model: - await check_model_access(user, selected_model) - - if selected_model_id: - if form_data.get('stream') == True: - - async def stream_wrapper(stream): - yield f'data: {JSONCodec.dumps({"selected_model_id": selected_model_id})}\n\n' - async for chunk in stream: - yield chunk - - response = await generate_chat_completion( - request, - form_data, - user, - bypass_filter=True, - bypass_system_prompt=bypass_system_prompt, - ) - # Upstream errors come back as a response object. - if not isinstance(response, StreamingResponse): - return response - return StreamingResponse( - stream_wrapper(response.body_iterator), - media_type='text/event-stream', - background=response.background, - ) - else: - response = await generate_chat_completion( - request, - form_data, - user, - bypass_filter=True, - bypass_system_prompt=bypass_system_prompt, - ) - if not isinstance(response, dict): - return response - return {**response, 'selected_model_id': selected_model_id} - - if model.get('pipe'): - # Below does not require bypass_filter because this is the only route the uses this function and it is already bypassing the filter - return await generate_function_chat_completion(request, form_data, user=user, models=models) - if model.get('owned_by') == 'ollama': - # Apply before Ollama conversion so tool follow-ups keep the model system prompt - if not bypass_system_prompt: - model_info = await Models.get_model_by_id(form_data['model']) - if model_info: - system = model_info.params.model_dump().get('system') - form_data = await apply_system_prompt_to_body(system, form_data, metadata, user) - request.state.bypass_system_prompt = True - - # Using /ollama/api/chat endpoint - form_data = convert_chat_completions_payload_to_ollama(form_data) - response = await generate_ollama_chat_completion( - request=request, - form_data=form_data, - user=user, - ) - if form_data.get('stream'): - response.headers['content-type'] = 'text/event-stream' - return StreamingResponse( - convert_ollama_stream_to_chat_completions(response), - headers=dict(response.headers), - background=response.background, - ) - else: - return convert_ollama_response_to_chat_completions(response) + if isinstance(model_ids, list) and model_ids: + selected_model_id = random.choice(model_ids) else: - return await generate_openai_chat_completion( - request=request, - form_data=form_data, - user=user, + model_ids = [ + available_model['id'] + for available_model in list(request.app.state.MODELS.values()) + if available_model.get('owned_by') != 'arena' + ] + selected_model_id = random.choice(model_ids) + + form_data['model'] = selected_model_id + + # bypass_filter recursion below skips the line-200 check; gate the resolved model here. + if not bypass_filter and user.role == 'user': + selected_model = request.app.state.MODELS.get(selected_model_id) + if selected_model: + await check_model_access(user, selected_model) + + if selected_model_id: + if form_data.get('stream') == True: + + async def stream_wrapper(stream): + yield f'data: {JSONCodec.dumps({"selected_model_id": selected_model_id})}\n\n' + async for chunk in stream: + yield chunk + + response = await generate_chat_completion( + request, + form_data, + user, + bypass_filter=True, + bypass_system_prompt=bypass_system_prompt, ) + # Upstream errors come back as a response object. + if not isinstance(response, StreamingResponse): + return response + return StreamingResponse( + stream_wrapper(response.body_iterator), + media_type='text/event-stream', + background=response.background, + ) + else: + response = await generate_chat_completion( + request, + form_data, + user, + bypass_filter=True, + bypass_system_prompt=bypass_system_prompt, + ) + if not isinstance(response, dict): + return response + return {**response, 'selected_model_id': selected_model_id} + + if model.get('pipe'): + # Below does not require bypass_filter because this is the only route the uses this function and it is already bypassing the filter + return await generate_function_chat_completion(request, form_data, user=user, models=models) + if model.get('owned_by') == 'ollama': + # Apply before Ollama conversion so tool follow-ups keep the model system prompt + if not bypass_system_prompt: + model_info = await Models.get_model_by_id(form_data['model']) + if model_info: + system = model_info.params.model_dump().get('system') + form_data = await apply_system_prompt_to_body(system, form_data, metadata, user) + request.state.bypass_system_prompt = True + + # Using /ollama/api/chat endpoint + form_data = convert_chat_completions_payload_to_ollama(form_data) + response = await generate_ollama_chat_completion( + request=request, + form_data=form_data, + user=user, + ) + if form_data.get('stream'): + response.headers['content-type'] = 'text/event-stream' + return StreamingResponse( + convert_ollama_stream_to_chat_completions(response), + headers=dict(response.headers), + background=response.background, + ) + else: + return convert_ollama_response_to_chat_completions(response) + else: + return await generate_openai_chat_completion( + request=request, + form_data=form_data, + user=user, + ) chat_completion = generate_chat_completion @@ -380,13 +262,7 @@ async def chat_completed(request: Request, form_data: dict, user: Any): if not request.app.state.MODELS: await get_all_models(request, user=user) - if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'): - models = { - **dict(request.app.state.MODELS.items()), - request.state.model['id']: request.state.model, - } - else: - models = request.app.state.MODELS + models = await add_tether_model(request, user, form_data.get('model')) data = form_data diff --git a/backend/open_webui/utils/context_compaction.py b/backend/open_webui/utils/context_compaction.py index 84267ab08a..55fe4c0471 100644 --- a/backend/open_webui/utils/context_compaction.py +++ b/backend/open_webui/utils/context_compaction.py @@ -426,9 +426,9 @@ async def _generate_summary( bypass_system_prompt: bool = False, ) -> str: from open_webui.utils.chat import generate_chat_completion + from open_webui.utils.models import add_tether_model - if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'): - models = {**dict(models.items()), request.state.model['id']: request.state.model} + models = await add_tether_model(request, user, model_id, models) task_config = await Config.get_many( 'task.model.params', diff --git a/backend/open_webui/utils/embeddings.py b/backend/open_webui/utils/embeddings.py index a2049d4de6..e94a0ee21c 100644 --- a/backend/open_webui/utils/embeddings.py +++ b/backend/open_webui/utils/embeddings.py @@ -13,7 +13,7 @@ from open_webui.routers.ollama import ( embed as ollama_embed, ) from open_webui.routers.openai import embeddings as openai_embeddings -from open_webui.utils.models import check_model_access +from open_webui.utils.models import check_model_access, add_tether_model from open_webui.utils.payload import convert_embed_payload_openai_to_ollama from open_webui.utils.response import convert_embedding_response_ollama_to_openai @@ -52,13 +52,7 @@ async def generate_embeddings( **request.state.metadata, } - # If "direct" flag present, use only that model - if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'): - models = { - request.state.model['id']: request.state.model, - } - else: - models = request.app.state.MODELS + models = await add_tether_model(request, user, form_data.get('model')) model_id = form_data.get('model') if model_id not in models: @@ -66,9 +60,8 @@ async def generate_embeddings( model = models[model_id] # Access filtering - if not getattr(request.state, 'direct', False): - if not bypass_filter and user.role == 'user': - await check_model_access(user, model) + if not bypass_filter and user.role == 'user': + await check_model_access(user, model) # Ollama backend — use /api/embed which supports batch input natively if model.get('owned_by') == 'ollama': diff --git a/backend/open_webui/utils/middleware.py b/backend/open_webui/utils/middleware.py index da566f6403..26293e95a3 100644 --- a/backend/open_webui/utils/middleware.py +++ b/backend/open_webui/utils/middleware.py @@ -727,7 +727,6 @@ async def process_tool_result( tool_function_name, tool_result, tool_type, - direct_tool=False, metadata=None, user=None, ): @@ -780,9 +779,7 @@ async def process_tool_result( else: tool_result = tool_result.body.decode('utf-8', 'replace') - elif (tool_type in EXTERNAL_TOOL_TYPES and isinstance(tool_result, tuple)) or ( - direct_tool and isinstance(tool_result, list) and len(tool_result) == 2 - ): + elif tool_type in EXTERNAL_TOOL_TYPES and isinstance(tool_result, tuple): tool_result, tool_response_headers = tool_result try: @@ -1109,10 +1106,9 @@ async def chat_completion_tools_handler( tool = None tool_type = '' - direct_tool = False try: - tool_function_params, tool_result, tool, tool_type, direct_tool = await execute_tool_call( + tool_function_params, tool_result, tool, tool_type = await execute_tool_call( body, {**metadata, 'tools': tools}, event_caller, @@ -1127,7 +1123,6 @@ async def chat_completion_tools_handler( tool_function_name, tool_result, tool_type, - direct_tool, metadata, user, ) @@ -2242,12 +2237,9 @@ async def process_chat_payload(request, form_data, user, metadata, model): } # Initialize events to store additional event to be sent to the client # Initialize contexts and citation - if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'): - models = { - request.state.model['id']: request.state.model, - } - else: - models = request.app.state.MODELS + from open_webui.utils.models import add_tether_model + + models = await add_tether_model(request, user, form_data.get('model')) task_model_id = get_task_model_id( form_data['model'], @@ -2439,10 +2431,9 @@ async def process_chat_payload(request, form_data, user, metadata, model): tool_ids = form_data.pop('tool_ids', None) terminal_id = form_data.pop('terminal_id', None) if not ENABLE_TOOL_SERVERS: - if terminal_id or metadata.get('tool_servers'): + if terminal_id: log.debug('Excluded external plugins disabled by plugin configuration') terminal_id = None - metadata['tool_servers'] = None files = form_data.pop('files', None) form_data.pop('folder_id', None) metadata['terminal_id'] = terminal_id @@ -2668,13 +2659,8 @@ async def process_chat_payload(request, form_data, user, metadata, model): # skip all server-side tool resolution and pass the caller's tools through # unchanged. Sending `tools: []` explicitly opts out of builtin injection. if payload_tools is None: - # Server side tools tool_ids = metadata.get('tool_ids', None) - # Client side tools - direct_tool_servers = metadata.get('tool_servers', None) - log.debug('tool_ids=%r', tool_ids) - log.debug('direct_tool_servers=%r', direct_tool_servers) tools_dict = {} @@ -2733,7 +2719,6 @@ async def process_chat_payload(request, form_data, user, metadata, model): 'callable': tool_function, 'type': 'mcp', 'client': client, - 'direct': False, } except Exception: log.exception("Failed to connect to MCP server '%s'", server_id) @@ -2798,33 +2783,6 @@ async def process_chat_payload(request, form_data, user, metadata, model): log.exception(e) raise HTTPException(status_code=503, detail=f'Terminal unavailable: {e}') from e - if direct_tool_servers: - for tool_server in direct_tool_servers: - if tool_server.get('is_terminal') is True and not terminal_capability: - continue - # Copy so the pops below keep metadata intact for sub-agents and approval resumes - tool_server = dict(tool_server) - tool_server_system_prompt = tool_server.pop('system_prompt', None) - if tool_server_system_prompt: - form_data['messages'] = add_or_update_system_message( - tool_server_system_prompt, - form_data['messages'], - append=True, - ) - - tool_specs = tool_server.pop('specs', []) - - for tool in tool_specs: - tools_dict[tool['name']] = { - 'spec': ( - get_builtin_tool_spec(display_file) - if tool_server.get('is_terminal') and tool['name'] == 'display_file' - else tool - ), - 'direct': True, - 'server': tool_server, - } - if terminal_id and terminal_capability: from open_webui.utils.terminals import add_terminal_agents_md, get_terminal_agents_md @@ -2878,10 +2836,7 @@ async def process_chat_payload(request, form_data, user, metadata, model): for name, tool_dict in builtin_tools.items(): if name not in tools_dict: tools_dict[name] = tool_dict - elif name == 'display_file' and ( - tools_dict[name].get('type') == 'terminal' - or tools_dict[name].get('server', {}).get('is_terminal') is True - ): + elif name == 'display_file' and tools_dict[name].get('type') == 'terminal': tools_dict[name] = {**tools_dict[name], 'file_tool': tool_dict} await filter_user_terminal_tools(request, user, tools_dict, metadata, extra_params) @@ -3201,7 +3156,7 @@ async def execute_tool_call(form_data, metadata, event_caller, tool_call, histor history.append(tool_call) tool_call['status'] = 'failed' if error else 'in_progress' if error: - return {}, error, None, None, False + return {}, error, None, None params = JSONCodec.loads(tool_call['arguments']) if name == 'display_file' and ( str(params.get('path', '')).startswith('/api/v1/files/') @@ -3209,11 +3164,10 @@ async def execute_tool_call(form_data, metadata, event_caller, tool_call, histor ): if tool.get('file_tool'): tool = tool['file_tool'] - elif tool.get('type') == 'terminal' or tool.get('server', {}).get('is_terminal') is True: + elif tool.get('type') == 'terminal': tool_call['status'] = 'failed' - return params, 'Error: Uploaded file display is not available.', None, None, False + return params, 'Error: Uploaded file display is not available.', None, None tool_type = tool.get('type', '') - direct_tool = tool.get('direct', False) if tool_type != 'mcp': allowed_params = tool.get('spec', {}).get('parameters', {}).get('properties', {}) params = {key: value for key, value in params.items() if key in allowed_params} @@ -3238,43 +3192,26 @@ async def execute_tool_call(form_data, metadata, event_caller, tool_call, histor is not True ): tool_call['status'] = 'failed' - return params, 'Error: tool call was not approved.', tool, tool_type, direct_tool + return params, 'Error: tool call was not approved.', tool, tool_type tool_call['started_at'] = time.time() started = time.perf_counter() try: - if direct_tool: - if not event_caller: - result = 'Error: Browser session is not connected for this direct tool.' - else: - result = await event_caller( - { - 'type': 'execute:tool', - 'data': { - 'id': str(uuid4()), - 'name': name, - 'params': params, - 'server': tool.get('server', {}), - 'session_id': metadata.get('session_id'), - }, - } - ) - else: - function = await get_updated_tool_function( - function=tool['callable'], - extra_params={ - '__messages__': form_data.get('messages', []), - '__files__': metadata.get('files') or [], - }, - ) - result = await function(**params) + function = await get_updated_tool_function( + function=tool['callable'], + extra_params={ + '__messages__': form_data.get('messages', []), + '__files__': metadata.get('files') or [], + }, + ) + result = await function(**params) finally: tool_call['ended_at'] = time.time() tool_call['duration'] = time.perf_counter() - started except Exception as e: result = {'error': str(e)} tool_call['status'] = 'failed' if _is_tool_result_error(result) else 'completed' - return params, result, tool, tool_type, direct_tool + return params, result, tool, tool_type async def resume_tool_calls(request, form_data, user, model, metadata, message) -> bool: @@ -3362,9 +3299,7 @@ async def resume_tool_calls(request, form_data, user, model, metadata, message) try: history = [call for call in output if call.get('type') == 'function_call'] history = history[: next(i for i, call in enumerate(history) if call.get('call_id') == item['call_id'])] - params, result, tool, tool_type, direct_tool = await execute_tool_call( - form_data, metadata, event_caller, item, history - ) + params, result, tool, tool_type = await execute_tool_call(form_data, metadata, event_caller, item, history) files, embeds = [], [] if result is None and tool is None: result = ( @@ -3375,9 +3310,7 @@ async def resume_tool_calls(request, form_data, user, model, metadata, message) terminal_file_result = build_terminal_file_tool_result(name, params, result, tool, metadata) if terminal_file_result: result = terminal_file_result - result, files, embeds = await process_tool_result( - request, name, result, tool_type, direct_tool, metadata, user - ) + result, files, embeds = await process_tool_result(request, name, result, tool_type, metadata, user) await terminal_event_handler(name, params, result, event_emitter) content = await tool_result_with_citations( item.get('name', ''), @@ -3497,7 +3430,6 @@ async def pause_for_tool_approval(chat_id: str, message_id: str, output: list[di 'tool_ids': metadata.get('tool_ids') or [], 'skill_ids': metadata.get('skill_ids') or [], 'terminal_id': metadata.get('terminal_id'), - 'tool_servers': metadata.get('tool_servers'), 'filter_ids': metadata.get('filter_ids') or [], 'features': metadata.get('features') or {}, 'variables': metadata.get('variables') or {}, @@ -4996,7 +4928,7 @@ async def streaming_chat_response_handler(response, ctx): ) if data: - if 'event' in data and not getattr(request.state, 'direct', False): + if 'event' in data: await event_emitter(data.get('event', {})) if 'selected_model_id' in data: @@ -6034,9 +5966,7 @@ async def streaming_chat_response_handler(response, ctx): ) except ToolApprovalRequired: break - tool_function_params, tool_result, tool, tool_type, direct_tool = tool_results[ - tool_call['call_id'] - ] + tool_function_params, tool_result, tool, tool_type = tool_results[tool_call['call_id']] if tool_result is None: results.append( { @@ -6064,7 +5994,6 @@ async def streaming_chat_response_handler(response, ctx): tool_function_name, tool_result, tool_type, - direct_tool, metadata, user, ) diff --git a/backend/open_webui/utils/models.py b/backend/open_webui/utils/models.py index fc2913dac1..3b6e07b1c2 100644 --- a/backend/open_webui/utils/models.py +++ b/backend/open_webui/utils/models.py @@ -524,7 +524,18 @@ async def get_all_models(request, refresh: bool = False, user: UserModel = None) return models +async def add_tether_model(request: Request, user, model_id, models=None): + """`models` (default: the shared models), plus the user's own model `model_id` when it is one.""" + models = request.app.state.MODELS if models is None else models + tether_model = await openai.get_tether_model(request, user, model_id) + # dict(...items()) is one HGETALL on a Redis-backed pool. + return {**dict(models.items()), model_id: tether_model} if tether_model else models + + async def check_model_access(user, model, model_info=None, db=None): + if model.get('owner_id') is not None and model.get('owner_id') == getattr(user, 'id', None): + # The caller's own connection, resolved from their settings. + return if model.get('arena'): meta = model.get('info', {}).get('meta', {}) access_grants = meta.get('access_grants', []) diff --git a/backend/open_webui/utils/subagents.py b/backend/open_webui/utils/subagents.py index e447424f9c..688177d3ac 100644 --- a/backend/open_webui/utils/subagents.py +++ b/backend/open_webui/utils/subagents.py @@ -360,19 +360,15 @@ async def delegate( 'tool_ids': copy.deepcopy(metadata.get('tool_ids') or []), 'skill_ids': copy.deepcopy(metadata.get('skill_ids') or []), 'chat_context': copy.deepcopy(metadata.get('chat_context') or {}), - 'tool_servers': [] if background else copy.deepcopy(metadata.get('tool_servers') or []), 'filter_ids': copy.deepcopy(metadata.get('filter_ids') or []), 'terminal_id': metadata.get('terminal_id'), 'features': features, 'files': copy.deepcopy(metadata.get('files') or []), 'variables': copy.deepcopy(metadata.get('variables') or {}), - 'direct': bool(metadata.get('direct')), 'folder_id': folder_id, } if not run.get('model_id'): return 'Error: model context is required.' - if run.get('direct'): - return 'Error: sub-agents are unavailable for direct connections.' if model_id: available_models = await get_subagent_models(request, UserModel(**user_data), metadata.get('model') or {}) available_ids = [model['id'] for model in available_models] @@ -537,8 +533,6 @@ async def delegate( } if run.get('terminal_id'): form_data['terminal_id'] = run['terminal_id'] - if run.get('tool_servers'): - form_data['tool_servers'] = run['tool_servers'] await request.app.state.CHAT_COMPLETION_HANDLER(child_request, form_data, user=user) message = await Chats.get_message_by_id_and_message_id(chat_id, assistant_message_id) if not message: diff --git a/backend/open_webui/utils/terminals.py b/backend/open_webui/utils/terminals.py index 001b2bee9c..79130da6cd 100644 --- a/backend/open_webui/utils/terminals.py +++ b/backend/open_webui/utils/terminals.py @@ -108,7 +108,12 @@ def split_template_id(terminal_id): raise HTTPException(400, 'Invalid template terminal ID') connection_id, separator, encoded = terminal_id.removeprefix('template:').rpartition(':') template_id = unquote(encoded) - if not separator or not connection_id or not template_id or template_terminal_id(connection_id, template_id) != terminal_id: + if ( + not separator + or not connection_id + or not template_id + or template_terminal_id(connection_id, template_id) != terminal_id + ): raise HTTPException(400, 'Invalid template terminal ID') return connection_id, template_id @@ -143,9 +148,7 @@ async def list_template_connections(user, connections): if not isinstance(user, UserModel): user = UserModel(**user) - group_ids = { - group.id for group in await Groups.get_groups_by_member_id(user.id, include_inherited=True) - } + group_ids = {group.id for group in await Groups.get_groups_by_member_id(user.id, include_inherited=True)} result = [] for connection in connections: if connection.get('server_type') != 'orchestrator' or not connection.get('enabled', True): @@ -159,20 +162,31 @@ async def list_template_connections(user, connections): log.warning('Cannot list templates for connection %s: HTTP %s', connection['id'], exc.status_code) continue selectors = [template_terminal_id(connection['id'], template['id']) for template in templates] - readable = set(selectors) if writable else await AccessGrants.get_accessible_resource_ids( - user_id=user.id, resource_type='terminal', resource_ids=selectors, - permission='read', user_group_ids=group_ids, + readable = ( + set(selectors) + if writable + else await AccessGrants.get_accessible_resource_ids( + user_id=user.id, + resource_type='terminal', + resource_ids=selectors, + permission='read', + user_group_ids=group_ids, + ) ) for template, selector in zip(templates, selectors): if selector not in readable: continue data = template.get('data') or {} - result.append({ - **connection, 'id': selector, - 'name': data.get('name') or template['id'], - 'template_id': template['id'], 'scope': data.get('scope'), - 'auth_type': 'bearer', - }) + result.append( + { + **connection, + 'id': selector, + 'name': data.get('name') or template['id'], + 'template_id': template['id'], + 'scope': data.get('scope'), + 'auth_type': 'bearer', + } + ) return result @@ -212,6 +226,7 @@ async def require_model_access(user, model_id, terminal_id, request=None): return from open_webui.models.models import Models from open_webui.utils.models import check_model_access, get_all_models, get_filtered_models + if request is not None: models = await get_all_models(request, user=user) permitted = await get_filtered_models(models, user) @@ -267,6 +282,7 @@ async def find_terminal_connection(user, terminal_id, metadata=None, request=Non metadata['chat_id'] = chat.meta.get('parent_chat_id') return await find_terminal_connection(user, terminal_id, metadata, request=request) from open_webui.utils.agents.session import get_session, model_id + shared_session = await get_session(chat) if shared_session and shared_session['terminal_id'] != terminal_id: shared_session = None @@ -285,7 +301,11 @@ async def find_terminal_connection(user, terminal_id, metadata=None, request=Non if not terminal_id.startswith('template:'): connections = await get_terminal_connections(instance_user, include_templates=False) connection = next((c for c in connections if c.get('id') == terminal_id), None) - if not connection or not connection.get('enabled', True) or not await has_connection_access(instance_user, connection): + if ( + not connection + or not connection.get('enabled', True) + or not await has_connection_access(instance_user, connection) + ): return None if is_terminal_orchestrator(connection): raise HTTPException(409, 'Select a terminal template') @@ -308,7 +328,11 @@ async def find_terminal_connection(user, terminal_id, metadata=None, request=Non owner = user if chat.user_id == user.id else await Users.get_user_by_id(chat.user_id) if owner is None: raise HTTPException(403, 'Chat owner is unavailable') - if owner.id != instance_user.id and not await has_connection_access(owner, connection) and not await has_connection_write_access(owner, connection): + if ( + owner.id != instance_user.id + and not await has_connection_access(owner, connection) + and not await has_connection_write_access(owner, connection) + ): raise HTTPException(403, 'Terminal connection access denied') principal = owner if not await has_connection_write_access(principal, connection): @@ -319,14 +343,20 @@ async def find_terminal_connection(user, terminal_id, metadata=None, request=Non await require_model_access(instance_user, context['model_id'], terminal_id, request) if metadata.get('automation_id'): from open_webui.models.automations import Automations + automation = await Automations.get_by_id(metadata['automation_id']) if not automation or automation.user_id != user.id: raise HTTPException(403, 'Automation terminal access denied') - return authorized_connection({ - **connection, 'id': terminal_id, - 'template_id': template_id, 'scope': scope, 'auth_type': 'bearer', - 'terminal_context': context, - }) + return authorized_connection( + { + **connection, + 'id': terminal_id, + 'template_id': template_id, + 'scope': scope, + 'auth_type': 'bearer', + 'terminal_context': context, + } + ) async def resolve_terminal_connection(request, user, metadata): @@ -367,7 +397,7 @@ async def get_terminal_json( method: str = 'GET', body: dict | None = None, ): - """Read JSON or upload a file through an admin terminal or a personal terminal's browser.""" + """Read JSON or upload a file through the chat's terminal connection.""" metadata = metadata or {} terminal_id = metadata.get('terminal_id') if not ENABLE_TOOL_SERVERS or not terminal_id: @@ -403,6 +433,7 @@ async def get_terminal_json( async with get_terminal_client( get_terminal_server_url(connection), connection.get('instance_user_id') or (user.id if hasattr(user, 'id') else user['id']), + service=connection.get('service', 'open_terminal'), timeout=timeout, trust_env=True, ) as session: @@ -422,21 +453,6 @@ async def get_terminal_json( f"Terminal '{connection.get('name') or terminal_id}' timed out. " 'It may still be starting. Please try again.' ) from error - - event_caller = (extra_params or {}).get('__event_call__') - if event_caller: - result = await event_caller( - { - 'type': 'request:terminal', - 'data': { - 'terminal_id': terminal_id, - 'path': path, - 'session_id': metadata.get('session_id'), - **({'file': file} if file else {}), - }, - } - ) - return result.get('data') if isinstance(result, dict) else None return None @@ -487,25 +503,16 @@ async def filter_user_terminal_tools(request, user, tools: dict, metadata: dict, shell_tools = { name: tool for name, tool in tools.items() - if name in {'read_user_terminal', 'send_user_terminal_input'} - and (tool.get('type') == 'terminal' or tool.get('server', {}).get('is_terminal') is True) + if name in {'read_user_terminal', 'send_user_terminal_input'} and tool.get('type') == 'terminal' } selected = { name: tool for name, tool in shell_tools.items() - if terminal_id - and ( - tool.get('tool_id') == f'terminal:{terminal_id}' - or (tool.get('direct') and tool.get('server', {}).get('url') == terminal_id) - ) + if terminal_id and tool.get('tool_id') == f'terminal:{terminal_id}' } available = False if selected and not metadata.get('automation_id') and not metadata.get('internal'): - available = any( - tool.get('user_shell_tools') == 'always' - or (tool.get('direct') and (tool.get('server', {}).get('config') or {}).get('user_shell_tools') == 'always') - for tool in selected.values() - ) + available = any(tool.get('user_shell_tools') == 'always' for tool in selected.values()) if not available and metadata.get('chat_id'): try: # This endpoint checks ownership, a live process, and a connected shell. @@ -580,6 +587,7 @@ async def get_terminal_file(request, user, metadata: dict, path: str, *, max_byt async with get_terminal_client( base_url, connection.get('instance_user_id') or (user.id if hasattr(user, 'id') else user['id']), + service=connection.get('service', 'open_terminal'), timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_TERMINAL), trust_env=True, ) as session: diff --git a/backend/open_webui/utils/tether.py b/backend/open_webui/utils/tether.py index eb82ba22c2..3a46c7d720 100644 --- a/backend/open_webui/utils/tether.py +++ b/backend/open_webui/utils/tether.py @@ -44,6 +44,7 @@ class RelayInterrupted(ConnectionError): # Set when no response header arrived; with a safe method the request can be repeated once. self.before_response = False self.connection = None + self.device = None def result(self): return {'error': str(self), 'code': 'tether_interrupted', 'outcome': 'unknown', 'retryable': False} @@ -67,6 +68,36 @@ def get_max_concurrent_streams(hello, window): return min(value, MAX_CONCURRENT_STREAMS, BUFFER_BUDGET // window) +def get_connections(value): + """Connections the user added in Tether. Each is a relay service of its own, like `open_terminal`; + URLs and keys stay on the device.""" + if value is None: + return [] + if not isinstance(value, list) or len(value) > 16: + raise ValueError('Invalid Tether connections') + connections = [] + for item in value: + if ( + not isinstance(item, dict) + or item.get('type') not in ('openai', 'openapi', 'terminal') + or not isinstance(item.get('name'), str) + ): + raise ValueError('Invalid Tether connection') + service = get_services([item.get('service')])[0] + connections.append({'service': service, 'name': item['name'].strip()[:100] or service, 'type': item['type']}) + return connections + + +async def get_tether_connections(user_id, type): + """(presence, connection) pairs of this type across the user's online devices.""" + return [ + (presence, item) + for presence in await hub.presences(user_id) + for item in presence.get('connections', []) + if item['type'] == type and item['service'] in presence.get('services', []) + ] + + def encode(header, data=b''): raw = json.dumps(header, separators=(',', ':')).encode() if len(raw) > 4096 or len(data) > CHUNK: @@ -540,6 +571,23 @@ async def get_terminal_connections(user, include_templates=True): }, } ) + # Terminals the user added in Tether: like the built-in one, but each under its own service. + for presence, item in await get_tether_connections(user_id, 'terminal'): + connections.append( + { + 'id': f'tether:{presence["connection_id"]}:{item["service"]}', + 'name': f'{presence["name"]} · {item["name"]}', + 'url': f'tether://{presence["connection_id"]}', + 'service': item['service'], + 'auth_type': 'none', + 'enabled': True, + 'owner_id': user_id, + 'config': { + 'chat_uploads': 'filesystem', + 'access_grants': [{'principal_type': 'user', 'principal_id': user_id, 'permission': 'read'}], + }, + } + ) if include_templates: from open_webui.utils.terminals import list_template_connections @@ -573,6 +621,7 @@ class RelayResponse: self.content_type = self.headers.get('Content-Type', '').split(';')[0] self.content = self self.cached = None + self.closed = False async def iter_any(self): while True: @@ -587,6 +636,11 @@ class RelayResponse: def iter_chunked(self, size): return self.iter_any() + async def iter_chunks(self): + # aiohttp yields (data, end_of_http_chunk); the relay has no HTTP chunk boundaries. + async for data in self.iter_any(): + yield data, False + async def read(self): if self.cached is None: parts, size = [], 0 @@ -602,10 +656,11 @@ class RelayResponse: async def text(self): return (await self.read()).decode('utf-8', errors='replace') - async def json(self): - return json.loads(await self.read()) + async def json(self, loads=json.loads, **_): + return loads(await self.read()) async def close(self): + self.closed = True self.upload.cancel() await asyncio.gather(self.upload, return_exceptions=True) await self.stream.close() @@ -663,6 +718,8 @@ class RelaySocket: class RelayClient: + """aiohttp-like client for `tether:///` URLs, served by one of the device's services.""" + def __init__(self, user_id, service, timeout=None): if not user_id: raise HTTPException(403, 'A user is required for Tether.') @@ -670,6 +727,7 @@ class RelayClient: self.service = get_services([service])[0] self.operations = [] self.timeout = timeout if timeout is not None else TIMEOUT + self.closed = False async def __aenter__(self): return self @@ -678,6 +736,7 @@ class RelayClient: await self.close() async def close(self): + self.closed = True await asyncio.gather(*(operation.close() for operation in self.operations), return_exceptions=True) def request(self, method, url, **kwargs): @@ -702,8 +761,7 @@ class RelayClient: except RelayInterrupted as error: if not (replayable and error.disconnected and error.before_response and error.connection): raise - device = urlsplit(str(url)).hostname - if not await hub.wait_for_presence(self.user_id, device, self.service, error.connection): + if not await hub.wait_for_presence(self.user_id, error.device, self.service, error.connection): raise return await self._request(method, url, **kwargs) @@ -711,12 +769,15 @@ class RelayClient: parsed = urlsplit(str(url)) if parsed.scheme != 'tether' or not parsed.hostname: raise ValueError('Invalid Tether URL') + device, path = parsed.hostname, parsed.path or '/' headers = dict(kwargs.get('headers') or {}) - headers['X-User-Id'] = self.user_id + if self.service == 'open_terminal': + # Only the built-in terminal reads this; never send it to the user's own servers. + headers['X-User-Id'] = self.user_id query = parsed.query if kwargs.get('params'): query += ('&' if query else '') + urlencode(kwargs['params'], doseq=True) - stream = await hub.open(self.user_id, parsed.hostname, self.service) + stream = await hub.open(self.user_id, device, self.service) body = kwargs.get('data') if kwargs.get('json') is not None: body = json.dumps(kwargs['json']).encode() @@ -735,7 +796,7 @@ class RelayClient: 'http-open' if method else 'ws-open', service=self.service, method=method, - path=parsed.path or '/', + path=path, query=query, headers=headers, ) @@ -788,12 +849,13 @@ class RelayClient: # Everything in this block precedes the response header. interrupted.before_response = True interrupted.connection = stream.presence['connection'] + interrupted.device = device if interrupted is error: raise raise interrupted from error -def get_terminal_client(url, user_id=None, **kwargs): +def get_terminal_client(url, user_id=None, service='open_terminal', **kwargs): if str(url).startswith('tether://'): - return RelayClient(user_id, service='open_terminal', timeout=kwargs.get('timeout')) + return RelayClient(user_id, service=service, timeout=kwargs.get('timeout')) return aiohttp.ClientSession(**kwargs) diff --git a/backend/open_webui/utils/timers.py b/backend/open_webui/utils/timers.py index bab8d17b8a..82e2a8c8b9 100644 --- a/backend/open_webui/utils/timers.py +++ b/backend/open_webui/utils/timers.py @@ -99,8 +99,6 @@ async def create_timer( model_id = metadata.get('model_id') or (metadata.get('model') or {}).get('id') if not model_id: return 'Error: model context is required.' - if metadata.get('direct'): - return 'Error: timers are unavailable for direct connections.' chat_id = str(uuid4()) user_message_id = str(uuid4()) diff --git a/backend/open_webui/utils/tool_approval.py b/backend/open_webui/utils/tool_approval.py index 048a4fe4bf..d74360f341 100644 --- a/backend/open_webui/utils/tool_approval.py +++ b/backend/open_webui/utils/tool_approval.py @@ -269,7 +269,6 @@ async def build_tool_approval_resume_payload(chat_id: str, message_id: str, chat 'tool_ids': message_meta.get('tool_ids') or None, 'skill_ids': message_meta.get('skill_ids') or None, 'terminal_id': message_meta.get('terminal_id') or None, - 'tool_servers': message_meta.get('tool_servers') or None, 'features': message_meta.get('features') or {}, 'variables': message_meta.get('variables') or {}, 'chat_variables': chat.variables if (assistant_message.get('user_id') or chat.user_id) == chat.user_id else {}, diff --git a/backend/open_webui/utils/tools.py b/backend/open_webui/utils/tools.py index 80bdcc5402..728dfc44dc 100644 --- a/backend/open_webui/utils/tools.py +++ b/backend/open_webui/utils/tools.py @@ -128,7 +128,7 @@ from open_webui.utils.plugin import ( load_tool_module_by_id, set_tool_module_in_cache, ) -from open_webui.utils.tether import RelayInterrupted, get_terminal_client +from open_webui.utils.tether import RelayInterrupted, get_tether_connections, get_terminal_client from open_webui.utils.terminals import ( get_terminal_server_url, ) @@ -483,16 +483,23 @@ async def get_tools(request: Request, tool_ids: list[str], user: UserModel, extr if len(splits) == 2: type = 'openapi' server_id = splits[1] - elif len(splits) == 3: + elif len(splits) >= 3: type = splits[1] - server_id = splits[2] + server_id = ':'.join(splits[2:]) server_id_splits = server_id.split('|') if len(server_id_splits) == 2: server_id = server_id_splits[0] function_names = server_id_splits[1].split(',') - if type == 'openapi': + if type == 'tether': + # A tool server the user added in Tether, reached through it. + loaded = await get_tether_tool_server(user, server_id) + if loaded is None: + log.warning(f"Tool server {server_id} is not offered by any of the user's devices") + continue + tool_server_data, tool_server_connection = loaded + elif type == 'openapi': tool_server_data = None for server in await get_tool_servers(request): if server['id'] == server_id: @@ -518,69 +525,69 @@ async def get_tools(request: Request, tool_ids: list[str], user: UserModel, extr log.warning(f'Access denied to tool server {server_id} for user {user.id}') continue - specs = tool_server_data.get('specs', []) - function_name_filter_list = tool_server_connection.get('config', {}).get( - 'function_name_filter_list', '' - ) - - if isinstance(function_name_filter_list, str): - function_name_filter_list = function_name_filter_list.split(',') - - for spec in specs: - function_name = spec['name'] - if function_name_filter_list: - if not is_string_allowed(function_name, function_name_filter_list): - # Skip this function - continue - - metadata = extra_params.get('__metadata__', {}) - - async def make_tool_function(function_name, tool_server_data, connection, server_id, metadata): - async def tool_function(**kwargs): - headers, cookies = await build_tool_server_headers( - connection, request, user, server_id=server_id, metadata=metadata - ) - headers.setdefault('Content-Type', 'application/json') - return await execute_tool_server( - url=tool_server_data['url'], - headers=headers, - cookies=cookies, - name=function_name, - params=kwargs, - server_data=tool_server_data, - ) - - return tool_function - - tool_function = await make_tool_function( - function_name, tool_server_data, tool_server_connection, server_id, metadata - ) - - callable = await get_async_tool_function_and_apply_extra_params( - tool_function, - {}, - ) - - tool_dict = { - 'tool_id': tool_id, - 'callable': callable, - 'spec': clean_openai_tool_schema(spec), - # Misc info - 'type': 'external', - } - - # Handle function name collisions - while function_name in tools_dict: - log.warning(f'Tool {function_name} already exists in another tools!') - # Prepend server ID to function name - function_name = f'{server_id}_{function_name}' - - tool_dict['spec'] = {**tool_dict['spec'], 'name': function_name} - tools_dict[function_name] = tool_dict - else: continue + specs = tool_server_data.get('specs', []) + function_name_filter_list = tool_server_connection.get('config', {}).get( + 'function_name_filter_list', '' + ) + + if isinstance(function_name_filter_list, str): + function_name_filter_list = function_name_filter_list.split(',') + + for spec in specs: + function_name = spec['name'] + if function_name_filter_list: + if not is_string_allowed(function_name, function_name_filter_list): + # Skip this function + continue + + metadata = extra_params.get('__metadata__', {}) + + async def make_tool_function(function_name, tool_server_data, connection, server_id, metadata): + async def tool_function(**kwargs): + headers, cookies = await build_tool_server_headers( + connection, request, user, server_id=server_id, metadata=metadata + ) + headers.setdefault('Content-Type', 'application/json') + return await execute_tool_server( + url=tool_server_data['url'], + headers=headers, + cookies=cookies, + name=function_name, + params=kwargs, + server_data=tool_server_data, + ) + + return tool_function + + tool_function = await make_tool_function( + function_name, tool_server_data, tool_server_connection, server_id, metadata + ) + + callable = await get_async_tool_function_and_apply_extra_params( + tool_function, + {}, + ) + + tool_dict = { + 'tool_id': tool_id, + 'callable': callable, + 'spec': clean_openai_tool_schema(spec), + # Misc info + 'type': 'external', + } + + # Handle function name collisions + while function_name in tools_dict: + log.warning(f'Tool {function_name} already exists in another tools!') + # Prepend server ID to function name + function_name = f'{server_id}_{function_name}' + + tool_dict['spec'] = {**tool_dict['spec'], 'name': function_name} + tools_dict[function_name] = tool_dict + return tools_dict @@ -803,7 +810,6 @@ async def get_builtin_tools( is_builtin_tool_enabled('subagents') and config.get('subagents.enable') and getattr(request.state, 'internal', False) is not True - and getattr(request.state, 'direct', False) is not True and not is_temporary_chat_id(metadata.get('chat_id')) and await has_user_permission('subagents') ): @@ -1381,6 +1387,7 @@ async def get_terminal_cwd( base_url: str, headers: dict, cookies: dict | None = None, + service: str = 'open_terminal', ) -> str | None: """Fetch the current working directory from a terminal server.""" try: @@ -1388,6 +1395,7 @@ async def get_terminal_cwd( async with get_terminal_client( base_url, headers.get('X-User-Id'), + service=service, timeout=aiohttp.ClientTimeout(total=5), trust_env=True, ) as session: @@ -1406,6 +1414,7 @@ async def get_terminal_system_prompt( base_url: str, headers: dict, cookies: dict | None = None, + service: str = 'open_terminal', ) -> str | None: """Fetch the system prompt from a terminal server. @@ -1418,6 +1427,7 @@ async def get_terminal_system_prompt( async with get_terminal_client( base_url, headers.get('X-User-Id'), + service=service, timeout=aiohttp.ClientTimeout(total=3), trust_env=True, ) as session: @@ -1555,7 +1565,10 @@ async def get_terminal_tools( return {} from open_webui.utils.terminals import find_terminal_connection, terminal_headers - connection = await find_terminal_connection(user, terminal_id, extra_params.get('__metadata__', {}), request=request) + + connection = await find_terminal_connection( + user, terminal_id, extra_params.get('__metadata__', {}), request=request + ) if connection is None: raise RuntimeError(f"Terminal server '{terminal_id}' not found") if not connection.get('enabled', True): @@ -1570,16 +1583,23 @@ async def get_terminal_tools( url = get_terminal_server_url(connection) discovery_headers = {**bearer_auth_header(connection['key']), **terminal_headers(connection)} openapi = await get_tool_server_data(url + '/openapi.json', discovery_headers) - server_data = {'id': terminal_id, 'url': url, 'openapi': openapi, 'specs': convert_openapi_to_tool_payload(openapi)} - elif connection.get('owner_id') == user.id: - url = connection['url'] - openapi = await get_tool_server_data(url + '/openapi.json', {'X-User-Id': user.id}) server_data = { 'id': terminal_id, 'url': url, 'openapi': openapi, 'specs': convert_openapi_to_tool_payload(openapi), } + elif connection.get('owner_id') == user.id: + url = connection['url'] + service = connection.get('service', 'open_terminal') + openapi = await get_tool_server_data(url + '/openapi.json', {'X-User-Id': user.id}, service=service) + server_data = { + 'id': terminal_id, + 'url': url, + 'openapi': openapi, + 'specs': convert_openapi_to_tool_payload(openapi), + 'service': service, + } else: terminal_servers = await get_terminal_servers(request) server_data = next((server for server in terminal_servers if server.get('id') == terminal_id), None) @@ -1617,12 +1637,15 @@ async def get_terminal_tools( connection_config = connection.get('config') or {} terminal_cwd = None if connection_config.get('working_directory_context', True): + service = server_data.get('service', 'open_terminal') terminal_cwd, system_prompt = await asyncio.gather( - get_terminal_cwd(server_data['url'], headers, cookies), - get_terminal_system_prompt(server_data['url'], headers, cookies), + get_terminal_cwd(server_data['url'], headers, cookies, service), + get_terminal_system_prompt(server_data['url'], headers, cookies, service), ) else: - system_prompt = await get_terminal_system_prompt(server_data['url'], headers, cookies) + system_prompt = await get_terminal_system_prompt( + server_data['url'], headers, cookies, server_data.get('service', 'open_terminal') + ) if not system_prompt: system_prompt = server_data.get('system_prompt') @@ -1642,8 +1665,9 @@ async def get_terminal_tools( async def tool_function(**kwargs): call_headers = dict(hdrs) if connection.get('template_id'): - current = await find_terminal_connection(user, terminal_id, - {**metadata, 'scope': connection.get('scope')}, request=request) + current = await find_terminal_connection( + user, terminal_id, {**metadata, 'scope': connection.get('scope')}, request=request + ) if current is None: raise HTTPException(403, 'Terminal access revoked') call_headers.update(terminal_headers(current)) @@ -1675,7 +1699,9 @@ async def get_terminal_tools( return tools_dict, system_prompt -async def get_tool_server_data(url: str, headers: dict | None) -> dict[str, Any]: +async def get_tool_server_data( + url: str, headers: dict | None, service: str = 'open_terminal', user_id: str | None = None +) -> dict[str, Any]: if not ENABLE_TOOL_SERVERS: raise RuntimeError('Tool servers are disabled') @@ -1690,7 +1716,9 @@ async def get_tool_server_data(url: str, headers: dict | None) -> dict[str, Any] error = None try: timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA) - async with get_terminal_client(url, _headers.get('X-User-Id'), timeout=timeout, trust_env=True) as session: + async with get_terminal_client( + url, user_id or _headers.get('X-User-Id'), service=service, timeout=timeout, trust_env=True + ) as session: async with session.get(url, headers=_headers, ssl=AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL) as response: if response.status != 200: error_body = await response.json() @@ -1724,6 +1752,40 @@ async def get_tool_server_data(url: str, headers: dict | None) -> dict[str, Any] return res +async def get_tether_tool_servers(user) -> list[dict]: + """OpenAPI tool servers the user added in Tether, by id (`:`).""" + if not ENABLE_TOOL_SERVERS: + return [] + return [ + { + 'id': f'{presence["connection_id"]}:{item["service"]}', + 'name': f'{presence["name"]} · {item["name"]}', + 'url': f'tether://{presence["connection_id"]}', + 'service': item['service'], + } + for presence, item in await get_tether_connections(user.id, 'openapi') + ] + + +async def get_tether_tool_server(user, server_id: str) -> tuple[dict, dict] | None: + """Spec data and connection for a tool server the user added in Tether. Tether adds the key.""" + server = next((s for s in await get_tether_tool_servers(user) if s['id'] == server_id), None) + if server is None: + return None + grant = {'principal_type': 'user', 'principal_id': user.id, 'permission': 'read'} + connection = { + 'url': server['url'], + 'path': 'openapi.json', + 'auth_type': 'none', + 'info': {'id': server_id, 'name': server['name']}, + 'service': server['service'], + 'user_id': user.id, + 'config': {'enable': True, 'access_grants': [grant]}, + } + data = await get_tool_servers_data([connection]) + return (data[0], connection) if data else None + + async def get_tool_servers_data(servers: list[dict[str, Any]]) -> list[dict[str, Any]]: # Prepare list of enabled servers along with their original index @@ -1762,6 +1824,8 @@ async def get_tool_servers_data(servers: list[dict[str, Any]]) -> list[dict[str, task = get_tool_server_data( spec_url, {'Authorization': f'Bearer {token}'} if token else None, + service=server.get('service', 'open_terminal'), + user_id=server.get('user_id'), ) elif spec_type == 'json' and server.get('spec', ''): # Use provided JSON spec @@ -1820,6 +1884,8 @@ async def get_tool_servers_data(servers: list[dict[str, Any]]) -> list[dict[str, 'openapi': openapi_data, 'info': response.get('info'), 'specs': response.get('specs'), + # A tool server the user added in Tether is reached through it. + **({'service': server['service'], 'user_id': server.get('user_id')} if server.get('service') else {}), } ) @@ -1933,7 +1999,8 @@ async def execute_tool_server( async with get_terminal_client( url, - (headers or {}).get('X-User-Id'), + server_data.get('user_id') or (headers or {}).get('X-User-Id'), + service=server_data.get('service', 'open_terminal'), trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER), ) as session: diff --git a/src/lib/apis/configs/index.ts b/src/lib/apis/configs/index.ts index bcc76dbb70..61dcfe6ce1 100644 --- a/src/lib/apis/configs/index.ts +++ b/src/lib/apis/configs/index.ts @@ -246,43 +246,6 @@ export const setTerminalServerConnections = async (token: string, connections: o return res; }; -/** - * Detect whether a terminal server URL points to an Orchestrator or a direct - * Open Terminal server. - * - * - GET {url}/api/v1/terminals/templates → 200 → "orchestrator" - * - GET {url}/api/config → 200 → "terminal" - * - Neither → null - */ -export const detectTerminalServerType = async ( - url: string, - key: string -): Promise<'orchestrator' | 'terminal' | null> => { - const baseUrl = url.replace(/\/$/, ''); - const headers: Record = {}; - if (key) { - headers['Authorization'] = `Bearer ${key}`; - } - - // Orchestrators expose a templates API; plain terminals don't. - try { - const res = await fetch(`${baseUrl}/api/v1/terminals/templates`, { headers }); - if (res.ok) return 'orchestrator'; - } catch { - // ignore - } - - // Fall back to open-terminal config endpoint. - try { - const res = await fetch(`${baseUrl}/api/config`, { headers }); - if (res.ok) return 'terminal'; - } catch { - // ignore - } - - return null; -}; - /** * Verify a terminal server connection via the backend proxy. * Used for system/admin connections to avoid CORS issues and API key exposure. diff --git a/src/lib/apis/index.ts b/src/lib/apis/index.ts index bb3e6c15e6..db0c9f3650 100644 --- a/src/lib/apis/index.ts +++ b/src/lib/apis/index.ts @@ -1,30 +1,11 @@ import { get } from 'svelte/store'; -import { config, selectedTerminalId, selectedFolder, chatId } from '$lib/stores'; +import { selectedTerminalId, selectedFolder, chatId } from '$lib/stores'; import { WEBUI_BASE_URL } from '$lib/constants'; -import { convertOpenApiToToolPayload, resolveSchema } from '$lib/utils'; -import { normalizeTags } from '$lib/utils/tags'; -import { getOpenAIModelsDirect } from './openai'; - -const TOOL_SERVER_FETCH_TIMEOUT = 10000; - -// Valid HTTP methods per OpenAPI 3.x – used to skip extension keys (x-*) -// and non-operation path-item fields (summary, description, servers, parameters). -const OPENAPI_HTTP_METHODS = new Set([ - 'get', - 'put', - 'post', - 'delete', - 'options', - 'head', - 'patch', - 'trace' -]); // Let every request reach its destination, // and let those who wait receive an answer worthy of their patience. export const getModels = async ( token: string = '', - connections: object | null = null, base: boolean = false, refresh: boolean = false, context?: { terminalId: string | null; chatId?: string | null; cwd?: string | null } @@ -78,127 +59,7 @@ export const getModels = async ( throw error; } - let models = res?.data ?? []; - - if (connections && !base) { - let localModels = []; - - if (connections) { - const OPENAI_API_BASE_URLS = connections.OPENAI_API_BASE_URLS; - const OPENAI_API_KEYS = connections.OPENAI_API_KEYS; - const OPENAI_API_CONFIGS = connections.OPENAI_API_CONFIGS; - - const requests = []; - for (const idx in OPENAI_API_BASE_URLS) { - const url = OPENAI_API_BASE_URLS[idx]; - - if (idx.toString() in OPENAI_API_CONFIGS) { - const apiConfig = OPENAI_API_CONFIGS[idx.toString()] ?? {}; - - const enable = apiConfig?.enable ?? true; - const modelIds = apiConfig?.model_ids ?? []; - - if (enable) { - if (modelIds.length > 0) { - const modelList = { - object: 'list', - data: modelIds.map((modelId) => ({ - id: modelId, - name: modelId, - owned_by: 'openai', - openai: { id: modelId }, - urlIdx: idx - })) - }; - - requests.push( - (async () => { - return modelList; - })() - ); - } else { - requests.push( - (async () => { - return await getOpenAIModelsDirect(url, OPENAI_API_KEYS[idx]) - .then((res) => { - return res; - }) - .catch((err) => { - return { - object: 'list', - data: [], - urlIdx: idx - }; - }); - })() - ); - } - } else { - requests.push( - (async () => { - return { - object: 'list', - data: [], - urlIdx: idx - }; - })() - ); - } - } - } - - const responses = await Promise.all(requests); - - for (const idx in responses) { - const response = responses[idx]; - const apiConfig = OPENAI_API_CONFIGS[idx.toString()] ?? {}; - - let models = Array.isArray(response) ? response : (response?.data ?? []); - models = models.map((model) => ({ ...model, openai: { id: model.id }, urlIdx: idx })); - - const prefixId = apiConfig.prefix_id; - if (prefixId) { - for (const model of models) { - model.id = `${prefixId}.${model.id}`; - } - } - - const tags = normalizeTags(apiConfig.tags); - if (tags.length > 0) { - for (const model of models) { - model.tags = tags; - } - } - - localModels = localModels.concat(models); - } - } - - models = models.concat( - localModels.map((model) => ({ - ...model, - name: model?.name ?? model?.id, - direct: true - })) - ); - - // Remove duplicates - const modelsMap = {}; - for (const model of models) { - const existing = modelsMap[model.id]; - modelsMap[model.id] = existing - ? { - ...existing, - ...model, - info: existing.info ?? model.info - } - : model; - } - - models = Object.values(modelsMap); - } - - return models; + return res?.data ?? []; }; export const unloadModel = async (token: string, model: string) => { @@ -241,7 +102,6 @@ type ChatCompletedForm = { session_id: string | undefined; id: string; filter_ids?: string[]; - model_item?: unknown; }; export const chatCompleted = async (token: string, body: ChatCompletedForm) => { @@ -424,333 +284,6 @@ export const resumeTemporaryChat = async (token: string, chatId: string, session return res.json(); }; -export const getToolServerData = async (token: string, url: string) => { - if (!get(config)?.features?.enable_tool_servers) throw new Error('Tool servers are disabled'); - let error = null; - - const res = await fetch(`${url}`, { - signal: AbortSignal.timeout(TOOL_SERVER_FETCH_TIMEOUT), - method: 'GET', - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json', - ...(token && { authorization: `Bearer ${token}` }) - } - }) - .then(async (res) => { - // Check if URL ends with .yaml or .yml to determine format - if (url.toLowerCase().endsWith('.yaml') || url.toLowerCase().endsWith('.yml')) { - if (!res.ok) throw await res.text(); - const [text, { parse }] = await Promise.all([res.text(), import('yaml')]); - return parse(text); - } else { - if (!res.ok) throw await res.json(); - return res.json(); - } - }) - .catch((err) => { - console.error(err); - if (err?.name === 'TimeoutError') { - error = `Connection to ${url} timed out`; - } else if ('detail' in err) { - error = err.detail; - } else { - error = err; - } - return null; - }); - - if (error) { - throw error; - } - - console.log(res); - return res; -}; - -export const getToolServersData = async (servers: object[]) => { - if (!get(config)?.features?.enable_tool_servers) return []; - return ( - await Promise.all( - servers - .filter((server) => server?.config?.enable) - .map(async (server) => { - let error = null; - - let toolServerToken = null; - - const auth_type = server?.auth_type ?? 'bearer'; - if (auth_type === 'bearer') { - toolServerToken = server?.key; - } else if (auth_type === 'none') { - // No authentication - } else if (auth_type === 'session') { - toolServerToken = localStorage.token; - } - - let res = null; - const specType = server?.spec_type ?? 'url'; - - if (specType === 'url') { - res = await getToolServerData( - toolServerToken, - (server?.path ?? '').includes('://') - ? server?.path - : `${server?.url}${(server?.path ?? '').startsWith('/') ? '' : '/'}${server?.path}` - ).catch((err) => { - error = err; - return null; - }); - } else if ((specType === 'json' && server?.spec) ?? null) { - try { - res = JSON.parse(server?.spec); - } catch (e) { - error = 'Failed to parse JSON spec'; - } - } - - if (res) { - if (!res.paths) { - return { - error: 'Invalid OpenAPI spec', - url: server?.url - }; - } - - const { openapi, info, specs } = { - openapi: res, - info: res.info, - specs: convertOpenApiToToolPayload(res) - }; - - const result: Record = { - url: server?.url, - openapi: openapi, - info: info, - specs: specs - }; - - // Fetch system prompt if the server supports it - try { - const baseUrl = (server?.url ?? '').replace(/\/$/, ''); - const configRes = await fetch(`${baseUrl}/api/config`, { - signal: AbortSignal.timeout(TOOL_SERVER_FETCH_TIMEOUT) - }); - if (configRes.ok) { - const config = await configRes.json(); - if (config?.features?.system) { - const headers: Record = {}; - if (toolServerToken) { - headers['Authorization'] = `Bearer ${toolServerToken}`; - } - const systemRes = await fetch(`${baseUrl}/system`, { - signal: AbortSignal.timeout(TOOL_SERVER_FETCH_TIMEOUT), - headers - }); - if (systemRes.ok) { - const systemData = await systemRes.json(); - if (systemData?.prompt) { - result.system_prompt = systemData.prompt; - } - } - } - } - } catch (e) { - // Server doesn't support /system — that's fine - } - - return result; - } else if (error) { - return { - error, - url: server?.url - }; - } else { - return null; - } - }) - ) - ).filter((server) => server); -}; - -export const executeToolServer = async ( - token: string, - url: string, - name: string, - params: Record, - serverData: { openapi: any; info: any; specs: any }, - sessionId?: string -) => { - if (!get(config)?.features?.enable_tool_servers) throw new Error('Tool servers are disabled'); - let error = null; - - try { - // Find the matching operationId in the OpenAPI spec (only valid HTTP methods) - const matchingRoute = Object.entries(serverData.openapi.paths).find(([_, methods]) => - Object.entries(methods as any).some( - ([method, operation]: any) => - OPENAPI_HTTP_METHODS.has(method) && - operation && - typeof operation === 'object' && - operation.operationId === name - ) - ); - - if (!matchingRoute) { - throw new Error(`No matching route found for operationId: ${name}`); - } - - const [routePath, methods] = matchingRoute; - - const methodEntry = Object.entries(methods as any).find( - ([method, operation]: any) => - OPENAPI_HTTP_METHODS.has(method) && - operation && - typeof operation === 'object' && - operation.operationId === name - ); - - if (!methodEntry) { - throw new Error(`No matching method found for operationId: ${name}`); - } - - const [httpMethod, operation]: [string, any] = methodEntry; - - // Merge path-level and operation-level parameters. - // Operation-level params override path-level params with the same (name, in). - const pathLevelParams: any[] = Array.isArray((methods as any).parameters) - ? (methods as any).parameters - : []; - const opParams: any[] = Array.isArray(operation.parameters) ? operation.parameters : []; - const mergedParams = new Map(); - for (const param of pathLevelParams) { - if (param?.name) mergedParams.set(`${param.name}:${param.in ?? ''}`, param); - } - for (const param of opParams) { - if (param?.name) mergedParams.set(`${param.name}:${param.in ?? ''}`, param); - } - - // Split parameters by type - const pathParams: Record = {}; - const queryParams: Record = {}; - let bodyParams: any = {}; - const declaredParamNames = new Set(); - - for (const param of mergedParams.values()) { - const paramName = param?.name; - if (!paramName) continue; - declaredParamNames.add(paramName); - const paramIn = param?.in; - if (params.hasOwnProperty(paramName)) { - if (paramIn === 'path') { - pathParams[paramName] = params[paramName]; - } else if (paramIn === 'query') { - queryParams[paramName] = params[paramName]; - } - } - } - - let finalUrl = `${url}${routePath}`; - - // Replace path parameters (`{param}`) - Object.entries(pathParams).forEach(([key, value]) => { - finalUrl = finalUrl.replace(new RegExp(`{${key}}`, 'g'), encodeURIComponent(value)); - }); - - // Append query parameters to URL if any - if (Object.keys(queryParams).length > 0) { - const queryString = new URLSearchParams( - Object.entries(queryParams).map(([k, v]) => [k, String(v)]) - ).toString(); - finalUrl += `?${queryString}`; - } - - // Handle requestBody composite - if (operation.requestBody && operation.requestBody.content) { - const contentType = Object.keys(operation.requestBody.content)[0]; - if (params !== undefined) { - const jsonSchema = operation.requestBody.content['application/json']?.schema; - const resolvedBodySchema = resolveSchema(jsonSchema, serverData.openapi.components); - const isComposedSchema = ['allOf', 'anyOf', 'oneOf'].some( - (keyword) => keyword in resolvedBodySchema - ); - const bodyProperties = isComposedSchema ? {} : (resolvedBodySchema.properties ?? {}); - // Strict servers reject declared parameters in the body, unless the body schema declares them too. - if (Object.keys(bodyProperties).length > 0) { - bodyParams = Object.fromEntries( - Object.entries(params).filter( - ([key]) => - Object.prototype.hasOwnProperty.call(bodyProperties, key) || - !declaredParamNames.has(key) - ) - ); - } else { - bodyParams = params; - } - } else { - // Optional: Fallback or explicit error if body is expected but not provided - throw new Error(`Request body expected for operation '${name}' but none found.`); - } - } - - // Prepare headers and request options - const headers: Record = { - 'Content-Type': 'application/json', - ...(token && { authorization: `Bearer ${token}` }) - }; - if (sessionId) headers['X-Session-Id'] = sessionId; - - const requestOptions: RequestInit = { - method: httpMethod.toUpperCase(), - headers - }; - - if ( - ['post', 'put', 'patch', 'delete'].includes(httpMethod.toLowerCase()) && - operation.requestBody - ) { - requestOptions.body = JSON.stringify(bodyParams); - } - - const res = await fetch(finalUrl, requestOptions); - if (!res.ok) { - const resText = await res.text(); - throw new Error(`HTTP error! Status: ${res.status}. Message: ${resText}`); - } - - // make a clone of res and extract headers - const responseHeaders = {}; - res.headers.forEach((value, key) => { - responseHeaders[key] = value; - }); - - let responseData; - const contentType = res.headers.get('Content-Type')?.split(';')[0]?.trim() ?? ''; - - try { - responseData = await res.clone().json(); - } catch { - if (contentType.startsWith('text/') || !contentType) { - responseData = await res.text(); - } else { - const buf = await res.arrayBuffer(); - const bytes = new Uint8Array(buf); - let binary = ''; - for (let i = 0; i < bytes.length; i++) { - binary += String.fromCharCode(bytes[i]); - } - const b64 = btoa(binary); - responseData = `data:${contentType};base64,${b64}`; - } - } - return [responseData, responseHeaders]; - } catch (err: any) { - error = err.message; - console.error('API Request Error:', error); - return [{ error }, null]; - } -}; - export const getTaskConfig = async (token: string = '') => { let error = null; diff --git a/src/lib/apis/openai/index.ts b/src/lib/apis/openai/index.ts index b068975832..703de3fe01 100644 --- a/src/lib/apis/openai/index.ts +++ b/src/lib/apis/openai/index.ts @@ -85,33 +85,6 @@ export const updateOpenAIConfig = async (token: string = '', config: OpenAIConfi return res; }; -export const getOpenAIModelsDirect = async (url: string, key: string) => { - let error = null; - - const res = await fetch(`${url}/models`, { - method: 'GET', - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json', - ...(key && { authorization: `Bearer ${key}` }) - } - }) - .then(async (res) => { - if (!res.ok) throw await res.json(); - return res.json(); - }) - .catch((err) => { - error = `OpenAI: ${err?.error?.message ?? 'Network Problem'}`; - return []; - }); - - if (error) { - throw error; - } - - return res; -}; - export const getOpenAIModels = async (token: string, urlIdx?: number) => { let error = null; @@ -332,8 +305,7 @@ export const deleteProviderModel = async (token: string, urlIdx: number, model: export const verifyOpenAIConnection = async ( token: string = '', - connection: Record = {}, - direct: boolean = false + connection: Record = {} ) => { const { url, key, config } = connection; if (!url) { @@ -343,53 +315,30 @@ export const verifyOpenAIConnection = async ( let error = null; let res = null; - if (direct) { - res = await fetch(`${url}/models`, { - method: 'GET', - headers: { - Accept: 'application/json', - Authorization: `Bearer ${key}`, - 'Content-Type': 'application/json' - } + res = await fetch(`${OPENAI_API_BASE_URL}/verify`, { + method: 'POST', + headers: { + Accept: 'application/json', + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + url, + key, + config }) - .then(async (res) => { - if (!res.ok) throw await res.json(); - return res.json(); - }) - .catch((err) => { - error = `OpenAI: ${err?.error?.message ?? 'Network Problem'}`; - return []; - }); - - if (error) { - throw error; - } - } else { - res = await fetch(`${OPENAI_API_BASE_URL}/verify`, { - method: 'POST', - headers: { - Accept: 'application/json', - Authorization: `Bearer ${token}`, - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ - url, - key, - config - }) + }) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); }) - .then(async (res) => { - if (!res.ok) throw await res.json(); - return res.json(); - }) - .catch((err) => { - error = `OpenAI: ${err?.error?.message ?? 'Network Problem'}`; - return []; - }); + .catch((err) => { + error = `OpenAI: ${err?.error?.message ?? 'Network Problem'}`; + return []; + }); - if (error) { - throw error; - } + if (error) { + throw error; } return res; diff --git a/src/lib/apis/terminal/index.ts b/src/lib/apis/terminal/index.ts index fec08aaadd..f5b985b1fc 100644 --- a/src/lib/apis/terminal/index.ts +++ b/src/lib/apis/terminal/index.ts @@ -123,11 +123,9 @@ export async function getTerminalFeatures( signal?: AbortSignal ): Promise { try { - const result = await terminalRequest<{ features?: TerminalFeatures }>( - target, - '/api/config', - { signal } - ); + const result = await terminalRequest<{ features?: TerminalFeatures }>(target, '/api/config', { + signal + }); return result.features ?? {}; } catch { return {}; @@ -180,7 +178,6 @@ export type TerminalProcessOutput = TerminalProcess & { export const resolveTerminalTarget = ( selector: string | null, servers: any[], - directServers: any[], token: string, context: Partial = {} ): TerminalTarget | null => { @@ -202,16 +199,7 @@ export const resolveTerminalTarget = ( system: true }; } - const direct = directServers.find((server) => server.url === selector); - return direct - ? { - selector, - baseUrl: direct.url.replace(/\/$/, ''), - key: direct.key ?? '', - system: false, - context: { chatId: context.chatId ?? null, modelId: null } - } - : null; + return null; }; export class TerminalRequestError extends Error { @@ -447,10 +435,7 @@ export const readComparisonSource = async ( return readSourceResponse(response, signal); }; -export const readFile = async ( - target: TerminalTarget, - path: string -): Promise => { +export const readFile = async (target: TerminalTarget, path: string): Promise => { const url = `${target.baseUrl.replace(/\/$/, '')}/files/read?path=${encodeURIComponent(path)}`; const headers: Record = terminalHeaders(target); @@ -717,9 +702,7 @@ export const moveEntry = async ( return res; }; -export const getListeningPorts = async ( - target: TerminalTarget -): Promise => { +export const getListeningPorts = async (target: TerminalTarget): Promise => { const url = `${target.baseUrl.replace(/\/$/, '')}/ports`; const res = await fetch(url, { headers: { diff --git a/src/lib/components/AddConnectionModal.svelte b/src/lib/components/AddConnectionModal.svelte index 6ce4058589..f3d8da26d4 100644 --- a/src/lib/components/AddConnectionModal.svelte +++ b/src/lib/components/AddConnectionModal.svelte @@ -27,7 +27,6 @@ export let edit = false; export let ollama = false; - export let direct = false; export let connection: any = null; @@ -124,23 +123,19 @@ } } - const res = await verifyOpenAIConnection( - localStorage.token, - { - url, - key, - config: { - auth_type, - ...(!direct && !ollama ? { forward_cookies: forwardCookies } : {}), - ...(provider ? { provider } : {}), - ...(azure ? { azure: true } : {}), - api_version: apiVersion, - passthrough_params: parsePassthroughParams(passthroughParams), - ...(_headers ? { headers: _headers } : {}) - } - }, - direct - ).catch((error) => { + const res = await verifyOpenAIConnection(localStorage.token, { + url, + key, + config: { + auth_type, + ...(!ollama ? { forward_cookies: forwardCookies } : {}), + ...(provider ? { provider } : {}), + ...(azure ? { azure: true } : {}), + api_version: apiVersion, + passthrough_params: parsePassthroughParams(passthroughParams), + ...(_headers ? { headers: _headers } : {}) + } + }).catch((error) => { toast.error(`${error}`); }); @@ -242,7 +237,7 @@ model_ids: modelIds, connection_type: connectionType, auth_type, - ...(!direct && !ollama ? { forward_cookies: forwardCookies } : {}), + ...(!ollama ? { forward_cookies: forwardCookies } : {}), headers: headers ? JSON.parse(headers) : undefined, passthrough_params: parsePassthroughParams(passthroughParams), ...(provider ? { provider } : {}), @@ -312,7 +307,6 @@ $: azure = provider === 'azure' || ((url.includes('azure.') || url.includes('cognitive.microsoft.com')) && - !direct && provider === '' && !/\/openai\/v1(\/|$)/.test(url)); @@ -356,29 +350,27 @@ }} >
- {#if !direct} -
-
-
{$i18n.t('Connection Type')}
+
+
+
{$i18n.t('Connection Type')}
-
- -
+
+
- {/if} +
@@ -467,10 +459,8 @@ {#if !ollama} - {#if !direct} - - - {/if} + + {/if}
@@ -504,7 +494,7 @@
- {#if !ollama && !direct} + {#if !ollama}