fix(ai): improve assistant execution and MCP settings
This commit is contained in:
1 parent
1c18a80092
commit
5a666b1f48
20 files changed
+213
-47
No files matched your search
@@ -159,6 +159,10 @@ const MESSAGE_SCROLL_BUTTON_HIDE_THRESHOLD_PX = 48;
|
|||||||
let messageScrollViewport: HTMLElement | null = null;
|
let messageScrollViewport: HTMLElement | null = null;
|
||||||
let messageTouchStartY: number | null = null;
|
let messageTouchStartY: number | null = null;
|
||||||
let lastMessageScrollTop = 0;
|
let lastMessageScrollTop = 0;
|
||||||
|
let assistantDeltaFrame: number | null = null;
|
||||||
|
let pendingAssistantDelta = "";
|
||||||
|
let pendingAssistantReasoning = "";
|
||||||
|
let pendingAssistantIndex = -1;
|
||||||
|
|
||||||
function startEditMessage(visibleIndex: number) {
|
function startEditMessage(visibleIndex: number) {
|
||||||
if (isGenerating.value) return;
|
if (isGenerating.value) return;
|
||||||
@@ -488,6 +492,12 @@ const proposalConfirmMessage = computed<ChatMessage | null>(() => {
|
|||||||
return null;
|
return null;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
let allowWriteSqlForNextRun = false;
|
||||||
|
|
||||||
|
function proposalContainsWriteSql(content: string) {
|
||||||
|
return /\b(insert|update|delete|replace|merge|create|alter|drop|truncate|rename|grant|revoke)\b/i.test(content);
|
||||||
|
}
|
||||||
|
|
||||||
function sendProposalReply(positive: boolean) {
|
function sendProposalReply(positive: boolean) {
|
||||||
// Disable while a stream is in flight or no proposal is currently active.
|
// Disable while a stream is in flight or no proposal is currently active.
|
||||||
if (isGenerating.value) return;
|
if (isGenerating.value) return;
|
||||||
@@ -497,6 +507,7 @@ function sendProposalReply(positive: boolean) {
|
|||||||
const replyZh = positive ? "请执行上面你刚提议的操作,不要再反问确认。" : "不用执行上面提到的操作,继续当前对话。";
|
const replyZh = positive ? "请执行上面你刚提议的操作,不要再反问确认。" : "不用执行上面提到的操作,继续当前对话。";
|
||||||
const replyEn = positive ? "Execute the action you just proposed above; do not ask for confirmation again." : "Do not execute the action mentioned above; continue the current conversation.";
|
const replyEn = positive ? "Execute the action you just proposed above; do not ask for confirmation again." : "Do not execute the action mentioned above; continue the current conversation.";
|
||||||
prompt.value = isZh ? replyZh : replyEn;
|
prompt.value = isZh ? replyZh : replyEn;
|
||||||
|
allowWriteSqlForNextRun = positive && assistantMode.value === "agent" && proposalContainsWriteSql(target.content);
|
||||||
// Use the existing send pipeline so the message is added to history, persisted, etc.
|
// Use the existing send pipeline so the message is added to history, persisted, etc.
|
||||||
send();
|
send();
|
||||||
}
|
}
|
||||||
@@ -596,19 +607,41 @@ function changeDatabase(value: string) {
|
|||||||
queryStore.updateDatabase(tab.id, decodeSelectableDatabaseValue(connection.db_type, value));
|
queryStore.updateDatabase(tab.id, decodeSelectableDatabaseValue(connection.db_type, value));
|
||||||
}
|
}
|
||||||
|
|
||||||
function appendAssistantDelta(assistantIdx: number, delta: string) {
|
function flushAssistantDeltas() {
|
||||||
const msg = messages.value[assistantIdx];
|
assistantDeltaFrame = null;
|
||||||
if (msg.isThinking) msg.isThinking = false;
|
const msg = messages.value[pendingAssistantIndex];
|
||||||
msg.content += delta;
|
if (!msg) return;
|
||||||
|
if (pendingAssistantReasoning) {
|
||||||
|
msg.reasoning = (msg.reasoning || "") + pendingAssistantReasoning;
|
||||||
|
msg.isThinking = true;
|
||||||
|
}
|
||||||
|
if (pendingAssistantDelta) {
|
||||||
|
msg.isThinking = false;
|
||||||
|
msg.content += pendingAssistantDelta;
|
||||||
|
}
|
||||||
|
pendingAssistantDelta = "";
|
||||||
|
pendingAssistantReasoning = "";
|
||||||
scrollToBottom();
|
scrollToBottom();
|
||||||
}
|
}
|
||||||
|
|
||||||
function appendAssistantReasoning(assistantIdx: number, delta: string) {
|
function scheduleAssistantDeltaFlush(assistantIdx: number) {
|
||||||
|
pendingAssistantIndex = assistantIdx;
|
||||||
|
if (assistantDeltaFrame !== null) return;
|
||||||
|
// Providers can emit many tiny chunks. Render once per animation frame so
|
||||||
|
// Markdown parsing, highlighting, and layout do not run for every token.
|
||||||
|
assistantDeltaFrame = requestAnimationFrame(flushAssistantDeltas);
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendAssistantDelta(assistantIdx: number, delta: string) {
|
||||||
const msg = messages.value[assistantIdx];
|
const msg = messages.value[assistantIdx];
|
||||||
if (!msg.reasoning) msg.reasoning = "";
|
if (msg.isThinking) msg.isThinking = false;
|
||||||
msg.reasoning += delta;
|
pendingAssistantDelta += delta;
|
||||||
msg.isThinking = true;
|
scheduleAssistantDeltaFlush(assistantIdx);
|
||||||
scrollToBottom();
|
}
|
||||||
|
|
||||||
|
function appendAssistantReasoning(assistantIdx: number, delta: string) {
|
||||||
|
pendingAssistantReasoning += delta;
|
||||||
|
scheduleAssistantDeltaFlush(assistantIdx);
|
||||||
}
|
}
|
||||||
|
|
||||||
const reasoningExpanded = ref(false);
|
const reasoningExpanded = ref(false);
|
||||||
@@ -1358,6 +1391,8 @@ async function send() {
|
|||||||
|
|
||||||
const requestedAction = activeAction.value;
|
const requestedAction = activeAction.value;
|
||||||
const requestedMode = assistantMode.value;
|
const requestedMode = assistantMode.value;
|
||||||
|
const allowWriteSql = requestedMode === "agent" && allowWriteSqlForNextRun;
|
||||||
|
allowWriteSqlForNextRun = false;
|
||||||
isGenerating.value = true;
|
isGenerating.value = true;
|
||||||
messages.value.push({ role: "assistant", content: "" });
|
messages.value.push({ role: "assistant", content: "" });
|
||||||
const assistantIdx = messages.value.length - 1;
|
const assistantIdx = messages.value.length - 1;
|
||||||
@@ -1379,6 +1414,7 @@ async function send() {
|
|||||||
mode: requestedMode,
|
mode: requestedMode,
|
||||||
instruction: modelInstruction,
|
instruction: modelInstruction,
|
||||||
context,
|
context,
|
||||||
|
allowWriteSql,
|
||||||
},
|
},
|
||||||
history,
|
history,
|
||||||
(event: AgentEvent) => {
|
(event: AgentEvent) => {
|
||||||
@@ -1420,6 +1456,8 @@ async function send() {
|
|||||||
const message = e instanceof Error ? e.message : String(e);
|
const message = e instanceof Error ? e.message : String(e);
|
||||||
messages.value[assistantIdx].content = `Error: ${message}`;
|
messages.value[assistantIdx].content = `Error: ${message}`;
|
||||||
} finally {
|
} finally {
|
||||||
|
if (assistantDeltaFrame !== null) cancelAnimationFrame(assistantDeltaFrame);
|
||||||
|
flushAssistantDeltas();
|
||||||
const msg = messages.value[assistantIdx];
|
const msg = messages.value[assistantIdx];
|
||||||
if (msg) msg.isThinking = false;
|
if (msg) msg.isThinking = false;
|
||||||
isGenerating.value = false;
|
isGenerating.value = false;
|
||||||
@@ -1628,6 +1666,7 @@ function stopResize() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
|
if (assistantDeltaFrame !== null) cancelAnimationFrame(assistantDeltaFrame);
|
||||||
clearTimeout(mentionTimer);
|
clearTimeout(mentionTimer);
|
||||||
cancelStream();
|
cancelStream();
|
||||||
detachMessageScrollListener();
|
detachMessageScrollListener();
|
||||||
@@ -1838,7 +1877,8 @@ async function openExternalUrl(url: string) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<template v-for="(seg, j) in messageRenderer.render(msg.content)" :key="j">
|
<div v-if="isGenerating && msg === messages[messages.length - 1]" class="whitespace-pre-wrap break-words text-sm leading-relaxed">{{ msg.content }}</div>
|
||||||
|
<template v-else v-for="(seg, j) in messageRenderer.render(msg.content)" :key="j">
|
||||||
<div v-if="seg.type === 'text'" class="ai-markdown whitespace-normal" @click.capture="onMarkdownClick">
|
<div v-if="seg.type === 'text'" class="ai-markdown whitespace-normal" @click.capture="onMarkdownClick">
|
||||||
<div v-html="seg.html" />
|
<div v-html="seg.html" />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1301,8 +1301,10 @@ const mcpStatusLoading = ref(false);
|
|||||||
const mcpStatusError = ref("");
|
const mcpStatusError = ref("");
|
||||||
const mcpCopied = ref<"" | McpCopyKind>("");
|
const mcpCopied = ref<"" | McpCopyKind>("");
|
||||||
const mcpConfigTab = ref<McpConfigTab>("claude");
|
const mcpConfigTab = ref<McpConfigTab>("claude");
|
||||||
const mcpReadonlyMode = ref(false);
|
const MCP_READONLY_STORAGE_KEY = "dbx-mcp-config-readonly";
|
||||||
const mcpAllowDangerous = ref(false);
|
const MCP_ALLOW_DANGEROUS_STORAGE_KEY = "dbx-mcp-config-allow-dangerous";
|
||||||
|
const mcpReadonlyMode = ref(localStorage.getItem(MCP_READONLY_STORAGE_KEY) === "true");
|
||||||
|
const mcpAllowDangerous = ref(localStorage.getItem(MCP_ALLOW_DANGEROUS_STORAGE_KEY) === "true");
|
||||||
const mcpInstalling = ref(false);
|
const mcpInstalling = ref(false);
|
||||||
const mcpInstallMessage = ref("");
|
const mcpInstallMessage = ref("");
|
||||||
const mcpInstallError = ref(false);
|
const mcpInstallError = ref(false);
|
||||||
@@ -1355,9 +1357,14 @@ const mcpCommand = computed(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
watch(mcpReadonlyMode, (value) => {
|
watch(mcpReadonlyMode, (value) => {
|
||||||
|
localStorage.setItem(MCP_READONLY_STORAGE_KEY, String(value));
|
||||||
if (value) mcpAllowDangerous.value = false;
|
if (value) mcpAllowDangerous.value = false;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
watch(mcpAllowDangerous, (value) => {
|
||||||
|
localStorage.setItem(MCP_ALLOW_DANGEROUS_STORAGE_KEY, String(value));
|
||||||
|
});
|
||||||
|
|
||||||
async function refreshMcpStatus() {
|
async function refreshMcpStatus() {
|
||||||
if (mcpStatusLoading.value) return;
|
if (mcpStatusLoading.value) return;
|
||||||
mcpStatusLoading.value = true;
|
mcpStatusLoading.value = true;
|
||||||
@@ -4025,6 +4032,7 @@ onUnmounted(cleanupPreviewEditor);
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="space-y-2">
|
<div class="space-y-2">
|
||||||
|
<p class="text-xs text-muted-foreground">{{ t("settings.mcpConfigOptionsHint") }}</p>
|
||||||
<div class="flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
|
<div class="flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
|
||||||
<div class="space-y-1">
|
<div class="space-y-1">
|
||||||
<Label for="mcp-readonly-mode">{{ t("settings.mcpReadonlyMode") }}</Label>
|
<Label for="mcp-readonly-mode">{{ t("settings.mcpReadonlyMode") }}</Label>
|
||||||
|
|||||||
@@ -3272,6 +3272,7 @@ export default {
|
|||||||
mcpInstallSuccess: "Installation successful",
|
mcpInstallSuccess: "Installation successful",
|
||||||
mcpInstallFailed: "Installation failed",
|
mcpInstallFailed: "Installation failed",
|
||||||
mcpConfig: "MCP config",
|
mcpConfig: "MCP config",
|
||||||
|
mcpConfigOptionsHint: "These options only update the generated config below. Copy it into your AI client and restart the MCP session to apply it.",
|
||||||
mcpCodexConfig: "Codex config",
|
mcpCodexConfig: "Codex config",
|
||||||
mcpCodexConfigPath: "Codex can use ~/.codex/config.toml or a project-level .codex/config.toml.",
|
mcpCodexConfigPath: "Codex can use ~/.codex/config.toml or a project-level .codex/config.toml.",
|
||||||
mcpCursorConfigPath: "Cursor can use .cursor/mcp.json in the project or ~/.cursor/mcp.json globally.",
|
mcpCursorConfigPath: "Cursor can use .cursor/mcp.json in the project or ~/.cursor/mcp.json globally.",
|
||||||
|
|||||||
@@ -3173,6 +3173,7 @@ export default withEnglishFallback({
|
|||||||
mcpInstallSuccess: "Instalación exitosa",
|
mcpInstallSuccess: "Instalación exitosa",
|
||||||
mcpInstallFailed: "Error de instalación",
|
mcpInstallFailed: "Error de instalación",
|
||||||
mcpConfig: "Configuración de MCP",
|
mcpConfig: "Configuración de MCP",
|
||||||
|
mcpConfigOptionsHint: "Estas opciones solo actualizan la configuración generada. Cópiala al cliente de IA y reinicia la sesión MCP para aplicarla.",
|
||||||
mcpCodexConfig: "Configuración de Codex",
|
mcpCodexConfig: "Configuración de Codex",
|
||||||
mcpCodexConfigPath: "Codex puede usar ~/.codex/config.toml o .codex/config.toml dentro del proyecto.",
|
mcpCodexConfigPath: "Codex puede usar ~/.codex/config.toml o .codex/config.toml dentro del proyecto.",
|
||||||
mcpCursorConfigPath: "Cursor puede usar .cursor/mcp.json en el proyecto o ~/.cursor/mcp.json globalmente.",
|
mcpCursorConfigPath: "Cursor puede usar .cursor/mcp.json en el proyecto o ~/.cursor/mcp.json globalmente.",
|
||||||
|
|||||||
@@ -3171,6 +3171,7 @@ export default withEnglishFallback({
|
|||||||
mcpInstallSuccess: "Installazione completata",
|
mcpInstallSuccess: "Installazione completata",
|
||||||
mcpInstallFailed: "Installazione fallita",
|
mcpInstallFailed: "Installazione fallita",
|
||||||
mcpConfig: "Configurazione MCP",
|
mcpConfig: "Configurazione MCP",
|
||||||
|
mcpConfigOptionsHint: "Queste opzioni aggiornano solo la configurazione generata. Copiala nel client AI e riavvia la sessione MCP per applicarla.",
|
||||||
mcpCodexConfig: "Configurazione Codex",
|
mcpCodexConfig: "Configurazione Codex",
|
||||||
mcpCodexConfigPath: "Codex può utilizzare ~/.codex/config.toml o un .codex/config.toml a livello di progetto.",
|
mcpCodexConfigPath: "Codex può utilizzare ~/.codex/config.toml o un .codex/config.toml a livello di progetto.",
|
||||||
mcpCursorConfigPath: "Cursor può usare .cursor/mcp.json nel progetto o ~/.cursor/mcp.json globalmente.",
|
mcpCursorConfigPath: "Cursor può usare .cursor/mcp.json nel progetto o ~/.cursor/mcp.json globalmente.",
|
||||||
|
|||||||
@@ -3155,6 +3155,7 @@ export default withEnglishFallback({
|
|||||||
mcpInstallSuccess: "インストール成功",
|
mcpInstallSuccess: "インストール成功",
|
||||||
mcpInstallFailed: "インストール失敗",
|
mcpInstallFailed: "インストール失敗",
|
||||||
mcpConfig: "MCP設定",
|
mcpConfig: "MCP設定",
|
||||||
|
mcpConfigOptionsHint: "これらのオプションは下の生成設定だけを更新します。AIクライアントにコピーした後、MCPセッションを再起動してください。",
|
||||||
mcpCodexConfig: "Codex設定",
|
mcpCodexConfig: "Codex設定",
|
||||||
mcpCodexConfigPath: "Codexは ~/.codex/config.toml またはプロジェクトレベルの .codex/config.toml を使用できます。",
|
mcpCodexConfigPath: "Codexは ~/.codex/config.toml またはプロジェクトレベルの .codex/config.toml を使用できます。",
|
||||||
mcpCursorConfigPath: "Cursorはプロジェクトの .cursor/mcp.json またはグローバル ~/.cursor/mcp.json を使用できます。",
|
mcpCursorConfigPath: "Cursorはプロジェクトの .cursor/mcp.json またはグローバル ~/.cursor/mcp.json を使用できます。",
|
||||||
|
|||||||
@@ -3172,6 +3172,7 @@ export default withEnglishFallback({
|
|||||||
mcpInstallSuccess: "Instalação bem-sucedida",
|
mcpInstallSuccess: "Instalação bem-sucedida",
|
||||||
mcpInstallFailed: "Falha na instalação",
|
mcpInstallFailed: "Falha na instalação",
|
||||||
mcpConfig: "Configuração do MCP",
|
mcpConfig: "Configuração do MCP",
|
||||||
|
mcpConfigOptionsHint: "Estas opções atualizam apenas a configuração gerada. Copie-a para o cliente de IA e reinicie a sessão MCP para aplicá-la.",
|
||||||
mcpCodexConfig: "Configuração do Codex",
|
mcpCodexConfig: "Configuração do Codex",
|
||||||
mcpCodexConfigPath: "O Codex pode usar ~/.codex/config.toml ou um .codex/config.toml no nível do projeto.",
|
mcpCodexConfigPath: "O Codex pode usar ~/.codex/config.toml ou um .codex/config.toml no nível do projeto.",
|
||||||
mcpCursorConfigPath: "O Cursor pode usar .cursor/mcp.json no projeto ou ~/.cursor/mcp.json globalmente.",
|
mcpCursorConfigPath: "O Cursor pode usar .cursor/mcp.json no projeto ou ~/.cursor/mcp.json globalmente.",
|
||||||
|
|||||||
@@ -3274,6 +3274,7 @@ export default withEnglishFallback({
|
|||||||
mcpInstallSuccess: "安装成功",
|
mcpInstallSuccess: "安装成功",
|
||||||
mcpInstallFailed: "安装失败",
|
mcpInstallFailed: "安装失败",
|
||||||
mcpConfig: "MCP 配置",
|
mcpConfig: "MCP 配置",
|
||||||
|
mcpConfigOptionsHint: "以下选项只会更新下方生成的配置文本。复制到 AI 客户端配置后,请重启对应 MCP 会话使其生效。",
|
||||||
mcpCodexConfig: "Codex 配置",
|
mcpCodexConfig: "Codex 配置",
|
||||||
mcpCodexConfigPath: "Codex 可放在 ~/.codex/config.toml 或项目级 .codex/config.toml。",
|
mcpCodexConfigPath: "Codex 可放在 ~/.codex/config.toml 或项目级 .codex/config.toml。",
|
||||||
mcpCursorConfigPath: "Cursor 可放在项目级 .cursor/mcp.json 或全局 ~/.cursor/mcp.json。",
|
mcpCursorConfigPath: "Cursor 可放在项目级 .cursor/mcp.json 或全局 ~/.cursor/mcp.json。",
|
||||||
|
|||||||
@@ -3032,6 +3032,7 @@ export default withEnglishFallback({
|
|||||||
mcpInstallSuccess: "安裝成功",
|
mcpInstallSuccess: "安裝成功",
|
||||||
mcpInstallFailed: "安裝失敗",
|
mcpInstallFailed: "安裝失敗",
|
||||||
mcpConfig: "MCP 設定",
|
mcpConfig: "MCP 設定",
|
||||||
|
mcpConfigOptionsHint: "以下選項只會更新下方產生的設定文字。複製到 AI 用戶端設定後,請重新啟動對應的 MCP 工作階段。",
|
||||||
mcpCodexConfig: "Codex 設定",
|
mcpCodexConfig: "Codex 設定",
|
||||||
mcpCodexConfigPath: "Codex 可放在 ~/.codex/config.toml 或專案級 .codex/config.toml。",
|
mcpCodexConfigPath: "Codex 可放在 ~/.codex/config.toml 或專案級 .codex/config.toml。",
|
||||||
mcpCursorConfigPath: "Cursor 可放在專案級 .cursor/mcp.json 或全域 ~/.cursor/mcp.json。",
|
mcpCursorConfigPath: "Cursor 可放在專案級 .cursor/mcp.json 或全域 ~/.cursor/mcp.json。",
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
import { createAiMessageRenderer } from "@/lib/ai/aiMessageRender";
|
||||||
|
|
||||||
|
describe("createAiMessageRenderer", () => {
|
||||||
|
it("caches completed short messages", () => {
|
||||||
|
const markdown = vi.fn((text: string) => `<p>${text}</p>`);
|
||||||
|
const renderer = createAiMessageRenderer({ markdown, maxCacheableChars: 100 });
|
||||||
|
|
||||||
|
renderer.render("hello");
|
||||||
|
renderer.render("hello");
|
||||||
|
|
||||||
|
expect(markdown).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not retain long streaming message versions", () => {
|
||||||
|
const markdown = vi.fn((text: string) => `<p>${text}</p>`);
|
||||||
|
const renderer = createAiMessageRenderer({ markdown, maxCacheableChars: 5 });
|
||||||
|
|
||||||
|
renderer.render("long message");
|
||||||
|
renderer.render("long message");
|
||||||
|
|
||||||
|
expect(markdown).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -93,6 +93,7 @@ export interface AiRequestInput {
|
|||||||
mode?: AiAssistantMode;
|
mode?: AiAssistantMode;
|
||||||
instruction: string;
|
instruction: string;
|
||||||
context: AiContext;
|
context: AiContext;
|
||||||
|
allowWriteSql?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildAgentRequest(input: AiRequestInput, history?: api.AiMessage[]): { messages: api.AiMessage[]; systemPrompt: string; taskContract: api.AiTaskContract; maxTokens: number } {
|
function buildAgentRequest(input: AiRequestInput, history?: api.AiMessage[]): { messages: api.AiMessage[]; systemPrompt: string; taskContract: api.AiTaskContract; maxTokens: number } {
|
||||||
@@ -163,6 +164,7 @@ export async function runAgentStream(input: AiRequestInput, history: api.AiMessa
|
|||||||
input.context.databaseType,
|
input.context.databaseType,
|
||||||
onEvent,
|
onEvent,
|
||||||
input.mode || "ask",
|
input.mode || "ask",
|
||||||
|
input.allowWriteSql || false,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,11 +22,13 @@ interface MessageSegment {
|
|||||||
|
|
||||||
export interface AiMessageRendererOptions {
|
export interface AiMessageRendererOptions {
|
||||||
maxEntries?: number;
|
maxEntries?: number;
|
||||||
|
maxCacheableChars?: number;
|
||||||
markdown: (text: string) => string;
|
markdown: (text: string) => string;
|
||||||
highlightCode?: (content: string, lang: string) => string;
|
highlightCode?: (content: string, lang: string) => string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const DEFAULT_MAX_ENTRIES = 100;
|
const DEFAULT_MAX_ENTRIES = 100;
|
||||||
|
const DEFAULT_MAX_CACHEABLE_CHARS = 20_000;
|
||||||
const SQL_LANGUAGES = new Map([
|
const SQL_LANGUAGES = new Map([
|
||||||
["sql", "SQL"],
|
["sql", "SQL"],
|
||||||
["mysql", "MYSQL"],
|
["mysql", "MYSQL"],
|
||||||
@@ -48,10 +50,12 @@ const SQL_LANGUAGE_LABELS = new Set(SQL_LANGUAGES.values());
|
|||||||
|
|
||||||
export function createAiMessageRenderer(options: AiMessageRendererOptions) {
|
export function createAiMessageRenderer(options: AiMessageRendererOptions) {
|
||||||
const maxEntries = Math.max(1, Math.floor(options.maxEntries ?? DEFAULT_MAX_ENTRIES));
|
const maxEntries = Math.max(1, Math.floor(options.maxEntries ?? DEFAULT_MAX_ENTRIES));
|
||||||
|
const maxCacheableChars = Math.max(0, Math.floor(options.maxCacheableChars ?? DEFAULT_MAX_CACHEABLE_CHARS));
|
||||||
const cache = new Map<string, AiMessageRenderSegment[]>();
|
const cache = new Map<string, AiMessageRenderSegment[]>();
|
||||||
|
|
||||||
function render(content: string): AiMessageRenderSegment[] {
|
function render(content: string): AiMessageRenderSegment[] {
|
||||||
const cached = cache.get(content);
|
const cacheable = content.length <= maxCacheableChars;
|
||||||
|
const cached = cacheable ? cache.get(content) : undefined;
|
||||||
if (cached) {
|
if (cached) {
|
||||||
cache.delete(content);
|
cache.delete(content);
|
||||||
cache.set(content, cached);
|
cache.set(content, cached);
|
||||||
@@ -72,11 +76,13 @@ export function createAiMessageRenderer(options: AiMessageRendererOptions) {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
cache.set(content, rendered);
|
if (cacheable) {
|
||||||
while (cache.size > maxEntries) {
|
cache.set(content, rendered);
|
||||||
const oldestKey = cache.keys().next().value;
|
while (cache.size > maxEntries) {
|
||||||
if (oldestKey === undefined) break;
|
const oldestKey = cache.keys().next().value;
|
||||||
cache.delete(oldestKey);
|
if (oldestKey === undefined) break;
|
||||||
|
cache.delete(oldestKey);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return rendered;
|
return rendered;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -998,11 +998,11 @@ function isAgentEvent(v: unknown): v is import("@/lib/backend/tauri").AgentEvent
|
|||||||
return typeof v === "object" && v !== null && "type" in v && typeof (v as Record<string, unknown>).type === "string";
|
return typeof v === "object" && v !== null && "type" in v && typeof (v as Record<string, unknown>).type === "string";
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function aiAgentStream(sessionId: string, request: AiCompletionRequest, connectionId: string, database: string, dbType: string, onEvent: (event: import("@/lib/backend/tauri").AgentEvent) => void, mode?: string, signal?: AbortSignal): Promise<string> {
|
export async function aiAgentStream(sessionId: string, request: AiCompletionRequest, connectionId: string, database: string, dbType: string, onEvent: (event: import("@/lib/backend/tauri").AgentEvent) => void, mode?: string, allowWriteSql = false, signal?: AbortSignal): Promise<string> {
|
||||||
const res = await fetch(apiUrl("/api/ai/agent-stream"), {
|
const res = await fetch(apiUrl("/api/ai/agent-stream"), {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ sessionId, request, connectionId, database, dbType, mode: mode || "ask" }),
|
body: JSON.stringify({ sessionId, request, connectionId, database, dbType, mode: mode || "ask", allowWriteSql }),
|
||||||
signal,
|
signal,
|
||||||
});
|
});
|
||||||
if (!res.ok) throw new Error(await res.text());
|
if (!res.ok) throw new Error(await res.text());
|
||||||
|
|||||||
@@ -338,7 +338,7 @@ export type AgentEvent =
|
|||||||
| { type: "context_compacted"; summary: string; summary_tokens: number; compacted_messages: number; estimated_before: number; estimated_after: number }
|
| { type: "context_compacted"; summary: string; summary_tokens: number; compacted_messages: number; estimated_before: number; estimated_after: number }
|
||||||
| { type: "error"; message: string };
|
| { type: "error"; message: string };
|
||||||
|
|
||||||
export async function aiAgentStream(sessionId: string, request: AiCompletionRequest, connectionId: string, database: string, dbType: string, onEvent: (event: AgentEvent) => void, mode?: string, _signal?: AbortSignal): Promise<string> {
|
export async function aiAgentStream(sessionId: string, request: AiCompletionRequest, connectionId: string, database: string, dbType: string, onEvent: (event: AgentEvent) => void, mode?: string, allowWriteSql = false, _signal?: AbortSignal): Promise<string> {
|
||||||
const unlisten: UnlistenFn = await listen<AgentEvent>("ai-agent-event", (event) => {
|
const unlisten: UnlistenFn = await listen<AgentEvent>("ai-agent-event", (event) => {
|
||||||
onEvent(event.payload);
|
onEvent(event.payload);
|
||||||
if (event.payload.type === "agent_end" || event.payload.type === "error") {
|
if (event.payload.type === "agent_end" || event.payload.type === "error") {
|
||||||
@@ -346,7 +346,7 @@ export async function aiAgentStream(sessionId: string, request: AiCompletionRequ
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
return await invoke("ai_agent_stream", { sessionId, request, connectionId, database, dbType, mode });
|
return await invoke("ai_agent_stream", { sessionId, request, connectionId, database, dbType, mode, allowWriteSql });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
unlisten();
|
unlisten();
|
||||||
throw e;
|
throw e;
|
||||||
|
|||||||
@@ -65,6 +65,7 @@ pub struct AgentLoopContext {
|
|||||||
pub database: String,
|
pub database: String,
|
||||||
pub db_type: DatabaseType,
|
pub db_type: DatabaseType,
|
||||||
pub cli_mcp_server_command: Option<CliAgentCommandSpec>,
|
pub cli_mcp_server_command: Option<CliAgentCommandSpec>,
|
||||||
|
pub sql_permissions: agent_tools::AgentSqlPermissions,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check if the provider supports function calling / tool use.
|
/// Check if the provider supports function calling / tool use.
|
||||||
@@ -108,7 +109,8 @@ pub async fn run_agent_loop(
|
|||||||
.map(|config| config.name.clone())
|
.map(|config| config.name.clone())
|
||||||
.unwrap_or_else(|| agent_ctx.connection_id.clone())
|
.unwrap_or_else(|| agent_ctx.connection_id.clone())
|
||||||
};
|
};
|
||||||
let prompt = crate::ai_codex_cli::build_codex_prompt(system_prompt, messages);
|
let prompt =
|
||||||
|
crate::ai_codex_cli::build_codex_prompt(system_prompt, messages, agent_ctx.sql_permissions.allow_writes);
|
||||||
return crate::ai_codex_cli::run_codex_agent(
|
return crate::ai_codex_cli::run_codex_agent(
|
||||||
config,
|
config,
|
||||||
&prompt,
|
&prompt,
|
||||||
@@ -117,6 +119,8 @@ pub async fn run_agent_loop(
|
|||||||
connection_name,
|
connection_name,
|
||||||
database: agent_ctx.database.clone(),
|
database: agent_ctx.database.clone(),
|
||||||
agent_mode: is_agent_mode,
|
agent_mode: is_agent_mode,
|
||||||
|
allow_writes: agent_ctx.sql_permissions.allow_writes,
|
||||||
|
allow_dangerous: agent_ctx.sql_permissions.allow_dangerous,
|
||||||
mcp_server_command: agent_ctx.cli_mcp_server_command.clone(),
|
mcp_server_command: agent_ctx.cli_mcp_server_command.clone(),
|
||||||
},
|
},
|
||||||
cancelled,
|
cancelled,
|
||||||
@@ -140,7 +144,7 @@ pub async fn run_agent_loop(
|
|||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
let tools = if is_agent_mode {
|
let tools = if is_agent_mode {
|
||||||
agent_tools::all_tools(agent_ctx.db_type)
|
agent_tools::all_tools(agent_ctx.db_type, agent_ctx.sql_permissions)
|
||||||
} else {
|
} else {
|
||||||
agent_tools::read_only_tools(agent_ctx.db_type)
|
agent_tools::read_only_tools(agent_ctx.db_type)
|
||||||
};
|
};
|
||||||
@@ -343,6 +347,7 @@ pub async fn run_agent_loop(
|
|||||||
let conn2 = agent_ctx.connection_id.clone();
|
let conn2 = agent_ctx.connection_id.clone();
|
||||||
let db2 = agent_ctx.database.clone();
|
let db2 = agent_ctx.database.clone();
|
||||||
let db_type = agent_ctx.db_type;
|
let db_type = agent_ctx.db_type;
|
||||||
|
let sql_permissions = agent_ctx.sql_permissions;
|
||||||
|
|
||||||
// Split by index into parallel and sequential groups using tool metadata
|
// Split by index into parallel and sequential groups using tool metadata
|
||||||
let tool_parallel_map: std::collections::HashMap<&str, bool> =
|
let tool_parallel_map: std::collections::HashMap<&str, bool> =
|
||||||
@@ -361,7 +366,7 @@ pub async fn run_agent_loop(
|
|||||||
let state = Arc::clone(&state2);
|
let state = Arc::clone(&state2);
|
||||||
let conn = conn2.clone();
|
let conn = conn2.clone();
|
||||||
let db = db2.clone();
|
let db = db2.clone();
|
||||||
async move { agent_tools::execute_tool(&tc, &state, &conn, &db, &db_type).await }
|
async move { agent_tools::execute_tool(&tc, &state, &conn, &db, &db_type, sql_permissions).await }
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
let parallel_results = join_all(parallel_futures).await;
|
let parallel_results = join_all(parallel_futures).await;
|
||||||
@@ -370,7 +375,8 @@ pub async fn run_agent_loop(
|
|||||||
let mut sequential_results = Vec::with_capacity(sequential_indices.len());
|
let mut sequential_results = Vec::with_capacity(sequential_indices.len());
|
||||||
for &i in &sequential_indices {
|
for &i in &sequential_indices {
|
||||||
let tc = make_tc(&collected_tool_calls[i]);
|
let tc = make_tc(&collected_tool_calls[i]);
|
||||||
sequential_results.push(agent_tools::execute_tool(&tc, &state2, &conn2, &db2, &db_type).await);
|
sequential_results
|
||||||
|
.push(agent_tools::execute_tool(&tc, &state2, &conn2, &db2, &db_type, sql_permissions).await);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Merge results back into original order
|
// Merge results back into original order
|
||||||
|
|||||||
@@ -26,6 +26,21 @@ const BROWSE_COLLECTION_LIMIT: usize = 20;
|
|||||||
/// Absolute maximum rows any query tool may request.
|
/// Absolute maximum rows any query tool may request.
|
||||||
const MAX_ALLOWED_ROWS: usize = 100;
|
const MAX_ALLOWED_ROWS: usize = 100;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||||
|
pub struct AgentSqlPermissions {
|
||||||
|
pub allow_writes: bool,
|
||||||
|
pub allow_dangerous: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sql_risk_allowed(risk: SqlRisk, permissions: AgentSqlPermissions) -> bool {
|
||||||
|
match risk {
|
||||||
|
SqlRisk::ReadOnly => true,
|
||||||
|
SqlRisk::Write => permissions.allow_writes,
|
||||||
|
SqlRisk::Ddl => permissions.allow_dangerous,
|
||||||
|
SqlRisk::Transaction => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns true for vector database types (Qdrant, Milvus, Weaviate, ChromaDb).
|
/// Returns true for vector database types (Qdrant, Milvus, Weaviate, ChromaDb).
|
||||||
/// If modifying this, also update VECTOR_DB_TYPES in apps/desktop/src/lib/ai.ts.
|
/// If modifying this, also update VECTOR_DB_TYPES in apps/desktop/src/lib/ai.ts.
|
||||||
pub fn is_vector_db(db_type: DatabaseType) -> bool {
|
pub fn is_vector_db(db_type: DatabaseType) -> bool {
|
||||||
@@ -45,13 +60,13 @@ pub fn read_only_tools(db_type: DatabaseType) -> Vec<ToolDefinition> {
|
|||||||
/// Get all available tool definitions for the given database type.
|
/// Get all available tool definitions for the given database type.
|
||||||
/// Includes read-only tools plus execute_query, get_sample_data, and
|
/// Includes read-only tools plus execute_query, get_sample_data, and
|
||||||
/// explain_query for database types that support them.
|
/// explain_query for database types that support them.
|
||||||
pub fn all_tools(db_type: DatabaseType) -> Vec<ToolDefinition> {
|
pub fn all_tools(db_type: DatabaseType, sql_permissions: AgentSqlPermissions) -> Vec<ToolDefinition> {
|
||||||
if is_vector_db(db_type) {
|
if is_vector_db(db_type) {
|
||||||
return vec![list_collections_tool(), browse_collection_tool()];
|
return vec![list_collections_tool(), browse_collection_tool()];
|
||||||
}
|
}
|
||||||
let mut tools = vec![list_tables_tool(), get_columns_tool()];
|
let mut tools = vec![list_tables_tool(), get_columns_tool()];
|
||||||
if supports_sql_query(db_type) {
|
if supports_sql_query(db_type) {
|
||||||
tools.push(execute_query_tool());
|
tools.push(execute_query_tool(sql_permissions));
|
||||||
tools.push(get_sample_data_tool());
|
tools.push(get_sample_data_tool());
|
||||||
}
|
}
|
||||||
if supports_explain_plan(Some(db_type)) {
|
if supports_explain_plan(Some(db_type)) {
|
||||||
@@ -109,12 +124,17 @@ fn get_columns_tool() -> ToolDefinition {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// execute_query tool definition.
|
/// execute_query tool definition.
|
||||||
fn execute_query_tool() -> ToolDefinition {
|
fn execute_query_tool(sql_permissions: AgentSqlPermissions) -> ToolDefinition {
|
||||||
|
let description = if sql_permissions.allow_dangerous {
|
||||||
|
"Execute SQL after the user explicitly confirmed this operation. Read queries, writes, and DDL are allowed for this run."
|
||||||
|
} else if sql_permissions.allow_writes {
|
||||||
|
"Execute SQL after the user explicitly confirmed this operation. Read queries and non-DDL writes are allowed for this run."
|
||||||
|
} else {
|
||||||
|
"Execute a read-only SQL query and return results (max 50 rows). Only SELECT, WITH, SHOW, DESCRIBE, EXPLAIN statements are allowed. Write operations (INSERT/UPDATE/DELETE/DDL) are blocked."
|
||||||
|
};
|
||||||
ToolDefinition {
|
ToolDefinition {
|
||||||
name: "execute_query",
|
name: "execute_query",
|
||||||
description: "Execute a read-only SQL query and return results (max 50 rows). \
|
description,
|
||||||
Only SELECT, WITH, SHOW, DESCRIBE, EXPLAIN statements are allowed. \
|
|
||||||
Write operations (INSERT/UPDATE/DELETE/DDL) are blocked.",
|
|
||||||
parameters: json!({
|
parameters: json!({
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
@@ -231,11 +251,14 @@ pub async fn execute_tool(
|
|||||||
connection_id: &str,
|
connection_id: &str,
|
||||||
database: &str,
|
database: &str,
|
||||||
db_type: &DatabaseType,
|
db_type: &DatabaseType,
|
||||||
|
sql_permissions: AgentSqlPermissions,
|
||||||
) -> ToolResult {
|
) -> ToolResult {
|
||||||
let result = match tool_call.name.as_str() {
|
let result = match tool_call.name.as_str() {
|
||||||
"list_tables" => execute_list_tables(tool_call, state, connection_id, database, db_type).await,
|
"list_tables" => execute_list_tables(tool_call, state, connection_id, database, db_type).await,
|
||||||
"get_columns" => execute_get_columns(tool_call, state, connection_id, database, db_type).await,
|
"get_columns" => execute_get_columns(tool_call, state, connection_id, database, db_type).await,
|
||||||
"execute_query" => execute_execute_query(tool_call, state, connection_id, database, db_type).await,
|
"execute_query" => {
|
||||||
|
execute_execute_query(tool_call, state, connection_id, database, db_type, sql_permissions).await
|
||||||
|
}
|
||||||
"get_sample_data" => execute_get_sample_data(tool_call, state, connection_id, database, db_type).await,
|
"get_sample_data" => execute_get_sample_data(tool_call, state, connection_id, database, db_type).await,
|
||||||
"list_collections" => execute_list_collections(tool_call, state, connection_id, database, db_type).await,
|
"list_collections" => execute_list_collections(tool_call, state, connection_id, database, db_type).await,
|
||||||
"browse_collection" => execute_browse_collection(tool_call, state, connection_id, database, db_type).await,
|
"browse_collection" => execute_browse_collection(tool_call, state, connection_id, database, db_type).await,
|
||||||
@@ -415,6 +438,7 @@ async fn execute_execute_query(
|
|||||||
connection_id: &str,
|
connection_id: &str,
|
||||||
database: &str,
|
database: &str,
|
||||||
db_type: &DatabaseType,
|
db_type: &DatabaseType,
|
||||||
|
sql_permissions: AgentSqlPermissions,
|
||||||
) -> Result<String, String> {
|
) -> Result<String, String> {
|
||||||
let sql = tool_call.arguments.get("sql").and_then(|v| v.as_str()).ok_or("Missing required parameter: sql")?.trim();
|
let sql = tool_call.arguments.get("sql").and_then(|v| v.as_str()).ok_or("Missing required parameter: sql")?.trim();
|
||||||
|
|
||||||
@@ -432,14 +456,14 @@ async fn execute_execute_query(
|
|||||||
// Classify SQL risk using sqlparser AST
|
// Classify SQL risk using sqlparser AST
|
||||||
let db_type_str = format!("{:?}", db_type).to_lowercase();
|
let db_type_str = format!("{:?}", db_type).to_lowercase();
|
||||||
let risk = crate::sql_risk::classify_sql_risk(sql, &db_type_str)?;
|
let risk = crate::sql_risk::classify_sql_risk(sql, &db_type_str)?;
|
||||||
match risk {
|
if !sql_risk_allowed(risk, sql_permissions) {
|
||||||
SqlRisk::ReadOnly => { /* proceed */ }
|
if risk == SqlRisk::Transaction {
|
||||||
_ => {
|
return Err("Blocked: transaction control statements are not available to the AI agent.".to_string());
|
||||||
return Err(format!(
|
|
||||||
"Blocked: {} statement detected. Only read-only queries (SELECT, SHOW, DESCRIBE, EXPLAIN) are allowed.",
|
|
||||||
risk
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
return Err(format!(
|
||||||
|
"Blocked: {} statement detected. Ask the user to confirm the proposed database change before executing it.",
|
||||||
|
risk
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Execute query using existing infrastructure
|
// Execute query using existing infrastructure
|
||||||
@@ -533,7 +557,8 @@ async fn execute_get_sample_data(
|
|||||||
name: "execute_query".to_string(),
|
name: "execute_query".to_string(),
|
||||||
arguments: serde_json::json!({ "sql": sql, "limit": limit }),
|
arguments: serde_json::json!({ "sql": sql, "limit": limit }),
|
||||||
};
|
};
|
||||||
execute_execute_query(&synthetic_call, state, connection_id, database, db_type).await
|
execute_execute_query(&synthetic_call, state, connection_id, database, db_type, AgentSqlPermissions::default())
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Execute an EXPLAIN query via the explain_query tool.
|
/// Execute an EXPLAIN query via the explain_query tool.
|
||||||
@@ -772,12 +797,32 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn vector_agent_tools_include_collection_browsing() {
|
fn vector_agent_tools_include_collection_browsing() {
|
||||||
let tools = all_tools(DatabaseType::Qdrant);
|
let tools = all_tools(DatabaseType::Qdrant, AgentSqlPermissions::default());
|
||||||
let names: Vec<&str> = tools.iter().map(|tool| tool.name).collect();
|
let names: Vec<&str> = tools.iter().map(|tool| tool.name).collect();
|
||||||
|
|
||||||
assert_eq!(names, vec!["list_collections", "browse_collection"]);
|
assert_eq!(names, vec!["list_collections", "browse_collection"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn confirmed_sql_permissions_update_execute_query_contract() {
|
||||||
|
let tools = all_tools(DatabaseType::Mysql, AgentSqlPermissions { allow_writes: true, allow_dangerous: true });
|
||||||
|
let execute_query = tools.iter().find(|tool| tool.name == "execute_query").unwrap();
|
||||||
|
|
||||||
|
assert!(execute_query.description.contains("explicitly confirmed"));
|
||||||
|
assert!(execute_query.description.contains("DDL"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sql_permissions_keep_writes_blocked_until_confirmation() {
|
||||||
|
assert!(!sql_risk_allowed(SqlRisk::Write, AgentSqlPermissions::default()));
|
||||||
|
assert!(!sql_risk_allowed(SqlRisk::Ddl, AgentSqlPermissions::default()));
|
||||||
|
assert!(sql_risk_allowed(SqlRisk::Ddl, AgentSqlPermissions { allow_writes: true, allow_dangerous: true }));
|
||||||
|
assert!(!sql_risk_allowed(
|
||||||
|
SqlRisk::Transaction,
|
||||||
|
AgentSqlPermissions { allow_writes: true, allow_dangerous: true }
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn build_browse_query_qdrant() {
|
fn build_browse_query_qdrant() {
|
||||||
let q = build_browse_query(&DatabaseType::Qdrant, "articles", "", 10).unwrap();
|
let q = build_browse_query(&DatabaseType::Qdrant, "articles", "", 10).unwrap();
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ pub struct CliAgentRunOptions {
|
|||||||
pub connection_name: String,
|
pub connection_name: String,
|
||||||
pub database: String,
|
pub database: String,
|
||||||
pub agent_mode: bool,
|
pub agent_mode: bool,
|
||||||
|
pub allow_writes: bool,
|
||||||
|
pub allow_dangerous: bool,
|
||||||
pub mcp_server_command: Option<CliAgentCommandSpec>,
|
pub mcp_server_command: Option<CliAgentCommandSpec>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,7 +59,8 @@ pub fn dbx_mcp_enabled_tools(agent_mode: bool) -> Vec<&'static str> {
|
|||||||
|
|
||||||
pub fn dbx_mcp_scope_env(options: &CliAgentRunOptions) -> Vec<(&'static str, String)> {
|
pub fn dbx_mcp_scope_env(options: &CliAgentRunOptions) -> Vec<(&'static str, String)> {
|
||||||
vec![
|
vec![
|
||||||
("DBX_MCP_ALLOW_WRITES", "0".to_string()),
|
("DBX_MCP_ALLOW_WRITES", if options.allow_writes { "1" } else { "0" }.to_string()),
|
||||||
|
("DBX_MCP_ALLOW_DANGEROUS_SQL", if options.allow_dangerous { "1" } else { "0" }.to_string()),
|
||||||
("DBX_MCP_SCOPE_CONNECTION_ID", options.connection_id.clone()),
|
("DBX_MCP_SCOPE_CONNECTION_ID", options.connection_id.clone()),
|
||||||
("DBX_MCP_SCOPE_CONNECTION_NAME", options.connection_name.clone()),
|
("DBX_MCP_SCOPE_CONNECTION_NAME", options.connection_name.clone()),
|
||||||
("DBX_MCP_SCOPE_DATABASE", options.database.clone()),
|
("DBX_MCP_SCOPE_DATABASE", options.database.clone()),
|
||||||
@@ -71,10 +74,20 @@ pub fn append_config_overrides(args: &mut Vec<String>, overrides: impl IntoItera
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn build_cli_agent_prompt(provider_label: &str, system_prompt: &str, messages: &[AiMessage]) -> String {
|
pub fn build_cli_agent_prompt(
|
||||||
|
provider_label: &str,
|
||||||
|
system_prompt: &str,
|
||||||
|
messages: &[AiMessage],
|
||||||
|
allow_write_sql: bool,
|
||||||
|
) -> String {
|
||||||
|
let database_access = if allow_write_sql {
|
||||||
|
"The user explicitly confirmed the proposed database change. DBX MCP tools may execute write and DDL SQL for this run only."
|
||||||
|
} else {
|
||||||
|
"Use the DBX MCP tools when you need live database schema or read-only query results."
|
||||||
|
};
|
||||||
let mut sections = vec![
|
let mut sections = vec![
|
||||||
format!("You are running inside DBX Desktop as the {provider_label} CLI provider."),
|
format!("You are running inside DBX Desktop as the {provider_label} CLI provider."),
|
||||||
"Use the DBX MCP tools when you need live database schema or read-only query results.".to_string(),
|
database_access.to_string(),
|
||||||
"Do not modify files or run shell commands. The DBX MCP server is the only intended tool surface.".to_string(),
|
"Do not modify files or run shell commands. The DBX MCP server is the only intended tool surface.".to_string(),
|
||||||
String::new(),
|
String::new(),
|
||||||
"## System instructions".to_string(),
|
"## System instructions".to_string(),
|
||||||
|
|||||||
@@ -433,8 +433,8 @@ pub fn build_codex_exec_command(config: &AiConfig, _prompt: &str, options: &Code
|
|||||||
CodexCommandSpec { program: codex_program(config), args }
|
CodexCommandSpec { program: codex_program(config), args }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn build_codex_prompt(system_prompt: &str, messages: &[crate::ai::AiMessage]) -> String {
|
pub fn build_codex_prompt(system_prompt: &str, messages: &[crate::ai::AiMessage], allow_write_sql: bool) -> String {
|
||||||
build_cli_agent_prompt("Codex", system_prompt, messages)
|
build_cli_agent_prompt("Codex", system_prompt, messages, allow_write_sql)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_codex_models(config: &AiConfig) -> Result<Vec<AiModelInfo>, String> {
|
pub async fn list_codex_models(config: &AiConfig) -> Result<Vec<AiModelInfo>, String> {
|
||||||
@@ -622,6 +622,8 @@ mod tests {
|
|||||||
connection_name: "local".to_string(),
|
connection_name: "local".to_string(),
|
||||||
database: "demo".to_string(),
|
database: "demo".to_string(),
|
||||||
agent_mode: true,
|
agent_mode: true,
|
||||||
|
allow_writes: false,
|
||||||
|
allow_dangerous: false,
|
||||||
mcp_server_command: None,
|
mcp_server_command: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -639,6 +641,7 @@ mod tests {
|
|||||||
assert!(spec.args.contains(&"mcp_servers.dbx.command=\"dbx-mcp-server\"".to_string()));
|
assert!(spec.args.contains(&"mcp_servers.dbx.command=\"dbx-mcp-server\"".to_string()));
|
||||||
assert!(spec.args.contains(&"mcp_servers.dbx.default_tools_approval_mode=\"approve\"".to_string()));
|
assert!(spec.args.contains(&"mcp_servers.dbx.default_tools_approval_mode=\"approve\"".to_string()));
|
||||||
assert!(spec.args.contains(&"mcp_servers.dbx.env.DBX_MCP_ALLOW_WRITES=\"0\"".to_string()));
|
assert!(spec.args.contains(&"mcp_servers.dbx.env.DBX_MCP_ALLOW_WRITES=\"0\"".to_string()));
|
||||||
|
assert!(spec.args.contains(&"mcp_servers.dbx.env.DBX_MCP_ALLOW_DANGEROUS_SQL=\"0\"".to_string()));
|
||||||
assert!(spec.args.contains(&"mcp_servers.dbx.env.DBX_MCP_SCOPE_CONNECTION_ID=\"conn-1\"".to_string()));
|
assert!(spec.args.contains(&"mcp_servers.dbx.env.DBX_MCP_SCOPE_CONNECTION_ID=\"conn-1\"".to_string()));
|
||||||
assert!(spec.args.iter().any(|arg| arg.contains("dbx_execute_query")));
|
assert!(spec.args.iter().any(|arg| arg.contains("dbx_execute_query")));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,6 +83,8 @@ pub struct AiAgentStreamRequest {
|
|||||||
/// Defaults to "ask" if not provided.
|
/// Defaults to "ask" if not provided.
|
||||||
#[serde(default = "default_agent_mode")]
|
#[serde(default = "default_agent_mode")]
|
||||||
pub mode: String,
|
pub mode: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub allow_write_sql: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_agent_mode() -> String {
|
fn default_agent_mode() -> String {
|
||||||
@@ -265,6 +267,10 @@ pub async fn ai_agent_stream(
|
|||||||
database: body.database,
|
database: body.database,
|
||||||
db_type: parsed_db_type,
|
db_type: parsed_db_type,
|
||||||
cli_mcp_server_command: None,
|
cli_mcp_server_command: None,
|
||||||
|
sql_permissions: dbx_core::agent_tools::AgentSqlPermissions {
|
||||||
|
allow_writes: body.allow_write_sql,
|
||||||
|
allow_dangerous: body.allow_write_sql,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
let sid = session_id.clone();
|
let sid = session_id.clone();
|
||||||
|
|||||||
@@ -86,6 +86,7 @@ pub async fn ai_agent_stream(
|
|||||||
database: String,
|
database: String,
|
||||||
db_type: String,
|
db_type: String,
|
||||||
mode: Option<String>,
|
mode: Option<String>,
|
||||||
|
allow_write_sql: Option<bool>,
|
||||||
) -> Result<String, String> {
|
) -> Result<String, String> {
|
||||||
let request = resolve_codex_cli_request(request);
|
let request = resolve_codex_cli_request(request);
|
||||||
let cancelled = dbx_core::ai::register_stream(&session_id).await;
|
let cancelled = dbx_core::ai::register_stream(&session_id).await;
|
||||||
@@ -104,6 +105,11 @@ pub async fn ai_agent_stream(
|
|||||||
database,
|
database,
|
||||||
db_type: parsed_db_type,
|
db_type: parsed_db_type,
|
||||||
cli_mcp_server_command,
|
cli_mcp_server_command,
|
||||||
|
// Explicit confirmation grants write access only to this agent run.
|
||||||
|
sql_permissions: dbx_core::agent_tools::AgentSqlPermissions {
|
||||||
|
allow_writes: allow_write_sql.unwrap_or(false),
|
||||||
|
allow_dangerous: allow_write_sql.unwrap_or(false),
|
||||||
|
},
|
||||||
};
|
};
|
||||||
let is_agent_mode = mode.as_deref() == Some("agent");
|
let is_agent_mode = mode.as_deref() == Some("agent");
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user