This commit is contained in:
Timothy Jaeryang Baek committed 2026-08-01 01:27:45 -04:00
1 parent fa2b38b2bc
commit 7b95de9b5a
8 files changed
+399 -71

No files matched your search

+21
View File
@@ -211,6 +211,27 @@ export const updateModelConfig = (
method: 'PUT'
});
// ── Tool Approval ───────────────────────────────────────────
export type ToolApprovalPolicy = 'allow' | 'review';
export interface ToolApprovalGroup {
id: string;
tools: {
name: string;
default_approval: ToolApprovalPolicy | null;
}[];
}
export interface ToolApprovalResponse {
default_approval: ToolApprovalPolicy;
overrides: Record<string, ToolApprovalPolicy>;
groups: ToolApprovalGroup[];
}
export const getToolApproval = async (): Promise<ToolApprovalResponse> =>
fetchJSON<ToolApprovalResponse>('/api/admin/tools/approval');
// ── Tool Servers ────────────────────────────────────────────
export interface ToolServer {
@@ -12,7 +12,6 @@
let titleGenerationEnabled = $state(true);
let titleGenerationModel = $state<string | null>(null);
let contextCompactionModel = $state<string | null>(null);
let toolApprovalReviewModel = $state<string | null>(null);
let compactTokenThreshold = $state(80000);
onMount(async () => {
@@ -29,10 +28,6 @@
typeof config['chat.context_compaction.model'] === 'string'
? config['chat.context_compaction.model']
: null;
toolApprovalReviewModel =
typeof config['tool_approval.review.model'] === 'string'
? config['tool_approval.review.model']
: null;
compactTokenThreshold = Number(config['chat.compact_token_threshold']) || 80000;
} catch {
toast.error($t('admin.failedToLoadConfig'));
@@ -48,7 +43,6 @@
'chat.title_generation.enabled': titleGenerationEnabled,
'chat.title_generation.model': titleGenerationModel,
'chat.context_compaction.model': contextCompactionModel,
'tool_approval.review.model': toolApprovalReviewModel,
'chat.compact_token_threshold': Math.max(10000, Number(compactTokenThreshold) || 80000)
});
toast.success($t('settings.saved'));
@@ -153,28 +147,6 @@
</p>
</div>
</div>
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">
{$t('admin.toolApproval')}
</h3>
<div>
<div class="flex items-center justify-between gap-3">
<span class="min-w-0 text-xs text-gray-600 dark:text-gray-400">
{$t('admin.toolApprovalReviewModel')}
</span>
<div class="shrink-0">
<ModelSelector
bind:selectedModel={toolApprovalReviewModel}
nullable
nullLabel={$t('modelSelector.currentModel')}
preferAbove={false}
/>
</div>
</div>
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600 -mt-1">
{$t('admin.toolApprovalReviewModelHint')}
</p>
</div>
</div>
<div class="shrink-0 pt-3 flex justify-end">
@@ -0,0 +1,245 @@
<script lang="ts">
import { onMount } from 'svelte';
import { toast } from 'svelte-sonner';
import {
getAdminConfig,
getToolApproval,
updateConfig,
type ToolApprovalGroup,
type ToolApprovalPolicy
} from '$lib/apis/admin';
import { t } from '$lib/i18n';
import Spinner from '$lib/components/common/Spinner.svelte';
import ModelSelector from '$lib/components/common/ModelSelector.svelte';
let loading = $state(true);
let saving = $state(false);
let reviewModel = $state<string | null>(null);
let defaultApproval = $state<ToolApprovalPolicy>('review');
let overrides = $state<Record<string, ToolApprovalPolicy>>({});
let groups = $state<ToolApprovalGroup[]>([]);
onMount(async () => {
try {
const [config, toolApproval] = await Promise.all([getAdminConfig(), getToolApproval()]);
reviewModel =
typeof config['tool_approval.review.model'] === 'string'
? config['tool_approval.review.model']
: null;
defaultApproval =
parseApproval(config['tool_approval.default_builtin_approval']) ??
toolApproval.default_approval;
overrides = parseOverrides(config['tool_approval.builtin_tools']);
groups = toolApproval.groups;
} catch {
toast.error($t('admin.failedToLoadConfig'));
} finally {
loading = false;
}
});
async function save() {
saving = true;
try {
await updateConfig({
'tool_approval.review.model': reviewModel,
'tool_approval.default_builtin_approval': defaultApproval,
'tool_approval.builtin_tools': overrides
});
toast.success($t('settings.saved'));
} catch {
toast.error($t('admin.failedToSave'));
} finally {
saving = false;
}
}
function parseApproval(value: unknown): ToolApprovalPolicy | null {
return value === 'allow' || value === 'review' ? value : null;
}
function parseOverrides(value: unknown): Record<string, ToolApprovalPolicy> {
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
const entries = Object.entries(value).flatMap(([name, policy]) => {
const parsed = parseApproval(policy);
return parsed ? [[name, parsed] as const] : [];
});
return Object.fromEntries(entries);
}
function setOverride(name: string, policy: ToolApprovalPolicy | null) {
const next = { ...overrides };
if (policy) next[name] = policy;
else delete next[name];
overrides = next;
}
function effective(tool: { name: string; default_approval: ToolApprovalPolicy | null }) {
return overrides[tool.name] ?? tool.default_approval ?? defaultApproval ?? 'review';
}
function approvalLabel(policy: ToolApprovalPolicy) {
return policy === 'allow' ? $t('admin.toolApprovalAllow') : $t('admin.toolApprovalReview');
}
</script>
<div class="flex flex-col h-full">
{#if loading}
<div class="flex justify-center py-8"><Spinner size={16} /></div>
{:else}
<div class="flex-1 min-h-0 overflow-y-auto scrollbar-hover pr-1.5 -mr-1.5">
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4">{$t('admin.tools')}</h2>
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2">
{$t('admin.toolApproval')}
</h3>
<div class="flex flex-col gap-2.5">
<div>
<div class="flex items-center justify-between gap-3">
<span class="min-w-0 text-xs text-gray-600 dark:text-gray-400">
{$t('admin.toolApprovalReviewModel')}
</span>
<div class="shrink-0">
<ModelSelector
bind:selectedModel={reviewModel}
nullable
nullLabel={$t('modelSelector.currentModel')}
preferAbove={false}
/>
</div>
</div>
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600 -mt-1">
{$t('admin.toolApprovalReviewModelHint')}
</p>
</div>
<div>
<div class="flex items-center justify-between gap-3">
<span class="min-w-0 text-xs text-gray-600 dark:text-gray-400">
{$t('admin.toolApprovalDefaultBuiltinApproval')}
</span>
<div class="shrink-0 flex gap-1">
<button
type="button"
class="h-6 rounded-md px-2 text-[0.6875rem] transition-colors {defaultApproval ===
'allow'
? 'bg-gray-200/60 text-gray-900 dark:bg-white/10 dark:text-white'
: 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-300'}"
onclick={() => (defaultApproval = 'allow')}
>
{$t('admin.toolApprovalAllow')}
</button>
<button
type="button"
class="h-6 rounded-md px-2 text-[0.6875rem] transition-colors {defaultApproval ===
'review'
? 'bg-gray-200/60 text-gray-900 dark:bg-white/10 dark:text-white'
: 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-300'}"
onclick={() => (defaultApproval = 'review')}
>
{$t('admin.toolApprovalReview')}
</button>
</div>
</div>
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600 -mt-1">
{$t('admin.toolApprovalDefaultBuiltinApprovalHint')}
</p>
</div>
</div>
<div class="mt-5">
<div class="flex items-center justify-between mb-2">
<h3 class="text-xs text-gray-400 dark:text-gray-600">
{$t('admin.toolApprovalBuiltinTools')}
</h3>
{#if Object.keys(overrides).length > 0}
<button
type="button"
class="text-[0.625rem] text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-400 transition-colors duration-75"
onclick={() => (overrides = {})}
>
{$t('models.resetToDefault')}
</button>
{/if}
</div>
<div class="flex flex-col gap-3">
{#each groups as group}
<div>
<div class="mb-1">
<div class="text-[0.75rem] text-gray-600 dark:text-gray-400">
{$t(`models.builtinTools.${group.id}`)}
</div>
<div class="text-[0.625rem] text-gray-400 dark:text-gray-600">
{$t(`models.builtinTools.${group.id}Desc`)}
</div>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-x-3 gap-y-1.5">
{#each group.tools as tool}
<div class="min-h-8">
<div class="flex items-center justify-between gap-2">
<code
class="min-w-0 truncate text-[0.6875rem] text-gray-600 dark:text-gray-400"
>
{tool.name}
</code>
<div class="shrink-0 flex gap-1">
<button
type="button"
class="h-6 rounded-md px-1.5 text-[0.625rem] transition-colors {overrides[
tool.name
] === undefined
? 'bg-gray-200/60 text-gray-900 dark:bg-white/10 dark:text-white'
: 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-300'}"
onclick={() => setOverride(tool.name, null)}
>
{$t('admin.toolApprovalDefault')}
</button>
<button
type="button"
class="h-6 rounded-md px-1.5 text-[0.625rem] transition-colors {overrides[
tool.name
] === 'allow'
? 'bg-gray-200/60 text-gray-900 dark:bg-white/10 dark:text-white'
: 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-300'}"
onclick={() => setOverride(tool.name, 'allow')}
>
{$t('admin.toolApprovalAllow')}
</button>
<button
type="button"
class="h-6 rounded-md px-1.5 text-[0.625rem] transition-colors {overrides[
tool.name
] === 'review'
? 'bg-gray-200/60 text-gray-900 dark:bg-white/10 dark:text-white'
: 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-300'}"
onclick={() => setOverride(tool.name, 'review')}
>
{$t('admin.toolApprovalReview')}
</button>
</div>
</div>
<p class="text-[0.625rem] text-gray-400 dark:text-gray-600 -mt-0.5">
{$t('admin.toolApprovalEffective', {
value: approvalLabel(effective(tool))
})}
</p>
</div>
{/each}
</div>
</div>
{/each}
</div>
</div>
</div>
<div class="shrink-0 pt-3 flex justify-end">
<button
class="text-[0.8125rem] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100 disabled:opacity-50"
disabled={saving}
onclick={save}
>
{saving ? $t('settings.saving') : $t('settings.save')}
</button>
</div>
{/if}
</div>
@@ -14,6 +14,7 @@
import Agents from './Admin/Agents.svelte';
import Models from './Admin/Models.svelte';
import Chat from './Admin/Chat.svelte';
import Tools from './Admin/Tools.svelte';
import Git from './Admin/Git.svelte';
import Skills from './Admin/Skills.svelte';
import Messaging from './Admin/Messaging.svelte';
@@ -40,6 +41,7 @@
| 'agents'
| 'models'
| 'chat'
| 'tools'
| 'git'
| 'skills'
| 'messaging'
@@ -71,6 +73,7 @@
'agents',
'models',
'chat',
'tools',
'git',
'messaging',
'gateway',
@@ -102,6 +105,7 @@
{ id: 'agents', label: $t('admin.agents'), icon: 'terminal' },
{ id: 'models', label: $t('admin.models'), icon: 'cube' },
{ id: 'chat', label: $t('admin.chat'), icon: 'chat-bubble' },
{ id: 'tools', label: $t('admin.tools'), icon: 'terminal' },
{ id: 'git', label: $t('admin.git'), icon: 'git-branch' },
{ id: 'messaging', label: $t('admin.messaging'), icon: 'chat-bubble' },
{ id: 'gateway', label: $t('admin.gateway.tab'), icon: 'gateway' },
@@ -216,6 +220,8 @@
<Models />
{:else if activeTab === 'chat'}
<Chat />
{:else if activeTab === 'tools'}
<Tools />
{:else if activeTab === 'git'}
<Git />
{:else if activeTab === 'skills'}
@@ -466,6 +466,7 @@
"admin.browserFirecrawlBaseUrlHint": "Change for self-hosted Firecrawl instances",
"admin.models": "Models",
"admin.chat": "Chat",
"admin.tools": "Tools",
"admin.chatTitles": "Titles",
"admin.chatTitleGeneration": "Chat title generation",
"admin.chatTitleGenerationHint": "Name new chats after the first response.",
@@ -476,6 +477,13 @@
"admin.toolApproval": "Tool approval",
"admin.toolApprovalReviewModel": "Review model",
"admin.toolApprovalReviewModelHint": "Reviews pending tool calls in Auto mode.",
"admin.toolApprovalDefaultBuiltinApproval": "Default built-in tool approval",
"admin.toolApprovalDefaultBuiltinApprovalHint": "Used when a built-in tool does not define its own policy.",
"admin.toolApprovalBuiltinTools": "Built-in tool approval",
"admin.toolApprovalDefault": "Default",
"admin.toolApprovalAllow": "Allow",
"admin.toolApprovalReview": "Review",
"admin.toolApprovalEffective": "Effective: {{value}}",
"admin.git": "Git",
"admin.gitCommitMessageModel": "Commit message model",
"admin.gitCommitMessageModelHint": "Drafts messages from staged changes.",
+43 -3
View File
@@ -477,9 +477,7 @@ class UpdateModelConfigRequest(BaseModel):
@router.put("/models/{model_id:path}/config")
async def update_model_config(
model_id: str, body: UpdateModelConfigRequest, request: Request
):
async def update_model_config(model_id: str, body: UpdateModelConfigRequest, request: Request):
"""Update config for a specific model (or '*' for global defaults)."""
require_admin(request)
all_config = await Config.get(CONFIG_KEY_CHAT_MODELS) or {}
@@ -532,6 +530,48 @@ def _mask_tool_server(server: dict) -> dict:
return masked
@router.get("/tools/approval")
async def get_tool_approval(request: Request):
"""Return built-in tool approval defaults for the Chat settings UI."""
require_admin(request)
from cptr.utils.tools import (
ALL_TOOLS,
BUILTIN_TOOL_GROUPS,
normalize_tool_approval,
)
raw_default = await Config.get("tool_approval.default_builtin_approval")
raw_overrides = await Config.get("tool_approval.builtin_tools") or {}
overrides = {}
if isinstance(raw_overrides, dict):
overrides = {
name: policy
for name, value in raw_overrides.items()
if (policy := normalize_tool_approval(value))
}
groups = []
for group_id, names in BUILTIN_TOOL_GROUPS.items():
tools = []
for name in names:
tool = ALL_TOOLS.get(name)
if tool:
tools.append(
{
"name": name,
"default_approval": normalize_tool_approval(tool.get("approval")),
}
)
if tools:
groups.append({"id": group_id, "tools": tools})
return {
"default_approval": normalize_tool_approval(raw_default) or "review",
"overrides": overrides,
"groups": groups,
}
@router.get("/tools/servers")
async def list_tool_servers(request: Request):
"""List all configured tool servers (keys masked)."""
+11 -5
View File
@@ -56,6 +56,7 @@ from cptr.utils.tools import (
disabled_builtin_tool_names,
execute_tool,
get_tool_list,
resolve_builtin_tool_approval,
_fn_to_schema,
)
from cptr.utils.chat_export import export_chat_to_file
@@ -742,6 +743,7 @@ async def review_tool_approval(
model: str,
tool_name: str,
arguments: dict,
approval_policy: str = "review",
) -> bool:
"""Return True when Auto mode can run a pending tool without prompting."""
latest_user = ""
@@ -754,8 +756,9 @@ async def review_tool_approval(
args_text = args_text[:3500] + "\n...(truncated)"
configured_model = await Config.get("tool_approval.review.model")
logger.info(
"[tool-approval] auto review start tool=%s active_model=%s review_model=%s args=%s",
"[tool-approval] auto review start tool=%s policy=%s active_model=%s review_model=%s args=%s",
tool_name,
approval_policy,
model,
configured_model or "<current>",
args_text[:1000],
@@ -1925,7 +1928,7 @@ async def run_chat_task(
# Plan mode: strip write tools, inject prompt as user message (not system, to preserve cache)
plan_mode = chat_params.get("plan_mode", False)
if plan_mode:
tools = [t for t in tools if not ALL_TOOLS.get(t["name"], {}).get("ask", True)]
tools = [t for t in tools if await resolve_builtin_tool_approval(t["name"]) == "allow"]
tools = [t for t in tools if t["name"] not in {"delegate_task", "update_memory"}]
tools.append(_fn_to_schema("create_artifact", create_artifact))
tools.append(ASK_USER_SCHEMA)
@@ -1953,7 +1956,7 @@ async def run_chat_task(
# Tool approval mode: 'ask' | 'auto' | 'full'
# ask = require approval for ALL tools (including reads)
# auto = run ask:false tools; review ask:true tools before prompting
# auto = run allow tools; review review tools before prompting
# full = auto-approve everything
approval_mode = chat_params.get("tool_approval_mode", "auto")
# Legacy compat: old boolean auto_approve_tools
@@ -1984,8 +1987,9 @@ async def run_chat_task(
name = item.get("name", "")
tool = ALL_TOOLS.get(name)
tool_approval = await resolve_builtin_tool_approval(name) if tool else "review"
should_auto = approval_mode == "full" or (
approval_mode == "auto" and tool and not tool.get("ask", True)
approval_mode == "auto" and tool and tool_approval == "allow"
)
if (
not should_auto
@@ -1999,6 +2003,7 @@ async def run_chat_task(
model=model,
tool_name=name,
arguments=item.get("arguments") or {},
approval_policy=tool_approval,
)
):
item["approved"] = True
@@ -2492,8 +2497,9 @@ async def run_chat_task(
if skill_name:
loaded_skill_names.add(skill_name)
tool = ALL_TOOLS.get(name)
tool_approval = await resolve_builtin_tool_approval(name) if tool else "review"
should_auto = approval_mode == "full" or (
approval_mode == "auto" and tool and not tool.get("ask", True)
approval_mode == "auto" and tool and tool_approval == "allow"
)
if not should_auto:
needs_approval = tc
+65 -35
View File
@@ -2277,45 +2277,53 @@ async def notify(message: str, target: str = "", title: str = "", *, __context__
# ── Registry ────────────────────────────────────────────────
ToolApprovalPolicy = Literal["allow", "review"]
TOOL_APPROVAL_POLICIES = {"allow", "review"}
def normalize_tool_approval(value: Any) -> ToolApprovalPolicy | None:
return value if isinstance(value, str) and value in TOOL_APPROVAL_POLICIES else None
TOOLS: dict[str, dict] = {
# Auto mode runs these without asking.
"read_file": {"fn": read_file, "ask": False},
"list_directory": {"fn": list_directory, "ask": False},
"search_files": {"fn": search_files, "ask": False},
"check_task": {"fn": check_task, "ask": False},
"web_search": {"fn": web_search, "ask": False},
"read_url": {"fn": read_url, "ask": False},
"search_chats": {"fn": search_chats, "ask": False},
"list_automations": {"fn": list_automations, "ask": False},
"view_skill": {"fn": view_skill, "ask": False},
"update_tasks": {"fn": update_tasks, "ask": False},
# Auto mode reviews these first, then asks if denied or unclear.
"create_file": {"fn": create_file, "ask": True},
"display_file": {"fn": display_file, "ask": True},
"edit_file": {"fn": edit_file, "ask": True},
"multi_edit_file": {"fn": multi_edit_file, "ask": True},
"write_file": {"fn": write_file, "ask": True},
"run_command": {"fn": run_command, "ask": True},
"send_input": {"fn": send_input, "ask": True},
"kill_task": {"fn": kill_task, "ask": True},
"create_automation": {"fn": create_automation, "ask": True},
"update_automation": {"fn": update_automation, "ask": True},
"toggle_automation": {"fn": toggle_automation, "ask": True},
"delete_automation": {"fn": delete_automation, "ask": True},
"notify": {"fn": notify, "ask": True},
"image_generate": {"fn": image_generate, "ask": True},
"manage_skill": {"fn": manage_skill, "ask": True},
"update_memory": {"fn": update_memory, "ask": False},
"read_file": {"fn": read_file, "approval": "allow"},
"list_directory": {"fn": list_directory, "approval": "allow"},
"search_files": {"fn": search_files, "approval": "allow"},
"check_task": {"fn": check_task, "approval": "allow"},
"web_search": {"fn": web_search, "approval": "allow"},
"read_url": {"fn": read_url, "approval": "allow"},
"search_chats": {"fn": search_chats, "approval": "allow"},
"list_automations": {"fn": list_automations, "approval": "allow"},
"view_skill": {"fn": view_skill, "approval": "allow"},
"update_tasks": {"fn": update_tasks, "approval": "allow"},
# Missing approval inherits tool_approval.default_builtin_approval.
"create_file": {"fn": create_file},
"display_file": {"fn": display_file},
"edit_file": {"fn": edit_file},
"multi_edit_file": {"fn": multi_edit_file},
"write_file": {"fn": write_file},
"run_command": {"fn": run_command},
"send_input": {"fn": send_input},
"kill_task": {"fn": kill_task},
"create_automation": {"fn": create_automation},
"update_automation": {"fn": update_automation},
"toggle_automation": {"fn": toggle_automation},
"delete_automation": {"fn": delete_automation},
"notify": {"fn": notify},
"image_generate": {"fn": image_generate},
"manage_skill": {"fn": manage_skill},
"update_memory": {"fn": update_memory, "approval": "allow"},
}
# Browser tools — conditionally included in schemas based on browser.enabled
BROWSER_TOOLS: dict[str, dict] = {
"browser_navigate": {"fn": browser_navigate, "ask": True},
"browser_snapshot": {"fn": browser_snapshot, "ask": False},
"browser_click": {"fn": browser_click, "ask": True},
"browser_type": {"fn": browser_type, "ask": True},
"browser_screenshot": {"fn": browser_screenshot, "ask": False},
"browser_evaluate": {"fn": browser_evaluate, "ask": True},
"browser_navigate": {"fn": browser_navigate},
"browser_snapshot": {"fn": browser_snapshot, "approval": "allow"},
"browser_click": {"fn": browser_click},
"browser_type": {"fn": browser_type},
"browser_screenshot": {"fn": browser_screenshot, "approval": "allow"},
"browser_evaluate": {"fn": browser_evaluate},
}
@@ -2668,14 +2676,36 @@ async def _run_subagent_chat(
SUBAGENT_TOOLS: dict[str, dict] = {
"delegate_task": {"fn": delegate_task, "ask": False},
"timer": {"fn": timer, "ask": True},
"delegate_task": {"fn": delegate_task, "approval": "allow"},
"timer": {"fn": timer},
}
# Combined lookup for execution and approval (always available regardless of config)
ALL_TOOLS: dict[str, dict] = {**TOOLS, **BROWSER_TOOLS, **SUBAGENT_TOOLS}
async def resolve_builtin_tool_approval(name: str) -> ToolApprovalPolicy:
"""Resolve built-in tool approval. Unknown tools stay conservative."""
tool = ALL_TOOLS.get(name)
if tool is None:
return "review"
from cptr.models import Config
overrides = await Config.get("tool_approval.builtin_tools") or {}
if isinstance(overrides, dict):
override = normalize_tool_approval(overrides.get(name))
if override:
return override
registry = normalize_tool_approval(tool.get("approval"))
if registry:
return registry
default = normalize_tool_approval(await Config.get("tool_approval.default_builtin_approval"))
return default or "review"
BUILTIN_TOOL_GROUPS: dict[str, tuple[str, ...]] = {
"files": (
"read_file",