From 28812039fc71816249d6231196564f1b894dbfb9 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Mon, 6 Jul 2026 19:12:13 -0500 Subject: [PATCH] refac --- cptr/frontend/src/lib/apis/admin.ts | 1 + .../src/lib/components/Admin/Models.svelte | 186 +++++++++++++++++- cptr/frontend/src/lib/i18n/locales/en.json | 23 +++ cptr/utils/chat_task.py | 49 ++++- cptr/utils/tools.py | 59 +++++- 5 files changed, 300 insertions(+), 18 deletions(-) diff --git a/cptr/frontend/src/lib/apis/admin.ts b/cptr/frontend/src/lib/apis/admin.ts index 7aa2627..e54d32a 100644 --- a/cptr/frontend/src/lib/apis/admin.ts +++ b/cptr/frontend/src/lib/apis/admin.ts @@ -170,6 +170,7 @@ export interface ModelConfigEntry { request_params?: Record; system_prompt?: string; compact_token_threshold?: number; + builtin_tools?: Record | null; }; } diff --git a/cptr/frontend/src/lib/components/Admin/Models.svelte b/cptr/frontend/src/lib/components/Admin/Models.svelte index c052fe9..f5f84ea 100644 --- a/cptr/frontend/src/lib/components/Admin/Models.svelte +++ b/cptr/frontend/src/lib/components/Admin/Models.svelte @@ -15,8 +15,10 @@ import Icon from '../Icon.svelte'; import Spinner from '$lib/components/common/Spinner.svelte'; import ModelSelector from '$lib/components/common/ModelSelector.svelte'; + import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte'; type ParamRow = { key: string; value: string }; + type BuiltinToolsConfig = Record; type ModelEntry = { id: string; name: string; @@ -25,6 +27,7 @@ rows: ParamRow[]; systemPrompt: string; compactTokenThreshold: number | null; + builtinTools: BuiltinToolsConfig; dirty: boolean; }; @@ -37,6 +40,7 @@ let globalRows = $state([]); let globalSystemPrompt = $state(''); let globalCompactTokenThreshold = $state(null); + let globalBuiltinTools = $state({}); let globalDirty = $state(false); let globalExpanded = $state(false); let showVariables = $state(false); @@ -66,6 +70,40 @@ { name: 'MODEL', desc: 'Model ID being used' } ]; + const BUILTIN_TOOL_GROUPS = [ + { id: 'files', label: 'models.builtinTools.files', desc: 'models.builtinTools.filesDesc' }, + { + id: 'terminal', + label: 'models.builtinTools.terminal', + desc: 'models.builtinTools.terminalDesc' + }, + { id: 'web', label: 'models.builtinTools.web', desc: 'models.builtinTools.webDesc' }, + { + id: 'browser', + label: 'models.builtinTools.browser', + desc: 'models.builtinTools.browserDesc' + }, + { id: 'memory', label: 'models.builtinTools.memory', desc: 'models.builtinTools.memoryDesc' }, + { id: 'chats', label: 'models.builtinTools.chats', desc: 'models.builtinTools.chatsDesc' }, + { id: 'skills', label: 'models.builtinTools.skills', desc: 'models.builtinTools.skillsDesc' }, + { + id: 'automations', + label: 'models.builtinTools.automations', + desc: 'models.builtinTools.automationsDesc' + }, + { id: 'images', label: 'models.builtinTools.images', desc: 'models.builtinTools.imagesDesc' }, + { + id: 'subagents', + label: 'models.builtinTools.subagents', + desc: 'models.builtinTools.subagentsDesc' + }, + { + id: 'notifications', + label: 'models.builtinTools.notifications', + desc: 'models.builtinTools.notificationsDesc' + } + ]; + const DEFAULT_PROMPT_PLACEHOLDER = `You are Computer, a helpful assistant running inside the user's computer interface. You have access to tools to read, search, and modify files in the workspace, run commands, and use configured tools. Use them to help the user directly. Approach hard requests with initiative and persistence: make the best possible attempt, adapt as needed, and keep going unless a real constraint prevents progress. {{CPTR_CONTEXT}} @@ -95,6 +133,60 @@ Files: return Number.isFinite(threshold) && threshold > 0 ? Math.floor(threshold) : null; } + function parseBuiltinTools(config: ModelConfigEntry | undefined): BuiltinToolsConfig { + const value = config?.params?.builtin_tools; + if (!value || typeof value !== 'object' || Array.isArray(value)) return {}; + return Object.fromEntries( + Object.entries(value).filter(([, enabled]) => typeof enabled === 'boolean') + ); + } + + function builtinEnabled( + tools: BuiltinToolsConfig, + group: string, + inherited: BuiltinToolsConfig | null = null + ): boolean { + if (tools[group] !== undefined) return tools[group] !== false; + if (inherited?.[group] !== undefined) return inherited[group] !== false; + return true; + } + + function setBuiltinEnabled( + tools: BuiltinToolsConfig, + group: string, + enabled: boolean, + inherited: BuiltinToolsConfig | null = null + ): BuiltinToolsConfig { + const next = { ...tools }; + const inheritedEnabled = inherited?.[group] !== undefined ? inherited[group] !== false : true; + if (enabled === inheritedEnabled) { + delete next[group]; + } else { + next[group] = enabled; + } + return next; + } + + function serializeBuiltinTools( + tools: BuiltinToolsConfig, + inherited: BuiltinToolsConfig | null = null + ): BuiltinToolsConfig | null { + const result: BuiltinToolsConfig = {}; + for (const group of BUILTIN_TOOL_GROUPS) { + if (tools[group.id] === undefined) continue; + const inheritedEnabled = + inherited?.[group.id] !== undefined ? inherited[group.id] !== false : true; + if (tools[group.id] !== inheritedEnabled) { + result[group.id] = tools[group.id]; + } + } + return Object.keys(result).length ? result : null; + } + + function configuredRowCount(rows: ParamRow[]): number { + return rows.filter((row) => row.key.trim()).length; + } + function rowsToRequestParams(rows: ParamRow[]): Record { const result: Record = {}; for (const { key, value } of rows) { @@ -119,8 +211,12 @@ Files: globalRows = parseRows(config['*']); globalSystemPrompt = config['*']?.params?.system_prompt || ''; globalCompactTokenThreshold = parseCompactTokenThreshold(config['*']); + globalBuiltinTools = parseBuiltinTools(config['*']); globalExpanded = - globalRows.length > 0 || !!globalSystemPrompt || globalCompactTokenThreshold !== null; + globalRows.length > 0 || + !!globalSystemPrompt || + globalCompactTokenThreshold !== null || + Object.keys(globalBuiltinTools).length > 0; } models = data.models.map((m) => { @@ -136,6 +232,7 @@ Files: rows: parseRows(mc), systemPrompt: (mc?.params as any)?.system_prompt || '', compactTokenThreshold: parseCompactTokenThreshold(mc), + builtinTools: parseBuiltinTools(mc), dirty: false }; }); @@ -204,13 +301,17 @@ Files: function buildParams( rows: ParamRow[], systemPrompt: string, - compactThreshold: number | null + compactThreshold: number | null, + builtinTools: BuiltinToolsConfig, + inheritedBuiltinTools: BuiltinToolsConfig | null = null ): Record { const params: Record = {}; const rp = rowsToRequestParams(rows); + const bt = serializeBuiltinTools(builtinTools, inheritedBuiltinTools); if (Object.keys(rp).length) params.request_params = rp; if (systemPrompt.trim()) params.system_prompt = systemPrompt.trim(); if (compactThreshold && compactThreshold > 0) params.compact_token_threshold = compactThreshold; + if (bt) params.builtin_tools = bt; return params; } @@ -221,7 +322,12 @@ Files: if (globalDirty) { promises.push( updateModelConfig('*', { - params: buildParams(globalRows, globalSystemPrompt, globalCompactTokenThreshold) + params: buildParams( + globalRows, + globalSystemPrompt, + globalCompactTokenThreshold, + globalBuiltinTools + ) }) ); } @@ -229,7 +335,13 @@ Files: if (model.dirty) { promises.push( updateModelConfig(model.id, { - params: buildParams(model.rows, model.systemPrompt, model.compactTokenThreshold) + params: buildParams( + model.rows, + model.systemPrompt, + model.compactTokenThreshold, + model.builtinTools, + globalBuiltinTools + ) }) ); } @@ -380,6 +492,47 @@ Files: {/snippet} +{#snippet builtinToolsField( + tools: BuiltinToolsConfig, + inherited: BuiltinToolsConfig | null, + onChange: (tools: BuiltinToolsConfig) => void, + resetLabel: string +)} +
+
+ {$t('models.builtinTools')} + {#if Object.keys(tools).length > 0} + + {/if} +
+
+ {#each BUILTIN_TOOL_GROUPS as group} +
+
+
+ {$t(group.label)} +
+
+ {$t(group.desc)} +
+
+ onChange(setBuiltinEnabled(tools, group.id, enabled, inherited))} + /> +
+ {/each} +
+
+{/snippet} +
{#if loading}
@@ -448,11 +601,11 @@ Files: {$t('models.defaults')} - {#if globalRows.filter((r) => r.key.trim()).length > 0 || globalSystemPrompt.trim()} + {#if configuredRowCount(globalRows) > 0 || globalSystemPrompt.trim()} {#if globalSystemPrompt.trim()}prompt{/if} - {#if globalRows.filter((r) => r.key.trim()).length > 0} - {globalRows.filter((r) => r.key.trim()).length} params + {#if configuredRowCount(globalRows) > 0} + {configuredRowCount(globalRows)} params {/if} {/if} @@ -480,6 +633,15 @@ Files: }, DEFAULT_PROMPT_PLACEHOLDER )} + {@render builtinToolsField( + globalBuiltinTools, + null, + (tools) => { + globalBuiltinTools = tools; + globalDirty = true; + }, + $t('models.resetToDefault') + )} {@render paramRows( globalRows, () => (globalDirty = true), @@ -546,6 +708,16 @@ Files: }, $t('models.systemPromptInherited') )} + {@render builtinToolsField( + model.builtinTools, + globalBuiltinTools, + (tools) => { + model.builtinTools = tools; + model.dirty = true; + models = [...models]; + }, + $t('models.resetToDefault') + )} {@render paramRows( model.rows, () => (model.dirty = true), diff --git a/cptr/frontend/src/lib/i18n/locales/en.json b/cptr/frontend/src/lib/i18n/locales/en.json index dbe06c4..f49a258 100644 --- a/cptr/frontend/src/lib/i18n/locales/en.json +++ b/cptr/frontend/src/lib/i18n/locales/en.json @@ -908,6 +908,29 @@ "connections.chatCompletions": "Chat Completions", "connections.responses": "Responses", "admin.agentsNoProfiles": "No agent profiles", + "models.builtinTools": "Builtin Tools", + "models.builtinTools.files": "Files", + "models.builtinTools.filesDesc": "Read, search, create, and edit workspace files", + "models.builtinTools.terminal": "Terminal", + "models.builtinTools.terminalDesc": "Run commands and manage command sessions", + "models.builtinTools.web": "Web", + "models.builtinTools.webDesc": "Search the web and read URLs", + "models.builtinTools.browser": "Browser", + "models.builtinTools.browserDesc": "Navigate, inspect, click, type, screenshot, and evaluate pages", + "models.builtinTools.memory": "Memory", + "models.builtinTools.memoryDesc": "Save durable user and workspace memories", + "models.builtinTools.chats": "Chats", + "models.builtinTools.chatsDesc": "Search previous chats", + "models.builtinTools.skills": "Skills", + "models.builtinTools.skillsDesc": "View and manage Computer skills", + "models.builtinTools.automations": "Automations", + "models.builtinTools.automationsDesc": "List and manage scheduled automations", + "models.builtinTools.images": "Images", + "models.builtinTools.imagesDesc": "Generate or edit images", + "models.builtinTools.subagents": "Subagents", + "models.builtinTools.subagentsDesc": "Delegate work to sub-agents", + "models.builtinTools.notifications": "Notifications", + "models.builtinTools.notificationsDesc": "Send user notifications", "models.requestParams": "Request params", "models.paramKey": "key", "models.paramValue": "value", diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index 5ca4957..e05b4af 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -52,6 +52,27 @@ PLAN_MODE_PROMPT = ( SKILLS_CREATE_RE = re.compile(r"^/skills:create(?:\s+(.*))?$", re.IGNORECASE | re.DOTALL) + +def resolve_builtin_tools_config( + chat_models_config: dict | None, *model_ids: str | None +) -> dict | None: + """Merge global/model builtin tool group config. Missing/null means default.""" + if not isinstance(chat_models_config, dict): + return None + merged: dict = {} + found = False + for model_id in ("*", *[m for m in model_ids if m]): + model_config = chat_models_config.get(model_id) + if not isinstance(model_config, dict): + continue + params = model_config.get("params", {}) + value = params.get("builtin_tools") if isinstance(params, dict) else None + if isinstance(value, dict): + merged.update(value) + found = True + return merged if found else None + + COMPUTER_SKILL_AUTHORING_STANDARDS = """\ Follow the Computer skill-authoring standards: @@ -1631,6 +1652,11 @@ async def run_chat_task( chat_obj = await Chat.get_by_id(chat_id) chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {} configured_model = (msg.model if msg else None) or model + try: + chat_models_config = await Config.get("chat.models") or {} + except Exception: + chat_models_config = {} + builtin_tools = resolve_builtin_tools_config(chat_models_config, model, configured_model) messages, loaded_summary = await _load_message_history(chat_id, message_id) _apply_skills_create_prompt(messages) memory_message, memory_files = _memory_recall_inputs(messages, regeneration_prompt) @@ -1646,7 +1672,7 @@ async def run_chat_task( system += f"\n\n[CONVERSATION SUMMARY]\n{loaded_summary}" if regeneration_prompt: messages.append({"role": "user", "content": regeneration_prompt}) - tools = await get_tool_list() + tools = await get_tool_list(builtin_tools=builtin_tools) # Remove view_skill tool if no skills are available skills = discover_skills(workspace) @@ -1715,15 +1741,17 @@ async def run_chat_task( global_rp = {} model_rp = {} compact_token_threshold = None - try: - chat_models_config = await Config.get("chat.models") or {} - global_rp = chat_models_config.get("*", {}).get("params", {}).get("request_params", {}) - model_rp = chat_models_config.get(model, {}).get("params", {}).get("request_params", {}) - compact_token_threshold = resolve_compact_token_threshold( - configured_model, chat_models_config=chat_models_config - ) - except Exception: - pass + global_params = chat_models_config.get("*", {}).get("params", {}) + if not isinstance(global_params, dict): + global_params = {} + model_params = chat_models_config.get(model, {}).get("params", {}) + if not isinstance(model_params, dict): + model_params = {} + global_rp = global_params.get("request_params") or {} + model_rp = model_params.get("request_params") or {} + compact_token_threshold = resolve_compact_token_threshold( + configured_model, chat_models_config=chat_models_config + ) compact_token_threshold = compact_token_threshold or resolve_compact_token_threshold() request_params = {**global_rp, **model_rp, **chat_request_params} or None @@ -1941,6 +1969,7 @@ async def run_chat_task( "chat_id": chat_id, "message_id": message_id, "connection": connection, + "builtin_tools": builtin_tools, } # Check if any call needs approval diff --git a/cptr/utils/tools.py b/cptr/utils/tools.py index 1abb9a1..4f39c15 100644 --- a/cptr/utils/tools.py +++ b/cptr/utils/tools.py @@ -2330,6 +2330,57 @@ SUBAGENT_TOOLS: dict[str, dict] = { # Combined lookup for execution and approval (always available regardless of config) ALL_TOOLS: dict[str, dict] = {**TOOLS, **BROWSER_TOOLS, **SUBAGENT_TOOLS} +BUILTIN_TOOL_GROUPS: dict[str, tuple[str, ...]] = { + "files": ( + "read_file", + "list_directory", + "search_files", + "create_file", + "display_file", + "edit_file", + "multi_edit_file", + "write_file", + ), + "terminal": ("run_command", "send_input", "check_task", "kill_task"), + "web": ("web_search", "read_url"), + "browser": ( + "browser_navigate", + "browser_snapshot", + "browser_click", + "browser_type", + "browser_screenshot", + "browser_evaluate", + ), + "memory": ("update_memory",), + "chats": ("search_chats",), + "skills": ("view_skill", "manage_skill"), + "automations": ( + "list_automations", + "create_automation", + "update_automation", + "toggle_automation", + "delete_automation", + ), + "images": ("image_generate",), + "subagents": ("delegate_task",), + "notifications": ("notify",), +} + + +def disabled_builtin_tool_names(builtin_tools: dict | None) -> set[str]: + """Return builtin tool names disabled by group config.""" + if not isinstance(builtin_tools, dict): + return set() + disabled: set[str] = set() + for group, enabled in builtin_tools.items(): + if enabled is False: + disabled.update(BUILTIN_TOOL_GROUPS.get(group, ())) + return disabled + + +def is_builtin_tool_enabled(name: str, builtin_tools: dict | None) -> bool: + return name not in disabled_builtin_tool_names(builtin_tools) + # ── External tool servers ─────────────────────────────────── @@ -2633,7 +2684,7 @@ def _without_background_param(schema: dict) -> dict: return schema -async def get_tool_list() -> list[dict]: +async def get_tool_list(builtin_tools: dict | None = None) -> list[dict]: """Return tool schemas for the LLM. Automatically includes browser tools when browser.enabled is true, @@ -2668,6 +2719,10 @@ async def get_tool_list() -> list[dict]: tools.pop("image_generate", None) pass + disabled_tools = disabled_builtin_tool_names(builtin_tools) + if disabled_tools: + tools = {name: tool for name, tool in tools.items() if name not in disabled_tools} + schemas = [_fn_to_schema(name, t["fn"]) for name, t in tools.items()] if not background_subagents_enabled: schemas = [_without_background_param(s) for s in schemas] @@ -2687,6 +2742,8 @@ async def execute_tool(name: str, args: dict, __context__: dict) -> str: """Execute a tool by name, injecting execution context.""" info = ALL_TOOLS.get(name) if info: + if not is_builtin_tool_enabled(name, __context__.get("builtin_tools")): + return f"Error: tool disabled: {name}" fn = info["fn"] try: sig = inspect.signature(fn)