refactor(desktop): organize lib modules by domain

This commit is contained in:
t8y2 committed 2026-07-04 13:53:52 +08:00
1 parent 90f0594e93
commit 7e7c4944e9
700 files changed
+1292 -1264

No files matched your search

+564
View File
@@ -0,0 +1,564 @@
import type { AiConfig } from "@/stores/settingsStore";
import { uuid } from "@/lib/common/utils";
import type { ColumnInfo, ConnectionConfig, DatabaseType, ForeignKeyInfo, IndexInfo, QueryResult, QueryTab } from "@/types/database";
import * as api from "@/lib/backend/api";
import { currentLocale, type Locale } from "@/i18n";
import { aiTableMentionKey, type AiTableMention } from "@/lib/ai/aiTableMentions";
import { aiSkillForAction } from "@/lib/ai/aiSkills";
import { isSchemaAware } from "@/lib/database/databaseCapabilities";
import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
import type { AgentEvent } from "@/lib/backend/tauri";
const VECTOR_DB_TYPES: ReadonlySet<DatabaseType> = new Set([
"qdrant",
"milvus",
"weaviate",
"chromadb",
// If modifying this, also update is_vector_db() in crates/dbx-core/src/agent_tools.rs.
]);
export function isVectorDbType(dbType: DatabaseType): boolean {
return VECTOR_DB_TYPES.has(dbType);
}
function dbLabel(dbType: DatabaseType): string {
const labels: Partial<Record<DatabaseType, string>> = {
qdrant: "Qdrant",
milvus: "Milvus",
weaviate: "Weaviate",
chromadb: "ChromaDB",
};
return labels[dbType] || dbType;
}
export type AiAction = "generate" | "explain" | "optimize" | "fix" | "convert" | "sampleData";
export type AiAssistantMode = "ask" | "agent";
function isChineseLocale(locale: Locale): boolean {
return locale === "zh-CN" || locale === "zh-TW";
}
export interface AiSchemaTable {
schema?: string;
name: string;
tableType: string;
comment?: string | null;
columns: ColumnInfo[];
indexes?: IndexInfo[];
foreignKeys?: ForeignKeyInfo[];
}
export interface AiContext {
connectionId: string;
connectionName: string;
databaseType: DatabaseType;
database: string;
currentSql: string;
lastError?: string;
lastResultPreview?: string;
tables: AiSchemaTable[];
schemaScope?: "focused_table" | "database";
truncated: boolean;
}
export interface AiRequestInput {
config: AiConfig;
action: AiAction;
mode?: AiAssistantMode;
instruction: string;
context: AiContext;
}
function buildAgentRequest(input: AiRequestInput, history?: api.AiMessage[]): { messages: api.AiMessage[]; systemPrompt: string; taskContract: api.AiTaskContract; maxTokens: number } {
const isZh = isChineseLocale(currentLocale());
const systemPrompt = buildSystemPrompt(input.action, input.context, input.mode);
const userPrompt = buildUserPrompt(input.action, input.context, input.instruction, isZh);
const taskContract: api.AiTaskContract = {
action: input.action,
mode: input.mode || "ask",
userRequest: input.instruction.trim(),
};
const messages: api.AiMessage[] = [...(history || []), { role: "user", content: userPrompt }];
const params = actionParams(input.action);
const maxTokens = input.config.enableThinking ? Math.max(params.maxTokens, 8192) : params.maxTokens;
return { messages, systemPrompt, taskContract, maxTokens };
}
export async function runAiAction(input: AiRequestInput, history?: api.AiMessage[]): Promise<string> {
const { messages, systemPrompt, taskContract, maxTokens } = buildAgentRequest(input, history);
return api.aiComplete({
config: input.config,
systemPrompt,
messages,
taskContract,
maxTokens,
});
}
export async function runAiStream(input: AiRequestInput, history: api.AiMessage[] | undefined, onDelta: (delta: string) => void, sessionId?: string, onReasoningDelta?: (delta: string) => void): Promise<void> {
const { messages, systemPrompt, taskContract, maxTokens } = buildAgentRequest(input, history);
const sid = sessionId || uuid();
await api.aiStream(
sid,
{
config: input.config,
systemPrompt,
messages,
taskContract,
maxTokens,
},
(chunk) => {
if (!chunk.done) {
if (chunk.reasoning_delta) onReasoningDelta?.(chunk.reasoning_delta);
if (chunk.delta) onDelta(chunk.delta);
}
},
);
}
export async function runAgentStream(input: AiRequestInput, history: api.AiMessage[] | undefined, onEvent: (event: AgentEvent) => void, sessionId?: string): Promise<string> {
const { messages, systemPrompt, taskContract, maxTokens } = buildAgentRequest(input, history);
const sid = sessionId || uuid();
return api.aiAgentStream(
sid,
{
config: input.config,
systemPrompt,
messages,
taskContract,
maxTokens,
},
input.context.connectionId,
input.context.database,
input.context.databaseType,
onEvent,
input.mode || "ask",
);
}
export function buildUserPrompt(action: AiAction, context: AiContext, instruction: string, isZh: boolean): string {
const userRequest = instruction.trim() || (isZh ? "(无额外说明)" : "(No extra instruction provided.)");
if (isVectorDbType(context.databaseType)) {
// Vector databases: skip SQL action instructions, only send the user's request
return userRequest;
}
const skill = aiSkillForAction(action);
const skillInstruction = isZh ? skill.userInstruction.zh : skill.userInstruction.en;
return [`Action: ${action}`, skillInstruction, "", "User request:", userRequest].join("\n");
}
function actionParams(action: AiAction): { maxTokens: number } {
switch (action) {
case "explain":
return { maxTokens: 3200 };
case "sampleData":
return { maxTokens: 2400 };
default:
return { maxTokens: 2400 };
}
}
export function extractSql(text: string): string {
const fenced = text.match(/```(?:sql|mysql|postgresql|sqlite|tsql|clickhouse)?\s*([\s\S]*?)```/i);
if (fenced?.[1]) return fenced[1].trim();
return text.trim();
}
export function buildSystemPrompt(action: AiAction, context: AiContext, mode: AiAssistantMode = "ask"): string {
if (isVectorDbType(context.databaseType)) {
return buildVectorSystemPrompt(context, mode);
}
const schema = formatSchema(context);
const resultPreview = context.lastResultPreview ? `\nLast result preview:\n${context.lastResultPreview}\n` : "";
const lastError = context.lastError ? `\nLast error:\n${context.lastError}\n` : "";
const schemaScope = context.schemaScope ?? "database";
const isZh = isChineseLocale(currentLocale());
const lines: string[] = [...buildBasePromptLines(isZh), ...buildModePromptLines(mode, isZh), ...buildActionPromptLines(action, isZh)];
if (schemaScope === "focused_table") {
lines.push(
isZh
? "Schema 上下文只覆盖当前打开的表;数据库中可能还有其他表。用户询问当前有哪些表、某表是否存在,或提到上下文中不存在的表时,不要直接断言不存在,优先生成只读元数据查询来核实。"
: "Schema context covers only the currently opened table; the database may contain other tables. When the user asks what tables exist, whether a table exists, or mentions a table absent from context, do not conclude it is missing; prefer a read-only metadata query to verify.",
);
} else if (context.truncated) {
lines.push(
isZh
? "Schema 已截断:如果请求可能涉及未出现的表或字段,不要猜测。请让用户用 @table 指定相关表,或先生成只读探索/元数据查询。"
: "Schema is truncated: if the request may involve tables or columns not shown, do not guess. Ask the user to mention the relevant @table, or generate a read-only exploration/metadata query first.",
);
}
lines.push(
isZh ? "返回 SQL 时放在 ```sql 代码块中。额外说明简短实用。" : "Put SQL in a fenced ```sql code block. Keep extra explanation short and practical.",
"",
`Database type: ${context.databaseType}`,
`Connection: ${context.connectionName}`,
`Database: ${context.database}`,
schemaCoverageLine(context, isZh),
"",
`Current SQL:\n${context.currentSql.trim() || "(empty)"}`,
lastError,
resultPreview,
`Schema:\n${schema}`,
);
return lines.filter(Boolean).join("\n");
}
function buildBasePromptLines(isZh: boolean): string[] {
return [
isZh ? "你是 DBX 内置的数据库助手。用中文回复。" : "You are DBX's built-in database assistant. Reply in English.",
isZh ? "精确、保守,根据当前数据库方言生成 SQL。" : "Be precise, conservative, and adapt SQL to the active database dialect.",
isZh ? "严格使用当前数据库方言;标识符引用、分页、日期函数、字符串拼接、LIMIT/TOP/OFFSET 语法必须匹配数据库类型。" : "Strictly use the active database dialect; identifier quoting, pagination, date functions, string concatenation, and LIMIT/TOP/OFFSET syntax must match the database type.",
isZh
? '标识符引用必须匹配当前连接类型:MySQL/MariaDB 用反引号 `name`,PostgreSQL/SQLite/Oracle 等用双引号 "name",SQL Server 用方括号 [name];不要因为用户口头提到其他数据库而切换方言。'
: 'Identifier quoting must match the active connection type: MySQL/MariaDB use backticks `name`, PostgreSQL/SQLite/Oracle and similar dialects use double quotes "name", and SQL Server uses brackets [name]. Do not switch dialects merely because the user mentions another database in prose.',
isZh
? "对于普通数据查询,优先使用下面已加载的 Schema 上下文,不要为了重复确认已给出的结构而查询 information_schema 或系统表。但当用户询问某表的字段详情、列信息时,应使用 get_columns 工具获取最权威完整的定义。"
: "For ordinary data queries, prefer the loaded schema context below. Do not query information_schema or system tables merely to rediscover structure already provided. However, when the user asks for detailed column/field information of a specific table, use the get_columns tool for the authoritative and complete definition.",
isZh
? "例外:当用户明确询问当前有哪些表/Schema、某张表是否存在、或需要盘点数据库对象时,应生成符合当前方言的只读元数据查询(例如 SHOW TABLES、information_schema、sqlite_master 等)。"
: "Exception: when the user explicitly asks what tables/schemas exist, whether a table exists, or asks for database object inventory, generate a read-only metadata query appropriate for the active dialect (for example SHOW TABLES, information_schema, sqlite_master).",
isZh ? "表注释和列注释是语义别名;当用户用中文业务名描述表或字段时,优先根据注释匹配真实表名和字段名。" : "Table and column comments are semantic aliases; when the user describes tables or fields by business names, prefer matching those comments to the real table and column names.",
isZh ? "当用户要求分析或查看某个表时,生成 SELECT 查询获取数据,而不是查询元数据。" : "When the user asks to 'analyze' or 'look at' a table, generate a SELECT query to retrieve data, not a metadata query.",
isZh ? "不要编造 Schema 中不存在的表或列。" : "Never invent tables or columns that are not in the schema context.",
isZh ? "用户输入中的 @schema.table 或 @table 表示用户明确提到的表;这些表已优先放入 Schema 上下文。" : "User input may contain @schema.table or @table mentions. Treat them as explicit table references; mentioned tables are prioritized in the schema context.",
isZh ? "不要生成多语句 SQL,除非用户明确要求。不要在同一个回答里混合 SELECT 和写操作。" : "Do not generate multi-statement SQL unless the user explicitly asks for it. Do not mix SELECT statements and write operations in the same answer.",
isZh ? "对于 DROP、DELETE、TRUNCATE、ALTER 或没有 WHERE 的 UPDATE,简要警告并优先提供安全的 SELECT 预览。" : "For destructive statements (DROP, DELETE, TRUNCATE, ALTER, UPDATE without WHERE), warn briefly and prefer a safer SELECT preview.",
isZh ? "对于 UPDATE 或 DELETE,必须带 WHERE 并说明影响范围;生产库写操作只给建议,不主动建议执行。" : "For UPDATE or DELETE, require a WHERE clause and explain the affected scope; for production writes, provide guidance but do not proactively suggest execution.",
isZh ? "当用户回复简短肯定词时(例如:需要、好、可以、对),直接执行你之前提议的动作,不要再反问确认。" : "When the user replies with a short affirmative (e.g.: Yes, OK, Sure, Do it), directly execute the action you previously proposed — do not ask for confirmation again.",
];
}
function buildVectorSystemPrompt(context: AiContext, mode: AiAssistantMode): string {
const isZh = isChineseLocale(currentLocale());
const schema = formatSchema(context);
const resultPreview = context.lastResultPreview ? `\nLast result preview:\n${context.lastResultPreview}\n` : "";
const lastError = context.lastError ? `\nLast error:\n${context.lastError}\n` : "";
const lines: string[] = [
isZh ? `你是 DBX 内置的向量数据库助手。当前连接的是 ${dbLabel(context.databaseType)} 数据库。用中文回复。` : `You are DBX's vector database assistant. Connected to ${dbLabel(context.databaseType)}. Reply in English.`,
isZh ? "数据存储在集合(collections)中,每条记录包含唯一标识及可选的元数据负载(payload/metadata)。" : "Data is stored in collections. Each record has a unique identifier and optional metadata payload.",
...buildVectorModePromptLines(context, mode, isZh),
"",
`Database type: ${context.databaseType}`,
`Connection: ${context.connectionName}`,
`Database: ${context.database}`,
schemaCoverageLine(context, isZh),
"",
`Current collection:\n${context.currentSql.trim() || "(none)"}`,
lastError,
resultPreview,
"",
`Schema:\n${schema}`,
];
if (context.schemaScope === "focused_table") {
lines.push(
isZh
? "Schema 上下文只覆盖当前打开的集合;数据库中可能还有其他集合。用户询问当前有哪些集合或提到上下文中不存在的集合时,不要直接断言不存在,先用 list_collections 工具确认。"
: "Schema context covers only the currently opened collection; the database may contain other collections. When the user asks what collections exist or mentions a collection absent from context, do not conclude it is missing; use list_collections to verify first.",
);
}
return lines.filter(Boolean).join("\n");
}
function buildVectorModePromptLines(context: AiContext, mode: AiAssistantMode, isZh: boolean): string[] {
if (mode === "agent") {
return [isZh ? "你处于 Agent 模式。你有以下工具可用:list_collections、browse_collection。" : "You are in Agent mode. You have the following tools available: list_collections, browse_collection."];
}
return [
isZh
? `你处于 Ask 模式。你只能使用 list_collections 确认集合清单;不要浏览集合数据。${dbLabel(context.databaseType)} 的查询格式为 REST API(METHOD /path + JSON body),具体格式因数据库类型而异。只生成查询请求文本和说明,不要暗示已经执行。`
: `You are in Ask mode. You may only use list_collections to inspect collection names; do not browse collection data. ${dbLabel(context.databaseType)} uses a REST API query format (METHOD /path + JSON body) that varies by database type. Generate query strings and explanations only; do not imply execution.`,
];
}
function buildModePromptLines(mode: AiAssistantMode, isZh: boolean): string[] {
if (mode === "agent") {
return [
isZh ? "你处于 Agent 模式。你有以下工具可用:list_tables、get_columns、execute_query、get_sample_data。" : "You are in Agent mode. You have the following tools available: list_tables, get_columns, execute_query, get_sample_data.",
isZh
? "用户提出数据查询意图时,必须调用 execute_query 工具执行 SQL,不要只输出 SQL 文本后停止。先用 list_tables/get_columns 了解 schema,再调用 execute_query 获取真实结果,最后基于结果回答用户。"
: "When the user expresses a data query intent, you MUST call the execute_query tool to run the SQL — do NOT just output SQL text and stop. Use list_tables/get_columns to understand the schema first, then call execute_query to get real results, then answer based on the actual data.",
isZh
? "只有 SELECT、WITH、SHOW、DESCRIBE、EXPLAIN 可以通过 execute_query 执行。如果用户要求写入操作,先解释原因,不要执行。"
: "Only SELECT, WITH, SHOW, DESCRIBE, EXPLAIN can be executed via execute_query. If the user requests a write operation, explain why it is blocked instead of executing.",
isZh ? "如果安全执行条件不满足,先说明原因,再给只读预览或澄清问题。" : "If safe execution requirements are not met, explain why first, then provide a read-only preview or a clarifying question.",
];
}
return [isZh ? "你处于 Ask 模式。只生成 SQL 和说明,不要暗示已经执行或即将自动执行。" : "You are in Ask mode. Generate SQL and explanations only; do not imply that anything has run or will auto-run."];
}
function schemaCoverageLine(context: AiContext, isZh: boolean): string {
if (context.schemaScope === "focused_table") {
if (isVectorDbType(context.databaseType)) {
return isZh ? "Schema 上下文只覆盖当前打开的集合,不是完整的集合列表。" : "Schema context scope: focused collection only; not a complete collection list.";
}
return "Schema context scope: focused table only; not a complete database table list.";
}
return context.truncated ? "Schema context is truncated." : "Schema context is complete for the loaded database scope.";
}
function buildActionPromptLines(action: AiAction, isZh: boolean): string[] {
const skill = aiSkillForAction(action);
return isZh ? [...skill.systemRules.zh, ...skill.outputContract.zh] : [...skill.systemRules.en, ...skill.outputContract.en];
}
function formatSchema(context: AiContext): string {
if (!context.tables.length) return "(No table schema loaded.)";
return context.tables
.map((table) => {
const name = table.schema ? `${table.schema}.${table.name}` : table.name;
const lines: string[] = [`${name} (${table.tableType})`];
const tableComment = table.comment?.trim();
if (tableComment) lines.push(` Comment: ${tableComment}`);
for (const column of table.columns) {
const flags = [column.is_primary_key ? "PK" : "", column.is_nullable ? "nullable" : "NOT NULL", column.column_default ? `default ${column.column_default}` : "", column.extra || ""].filter(Boolean).join(", ");
const columnComment = column.comment?.trim();
lines.push(` - ${column.name}: ${column.data_type}${flags ? ` (${flags})` : ""}${columnComment ? ` -- ${columnComment}` : ""}`);
}
if (table.indexes?.length) {
for (const idx of table.indexes) {
if (idx.is_primary) continue;
const unique = idx.is_unique ? "UNIQUE " : "";
lines.push(` Index: ${unique}${idx.name}(${idx.columns.join(", ")})`);
}
}
if (table.foreignKeys?.length) {
for (const fk of table.foreignKeys) {
lines.push(` FK: ${fk.column} → ${fk.ref_table}.${fk.ref_column}`);
}
}
return lines.join("\n");
})
.join("\n\n");
}
export async function buildAiContext(tab: QueryTab, connection: ConnectionConfig, options: { maxTables?: number; maxColumnsPerTable?: number; maxIndexesPerTable?: number; maxFksPerTable?: number; mentionedTables?: AiTableMention[] } = {}): Promise<AiContext> {
const maxTables = options.maxTables ?? 50;
const maxColumnsPerTable = options.maxColumnsPerTable ?? 40;
const maxIndexesPerTable = options.maxIndexesPerTable ?? 10;
const maxFksPerTable = options.maxFksPerTable ?? 10;
const databaseType = aiDatabaseTypeForConnection(connection);
const tables: AiSchemaTable[] = [];
const tableKeys = new Set<string>();
let truncated = false;
let schemaScope: AiContext["schemaScope"] = "database";
let currentCollectionName: string | undefined;
if (tab.tableMeta) {
schemaScope = "focused_table";
const s = tab.tableMeta.schema ?? "";
const tName = tab.tableMeta.tableName;
const [indexes, foreignKeys] = await Promise.all([api.listIndexes(tab.connectionId, tab.database, s, tName).catch(() => [] as IndexInfo[]), api.listForeignKeys(tab.connectionId, tab.database, s, tName).catch(() => [] as ForeignKeyInfo[])]);
const tableComment = await loadTableComment(tab.connectionId, tab.database, s, tName).catch(() => undefined);
tables.push({
schema: tab.tableMeta.schema,
name: tName,
tableType: "TABLE",
comment: tableComment,
columns: tab.tableMeta.columns.slice(0, maxColumnsPerTable),
indexes: indexes.slice(0, maxIndexesPerTable),
foreignKeys: foreignKeys.slice(0, maxFksPerTable),
});
tableKeys.add(aiTableMentionKey(tab.tableMeta.schema, tName));
truncated = tab.tableMeta.columns.length > maxColumnsPerTable;
}
for (const mention of options.mentionedTables ?? []) {
const key = aiTableMentionKey(mention.schema, mention.table);
if (tableKeys.has(key)) continue;
const entry = await loadMentionedTableContext(tab, connection, mention, maxColumnsPerTable, maxIndexesPerTable, maxFksPerTable).catch(() => undefined);
if (!entry) continue;
tableKeys.add(aiTableMentionKey(entry.schema, entry.name));
tables.push(entry);
}
// Vector databases: load collections instead of SQL tables
if (isVectorDbType(databaseType)) {
try {
const collections = await api.vectorListCollections(tab.connectionId, tab.database);
// Find the currently opened collection (tab.sql is UUID for ChromaDB, name for others)
const currentCollection = collections.find((c) => c.id === tab.sql || c.name === tab.sql);
if (currentCollection) {
schemaScope = "focused_table";
currentCollectionName = currentCollection.name;
tables.push({
name: currentCollection.name,
tableType: "COLLECTION",
comment: currentCollection.dimension ? `${currentCollection.dimension}d vector` : undefined,
columns: [],
});
tableKeys.add(aiTableMentionKey(undefined, currentCollection.name));
}
for (const col of collections.slice(0, maxTables)) {
const key = aiTableMentionKey(undefined, col.name);
if (tableKeys.has(key)) continue;
tables.push({
name: col.name,
tableType: "COLLECTION",
comment: col.dimension ? `${col.dimension}d vector` : undefined,
columns: [],
});
tableKeys.add(key);
}
if (collections.length > maxTables) truncated = true;
} catch {
truncated = true;
}
}
if (!tab.tableMeta && !["redis", "mongodb"].includes(connection.db_type) && !isVectorDbType(databaseType)) {
try {
const schemas = await loadCandidateSchemas(tab, connection);
for (const schema of schemas) {
const tableList = await api.listTables(tab.connectionId, tab.database, schema);
const candidates = tableList.slice(0, maxTables - tables.length);
if (candidates.length < tableList.length) truncated = true;
const metaResults = await Promise.all(
candidates.map((table) =>
Promise.all([
api.getColumns(tab.connectionId, tab.database, schema, table.name),
api.listIndexes(tab.connectionId, tab.database, schema, table.name).catch(() => [] as IndexInfo[]),
api.listForeignKeys(tab.connectionId, tab.database, schema, table.name).catch(() => [] as ForeignKeyInfo[]),
]).then(([columns, indexes, foreignKeys]) => ({
schema: schema === tab.database && !isSchemaAware(databaseType) ? undefined : schema,
name: table.name,
tableType: table.table_type,
comment: table.comment,
columns: columns.slice(0, maxColumnsPerTable),
indexes: indexes.slice(0, maxIndexesPerTable),
foreignKeys: foreignKeys.slice(0, maxFksPerTable),
_truncatedCols: columns.length > maxColumnsPerTable,
})),
),
);
for (const meta of metaResults) {
if (meta._truncatedCols) truncated = true;
const { _truncatedCols, ...entry } = meta;
const key = aiTableMentionKey(entry.schema, entry.name);
if (tableKeys.has(key)) continue;
tableKeys.add(key);
tables.push(entry);
}
if (tables.length >= maxTables) break;
}
} catch {
truncated = true;
}
}
return {
connectionId: tab.connectionId,
connectionName: connection.name,
databaseType,
database: tab.database,
currentSql: currentCollectionName ?? tab.sql,
lastError: extractLastError(tab.result),
lastResultPreview: formatResultPreview(tab.result),
tables,
schemaScope,
truncated,
};
}
async function loadMentionedTableContext(tab: QueryTab, connection: ConnectionConfig, mention: AiTableMention, maxColumnsPerTable: number, maxIndexesPerTable: number, maxFksPerTable: number): Promise<AiSchemaTable | undefined> {
const databaseType = aiDatabaseTypeForConnection(connection);
const schema = await resolveMentionedTableSchema(tab, connection, mention);
const [columns, indexes, foreignKeys, tableComment] = await Promise.all([
api.getColumns(tab.connectionId, tab.database, schema, mention.table),
api.listIndexes(tab.connectionId, tab.database, schema, mention.table).catch(() => [] as IndexInfo[]),
api.listForeignKeys(tab.connectionId, tab.database, schema, mention.table).catch(() => [] as ForeignKeyInfo[]),
loadTableComment(tab.connectionId, tab.database, schema, mention.table).catch(() => undefined),
]);
return {
schema: schema === tab.database && !isSchemaAware(databaseType) ? undefined : schema,
name: mention.table,
tableType: "TABLE",
comment: tableComment,
columns: columns.slice(0, maxColumnsPerTable),
indexes: indexes.slice(0, maxIndexesPerTable),
foreignKeys: foreignKeys.slice(0, maxFksPerTable),
};
}
async function loadTableComment(connectionId: string, database: string, schema: string, tableName: string): Promise<string | undefined> {
const tables = await api.listTables(connectionId, database, schema, tableName, 10);
return tables.find((table) => table.name.toLowerCase() === tableName.toLowerCase())?.comment?.trim() || undefined;
}
async function resolveMentionedTableSchema(tab: QueryTab, connection: ConnectionConfig, mention: AiTableMention): Promise<string> {
if (mention.schema) return mention.schema;
if (tab.tableMeta?.tableName.toLowerCase() === mention.table.toLowerCase() && tab.tableMeta.schema) {
return tab.tableMeta.schema;
}
if (isSchemaAware(aiDatabaseTypeForConnection(connection))) {
const schemas = await loadCandidateSchemas(tab, connection);
for (const schema of schemas) {
const tables = await api.listTables(tab.connectionId, tab.database, schema, mention.table, 10).catch(() => []);
if (tables.some((table) => table.name.toLowerCase() === mention.table.toLowerCase())) return schema;
}
}
return tab.database || connection.database || "main";
}
async function loadCandidateSchemas(tab: QueryTab, connection: ConnectionConfig): Promise<string[]> {
if (isSchemaAware(aiDatabaseTypeForConnection(connection))) {
const schemas = await api.listSchemas(tab.connectionId, tab.database);
return prioritizeSchemas(schemas);
}
return [tab.database || connection.database || "main"];
}
function aiDatabaseTypeForConnection(connection: ConnectionConfig): DatabaseType {
return effectiveDatabaseTypeForConnection(connection) ?? connection.db_type;
}
function prioritizeSchemas(schemas: string[]): string[] {
const preferred = ["public", "dbo", "main"];
return [...schemas].sort((a, b) => {
const ai = preferred.indexOf(a);
const bi = preferred.indexOf(b);
if (ai >= 0 || bi >= 0) return (ai >= 0 ? ai : 99) - (bi >= 0 ? bi : 99);
return a.localeCompare(b);
});
}
function extractLastError(result?: QueryResult): string | undefined {
if (!result?.columns.includes("Error")) return undefined;
return result.rows[0]?.[0] == null ? undefined : String(result.rows[0][0]);
}
function formatResultPreview(result?: QueryResult): string | undefined {
if (!result || result.columns.includes("Error") || !result.rows.length) return undefined;
const MAX_VALUE_CHARS = 200;
const rows = result.rows.slice(0, 5).map((row) => {
return result.columns
.map((column, index) => {
const raw = JSON.stringify(row[index] ?? null);
const val = raw.length > MAX_VALUE_CHARS ? raw.slice(0, MAX_VALUE_CHARS) + "…" : raw;
return `${column}=${val}`;
})
.join(", ");
});
return rows.join("\n");
}
+84
View File
@@ -0,0 +1,84 @@
import type { AiAction, AiAssistantMode } from "@/lib/ai/ai";
import { classifyAiSqlExecution, shouldAttemptAiAutoExecute, stripAiSqlComments, type AiSqlExecutionDecision } from "@/lib/ai/aiSqlExecutionPolicy";
import type { ConnectionConfig } from "@/types/database";
export type AiAgentStep =
| { kind: "generate_sql"; status: "done"; sql: string }
| { kind: "generate_sql"; status: "skipped"; reason: "no_sql" }
| ({
kind: "risk_check";
status: "done";
} & AiSqlExecutionDecision)
| { kind: "execute_sql"; status: "pending"; sql: string }
| {
kind: "execute_sql";
status: "skipped";
reason: "ask_mode" | "no_sql" | "no_execution_intent" | "unsupported_action" | "blocked_by_policy" | "requires_confirmation";
};
export interface AiAgentPlanInput {
mode: AiAssistantMode;
action: AiAction;
instruction: string;
assistantContent: string;
connection?: ConnectionConfig;
}
export interface AiAgentPlan {
steps: AiAgentStep[];
executableSql?: string;
handoffSql?: string;
}
export function buildAiAgentPlan(input: AiAgentPlanInput): AiAgentPlan {
const sql = extractFirstExecutableSqlCodeBlock(input.assistantContent);
if (!sql) {
return {
steps: [
{ kind: "generate_sql", status: "skipped", reason: "no_sql" },
{ kind: "execute_sql", status: "skipped", reason: "no_sql" },
],
};
}
const steps: AiAgentStep[] = [{ kind: "generate_sql", status: "done", sql }];
if (input.mode !== "agent") {
steps.push({ kind: "execute_sql", status: "skipped", reason: "ask_mode" });
return { steps };
}
if (input.action !== "generate") {
steps.push({ kind: "execute_sql", status: "skipped", reason: "unsupported_action" });
return { steps };
}
if (!shouldAttemptAiAutoExecute(input.instruction, input.action)) {
steps.push({ kind: "execute_sql", status: "skipped", reason: "no_execution_intent" });
return { steps };
}
const decision = classifyAiSqlExecution(sql, input.connection);
steps.push({ kind: "risk_check", status: "done", ...decision });
if (decision.action === "auto_execute") {
steps.push({ kind: "execute_sql", status: "pending", sql });
return { steps, executableSql: sql, handoffSql: sql };
}
steps.push({
kind: "execute_sql",
status: "skipped",
reason: decision.action === "block" ? "blocked_by_policy" : "requires_confirmation",
});
return { steps, handoffSql: sql };
}
function extractFirstExecutableSqlCodeBlock(content: string): string | undefined {
const blocks = content.matchAll(/```(?:sql|mysql|postgresql|sqlite|tsql|clickhouse)?\s*\n([\s\S]*?)```/gi);
for (const block of blocks) {
const sql = block[1]?.trim();
if (sql && stripAiSqlComments(sql).trim()) return sql;
}
return undefined;
}
@@ -0,0 +1,119 @@
import type { AiAgentPlan, AiAgentStep } from "@/lib/ai/aiAgentPlan";
export type AiAgentStepTone = "success" | "active" | "warning" | "danger" | "muted";
export interface AiAgentStepItem {
key: string;
labelKey: string;
tone: AiAgentStepTone;
titleKey?: string;
titleParams?: Record<string, string>;
/** Tool name for display */
toolName?: string;
/** Tool arguments (e.g., SQL query) for display */
toolArgs?: Record<string, unknown>;
/** Tool result content (e.g., query results) for display */
toolResult?: string;
/** Whether this is an error result */
isError?: boolean;
/** Structured explain plan data (for explain_query tool results) */
explainData?: unknown;
}
/** Backend fallback tool_call_id values that repeat across calls and must not be used as stable merge keys. */
const REPEATING_TOOL_CALL_IDS = new Set(["cli-tool-call"]);
/**
* Build a tool step key. Real tool_call_id values merge start/end into one card;
* missing or known repeating fallback IDs stay event-specific to avoid collapsing unrelated calls.
*/
export function toolCallStepKey(toolCallId: string, index: number, eventType: string): string {
if (toolCallId && !REPEATING_TOOL_CALL_IDS.has(toolCallId)) return `tool-${toolCallId}`;
return `tool-${eventType}-${index}`;
}
/** Upsert a step, preserving details gathered from the previous state of the same card. */
export function upsertAgentStep(steps: AiAgentStepItem[], step: AiAgentStepItem) {
const idx = steps.findIndex((s) => s.key === step.key);
if (idx < 0) {
steps.push(step);
return;
}
const existing = steps[idx];
const merged: AiAgentStepItem = { ...step };
if (!merged.toolArgs && existing.toolArgs) merged.toolArgs = existing.toolArgs;
if (!merged.explainData && existing.explainData) merged.explainData = existing.explainData;
if (!merged.titleKey && existing.titleKey) merged.titleKey = existing.titleKey;
if (!merged.titleParams && existing.titleParams) merged.titleParams = existing.titleParams;
steps.splice(idx, 1, merged);
}
export function buildAiAgentStepItems(plan: AiAgentPlan): AiAgentStepItem[] {
return plan.steps.map(presentStep);
}
function presentStep(step: AiAgentStep): AiAgentStepItem {
if (step.kind === "generate_sql") {
if (step.status === "done") {
return { key: "generated", labelKey: "ai.agentSteps.generated", tone: "success" };
}
return { key: "noSql", labelKey: "ai.agentSteps.noSql", tone: "muted" };
}
if (step.kind === "risk_check") {
const title = {
titleKey: "ai.agentStepTitles.riskCheck",
titleParams: {
action: step.action,
category: step.category,
environment: step.environment,
reasons: step.reasons.length ? step.reasons.join(", ") : "-",
},
};
if (step.action === "auto_execute") {
return { key: "safe", labelKey: "ai.agentSteps.safe", tone: "success", ...title };
}
if (step.action === "confirm") {
return { key: "needsConfirm", labelKey: "ai.agentSteps.needsConfirm", tone: "warning", ...title };
}
return { key: "blocked", labelKey: "ai.agentSteps.blocked", tone: "danger", ...title };
}
if (step.status === "pending") {
return { key: "autoExecute", labelKey: "ai.agentSteps.autoExecute", tone: "active" };
}
if (step.reason === "no_execution_intent") {
return {
key: "notRequested",
labelKey: "ai.agentSteps.notRequested",
titleKey: "ai.agentStepTitles.notRequested",
tone: "muted",
};
}
return {
key: "skipped",
labelKey: "ai.agentSteps.skipped",
titleKey: skippedTitleKey(step.reason),
tone: "muted",
};
}
function skippedTitleKey(reason: string): string {
switch (reason) {
case "blocked_by_policy":
return "ai.agentStepTitles.blocked";
case "requires_confirmation":
return "ai.agentStepTitles.requiresConfirmation";
case "ask_mode":
return "ai.agentStepTitles.askMode";
case "unsupported_action":
return "ai.agentStepTitles.unsupportedAction";
case "no_sql":
return "ai.agentStepTitles.noSql";
default:
return "ai.agentStepTitles.skipped";
}
}
@@ -0,0 +1,101 @@
import type { AppThemeAppearance } from "@/lib/app/appTheme";
export type AiCodeHighlighter = (content: string, lang: string, appearance?: AppThemeAppearance) => string;
interface AiShikiCodeHighlighterOptions {
appearance: () => AppThemeAppearance;
}
const SHIKI_THEMES = {
dark: "github-dark",
light: "github-light",
} as const;
const SHIKI_LANGUAGES = ["bash", "css", "go", "html", "java", "javascript", "json", "markdown", "php", "python", "rust", "shellscript", "sql", "tsx", "typescript", "vue", "xml", "yaml"] as const;
const SHIKI_LANG_BY_AI_LABEL: Record<string, (typeof SHIKI_LANGUAGES)[number] | "text"> = {
BASH: "bash",
CLICKHOUSE: "sql",
CSS: "css",
GO: "go",
HTML: "html",
JAVA: "java",
JAVASCRIPT: "javascript",
JS: "javascript",
JSON: "json",
MARKDOWN: "markdown",
MYSQL: "sql",
PHP: "php",
POSTGRESQL: "sql",
PYTHON: "python",
RUST: "rust",
SHELL: "shellscript",
SH: "shellscript",
SQL: "sql",
SQLITE: "sql",
TS: "typescript",
TSQL: "sql",
TSX: "tsx",
TYPESCRIPT: "typescript",
VUE: "vue",
XML: "xml",
YAML: "yaml",
YML: "yaml",
ZSH: "shellscript",
};
type ShikiHighlighter = Awaited<ReturnType<typeof import("shiki/core").createHighlighterCore>>;
let highlighterPromise: Promise<ShikiHighlighter> | undefined;
export async function createAiShikiCodeHighlighter(options: AiShikiCodeHighlighterOptions): Promise<AiCodeHighlighter> {
const highlighter = await getAiShikiHighlighter();
return (content, lang, appearance = options.appearance()) =>
highlighter.codeToHtml(content, {
lang: resolveShikiLanguage(lang),
structure: "inline",
theme: SHIKI_THEMES[appearance],
});
}
function getAiShikiHighlighter(): Promise<ShikiHighlighter> {
highlighterPromise ??= loadAiShikiHighlighter();
return highlighterPromise;
}
async function loadAiShikiHighlighter(): Promise<ShikiHighlighter> {
const [{ createHighlighterCore }, { createJavaScriptRegexEngine }, githubDark, githubLight, bash, css, go, html, java, javascript, json, markdown, php, python, rust, shellscript, sql, tsx, typescript, vue, xml, yaml] = await Promise.all([
import("shiki/core"),
import("shiki/engine/javascript"),
import("shiki/themes/github-dark.mjs"),
import("shiki/themes/github-light.mjs"),
import("shiki/langs/bash.mjs"),
import("shiki/langs/css.mjs"),
import("shiki/langs/go.mjs"),
import("shiki/langs/html.mjs"),
import("shiki/langs/java.mjs"),
import("shiki/langs/javascript.mjs"),
import("shiki/langs/json.mjs"),
import("shiki/langs/markdown.mjs"),
import("shiki/langs/php.mjs"),
import("shiki/langs/python.mjs"),
import("shiki/langs/rust.mjs"),
import("shiki/langs/shellscript.mjs"),
import("shiki/langs/sql.mjs"),
import("shiki/langs/tsx.mjs"),
import("shiki/langs/typescript.mjs"),
import("shiki/langs/vue.mjs"),
import("shiki/langs/xml.mjs"),
import("shiki/langs/yaml.mjs"),
]);
return createHighlighterCore({
engine: createJavaScriptRegexEngine(),
langs: [bash.default, css.default, go.default, html.default, java.default, javascript.default, json.default, markdown.default, php.default, python.default, rust.default, shellscript.default, sql.default, tsx.default, typescript.default, vue.default, xml.default, yaml.default],
themes: [githubDark.default, githubLight.default],
});
}
function resolveShikiLanguage(lang: string): (typeof SHIKI_LANGUAGES)[number] | "text" {
return SHIKI_LANG_BY_AI_LABEL[lang.toUpperCase()] ?? "text";
}
+119
View File
@@ -0,0 +1,119 @@
import { Marked, type Tokens } from "marked";
const EXTERNAL_LINK_PROTOCOLS = new Set(["http:", "https:"]);
export interface AiMarkdownLinkClickEvent {
target: unknown;
currentTarget: unknown;
preventDefault: () => void;
stopPropagation: () => void;
}
export type AiMarkdownLinkOpener = (url: string) => void | Promise<void>;
const markedInstance = new Marked({
breaks: true,
gfm: true,
renderer: {
codespan({ text }: Tokens.Codespan) {
return `<code class="rounded bg-muted px-1.5 py-0.5 text-[11px] font-mono">${escapeHtml(text)}</code>`;
},
html({ text }: Tokens.HTML | Tokens.Tag) {
return escapeHtml(text);
},
link({ href, title, tokens }: Tokens.Link) {
const label = this.parser.parseInline(tokens);
const safeHref = normalizeAiMarkdownLink(href);
if (!safeHref) return label;
const titleAttr = title ? ` title="${escapeHtml(title)}"` : "";
return `<a href="${escapeHtml(safeHref)}"${titleAttr} target="_blank" rel="noopener noreferrer">${label}</a>`;
},
table({ header, rows, align }: Tokens.Table) {
const renderCell = (cell: Tokens.TableCell, tag: "th" | "td", colIndex: number): string => {
const content = this.parser.parseInline(cell.tokens);
const alignAttr = align?.[colIndex] ? ` align="${escapeHtml(align[colIndex]!)}"` : "";
return `<${tag}${alignAttr}>${content}</${tag}>`;
};
const thead = header.length > 0 ? `<thead><tr>${header.map((cell, i) => renderCell(cell, "th", i)).join("")}</tr></thead>` : "";
const tbodyRows = rows
.map((row) => {
const cells = row.map((cell, i) => renderCell(cell, "td", i)).join("");
return `<tr>${cells}</tr>`;
})
.join("");
const tbody = `<tbody>${tbodyRows}</tbody>`;
return `<div class="ai-markdown-table-wrap"><table>${thead}${tbody}</table></div>`;
},
},
});
export function formatAiInlineMarkdown(text: string): string {
try {
return markedInstance.parse(text) as string;
} catch {
return escapeHtml(text);
}
}
export function normalizeAiMarkdownLink(href: string): string | null {
try {
const url = new URL(href);
return EXTERNAL_LINK_PROTOCOLS.has(url.protocol) ? url.toString() : null;
} catch {
return null;
}
}
export function aiMarkdownLinkUrlFromClick(target: unknown, currentTarget: unknown): string | null {
const anchor = closestAnchor(target);
if (!anchor) return null;
if (hasContains(currentTarget) && !currentTarget.contains(anchor)) return null;
const href = anchor.getAttribute("href");
return href ? normalizeAiMarkdownLink(href) : null;
}
export function handleAiMarkdownLinkClick(event: AiMarkdownLinkClickEvent, openUrl: AiMarkdownLinkOpener): boolean {
const url = aiMarkdownLinkUrlFromClick(event.target, event.currentTarget);
if (!url) return false;
event.preventDefault();
event.stopPropagation();
void openUrl(url);
return true;
}
function escapeHtml(value: string): string {
return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
interface AnchorLike {
getAttribute: (name: string) => string | null;
}
function closestAnchor(target: unknown): AnchorLike | null {
const closestSource = hasClosest(target) ? target : parentWithClosest(target);
if (!closestSource) return null;
const anchor = closestSource.closest("a[href]");
return hasGetAttribute(anchor) ? anchor : null;
}
function parentWithClosest(target: unknown): { closest: (selector: string) => unknown } | null {
if (!target || typeof target !== "object" || !("parentElement" in target)) return null;
const parentElement = target.parentElement;
return hasClosest(parentElement) ? parentElement : null;
}
function hasClosest(value: unknown): value is { closest: (selector: string) => unknown } {
return !!value && typeof value === "object" && "closest" in value && typeof value.closest === "function";
}
function hasGetAttribute(value: unknown): value is AnchorLike {
return !!value && typeof value === "object" && "getAttribute" in value && typeof value.getAttribute === "function";
}
function hasContains(value: unknown): value is { contains: (node: unknown) => boolean } {
return !!value && typeof value === "object" && "contains" in value && typeof value.contains === "function";
}
+19
View File
@@ -0,0 +1,19 @@
export interface MessageWithKind {
kind?: string;
}
/**
* Maps a visible message index (contextSummary messages excluded) to the
* actual index in the full messages array.
* Returns -1 if not found.
*/
export function visibleToActualIndex(messages: MessageWithKind[], visibleIndex: number): number {
let vi = 0;
for (let i = 0; i < messages.length; i++) {
if (messages[i].kind !== "contextSummary") {
if (vi === visibleIndex) return i;
vi++;
}
}
return -1;
}
+135
View File
@@ -0,0 +1,135 @@
export interface AiMessageTextSegment {
type: "text";
content: string;
html: string;
}
export interface AiMessageCodeSegment {
type: "code";
content: string;
lang: string;
html: string;
isSql: boolean;
}
export type AiMessageRenderSegment = AiMessageTextSegment | AiMessageCodeSegment;
interface MessageSegment {
type: "text" | "code";
content: string;
lang?: string;
}
export interface AiMessageRendererOptions {
maxEntries?: number;
markdown: (text: string) => string;
highlightCode?: (content: string, lang: string) => string;
}
const DEFAULT_MAX_ENTRIES = 100;
const SQL_LANGUAGES = new Map([
["sql", "SQL"],
["mysql", "MYSQL"],
["postgres", "POSTGRESQL"],
["postgresql", "POSTGRESQL"],
["sqlite", "SQLITE"],
["tsql", "TSQL"],
["clickhouse", "CLICKHOUSE"],
["mongodb", "MONGODB"],
["mongo", "MONGODB"],
]);
const SHELL_LANGUAGES = new Map([
["bash", "BASH"],
["sh", "SHELL"],
["shell", "SHELL"],
["zsh", "ZSH"],
]);
const SQL_LANGUAGE_LABELS = new Set(SQL_LANGUAGES.values());
export function createAiMessageRenderer(options: AiMessageRendererOptions) {
const maxEntries = Math.max(1, Math.floor(options.maxEntries ?? DEFAULT_MAX_ENTRIES));
const cache = new Map<string, AiMessageRenderSegment[]>();
function render(content: string): AiMessageRenderSegment[] {
const cached = cache.get(content);
if (cached) {
cache.delete(content);
cache.set(content, cached);
return cached;
}
const rendered = parseAiMessage(content).map((segment): AiMessageRenderSegment => {
if (segment.type === "text") {
return { type: "text", content: segment.content, html: options.markdown(segment.content) };
}
const lang = normalizeAiCodeLanguage(segment.lang);
return {
type: "code",
content: segment.content,
html: options.highlightCode?.(segment.content, lang) ?? escapeHtml(segment.content),
lang,
isSql: isSqlAiCodeLanguage(lang),
};
});
cache.set(content, rendered);
while (cache.size > maxEntries) {
const oldestKey = cache.keys().next().value;
if (oldestKey === undefined) break;
cache.delete(oldestKey);
}
return rendered;
}
function clear() {
cache.clear();
}
return { render, clear };
}
export function parseAiMessage(text: string): MessageSegment[] {
const segments: MessageSegment[] = [];
const lines = text.split("\n");
let i = 0;
while (i < lines.length) {
const fenceMatch = lines[i].match(/^```([a-zA-Z0-9_+.-]*)\s*$/);
if (fenceMatch) {
const lang = fenceMatch[1] || "sql";
const codeLines: string[] = [];
i++;
while (i < lines.length && !/^```\s*$/.test(lines[i])) {
codeLines.push(lines[i]);
i++;
}
if (i < lines.length) i++;
const content = codeLines.join("\n").trim();
if (content) segments.push({ type: "code", lang, content });
} else {
const textLines: string[] = [];
while (i < lines.length && !/^```([a-zA-Z0-9_+.-]*)\s*$/.test(lines[i])) {
textLines.push(lines[i]);
i++;
}
const content = textLines.join("\n");
if (content.trim()) segments.push({ type: "text", content });
}
}
return segments;
}
export function normalizeAiCodeLanguage(lang?: string): string {
const key = (lang || "sql").trim().toLowerCase();
if (!key) return "SQL";
return SQL_LANGUAGES.get(key) || SHELL_LANGUAGES.get(key) || (key === "json" ? "JSON" : key.toUpperCase());
}
export function isSqlAiCodeLanguage(lang: string): boolean {
return SQL_LANGUAGE_LABELS.has(lang);
}
function escapeHtml(value: string): string {
return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
@@ -0,0 +1,25 @@
export interface AiModelPresentation {
primary: string;
secondary?: string;
}
function compactModelName(value: string): string {
return value
.trim()
.toLowerCase()
.replace(/[\s_-]+/g, "");
}
export function shouldShowAiModelSecondaryLabel(label: string, modelId: string): boolean {
const normalizedLabel = compactModelName(label);
const normalizedId = compactModelName(modelId);
if (!normalizedLabel || !normalizedId || normalizedLabel === normalizedId) return false;
return true;
}
export function formatAiModelOption(label: string, modelId: string): AiModelPresentation {
return {
primary: label || modelId,
secondary: shouldShowAiModelSecondaryLabel(label, modelId) ? modelId : undefined,
};
}
@@ -0,0 +1,17 @@
export interface AiPromptKeydownLikeEvent {
key: string;
shiftKey?: boolean;
isComposing?: boolean;
keyCode?: number;
}
export function isAiPromptImeCompositionEvent(event: AiPromptKeydownLikeEvent, compositionActive = false): boolean {
return compositionActive || !!event.isComposing || event.keyCode === 229 || event.key === "Process";
}
export function shouldSubmitAiPromptOnKeydown(event: AiPromptKeydownLikeEvent, compositionActive = false): boolean {
if (event.key !== "Enter") return false;
if (event.shiftKey) return false;
if (isAiPromptImeCompositionEvent(event, compositionActive)) return false;
return true;
}
+168
View File
@@ -0,0 +1,168 @@
/**
* Pure detectors for recognizing AI assistant action proposals and user
* short replies (affirmative / negative). Used by the chat UI to render
* a quick action confirmation bar instead of requiring the user to type.
*
* Detectors are intentionally narrow:
* - A "proposal" requires both a first-person/asking phrase AND an
* actionable intent verb (execute query, fetch data, investigate, etc.)
* - Affirmative / negative detectors only match short replies (the user
* typing a couple of words). Long replies fall through.
*
* Side-effect free. Safe to import from anywhere.
*/
/** Trim whitespace, leading/trailing punctuation (CJK + ASCII) for short-reply matching. */
function stripOuterPunctuation(input: string): string {
return input
.replace(/^[\s ]+/, "")
.replace(/[\s ]+$/, "")
.replace(/^[!?.,;:!?。,;:]+/, "")
.replace(/[!?.,;:!?。,;:]+$/, "");
}
/** Returns the last non-empty line/sentence-ish chunk of the assistant message. */
function lastNonEmptyLine(content: string): string {
const lines = content.split(/\r?\n/);
for (let i = lines.length - 1; i >= 0; i--) {
const trimmed = lines[i].trim();
if (trimmed) return trimmed;
}
return "";
}
/** True when the string contains at least one CJK ideograph. */
export function containsChinese(input: string): boolean {
return /[一-鿿]/.test(input);
}
// Phrases that indicate the assistant is asking permission to take an action.
const ZH_ASK_PHRASES = [
/需要我/, // "do you need me to"
/要不要我/, // "shall I"
/是否需要/, // "is it needed"
/帮我?(?:你)?/, // "shall I help" (loose)
/我来/, // "let me"
/我帮你/, // "let me help you"
/我现在/, // "shall I now"
/我可以/, // "may I"
/我去/, // "shall I go"
/我能/, // "may I"
];
const EN_ASK_PHRASES = [/\bshould\s+i\b/i, /\bdo\s+you\s+want\s+me\s+to\b/i, /\bwould\s+you\s+like\s+me\s+to\b/i, /\bwant\s+me\s+to\b/i, /\bshall\s+i\b/i, /\bcan\s+i\b/i, /\blet\s+me\s+know\s+if\s+you\s+want\s+me\s+to\b/i];
// Actionable intent verbs/phrases. Must co-occur with an ask phrase to count.
const ZH_ACTION_PHRASES = [
/执行/, // execute
/运行/, // run
/查询/, // query
/查看/, // view
/看看/,
/查一下/, // check
/拉取/, // fetch
/获取/, // get/fetch
/读取/, // read
/取出?/, // take out / extract
/取数据/,
/看看数据/,
/看一下/,
/分析/, // analyze
/统计/, // count/aggregate
/排查/, // investigate
/调查/, // investigate
/生成/, // generate
/创建/, // create
/列出/, // list
/对比/, // compare
];
const EN_ACTION_PHRASES = [
/\bexecute\b/i,
/\brun\b/i,
/\bquery\b/i,
/\bfetch\b/i,
/\bpull\b/i,
/\bretrieve\b/i,
/\bread\b/i,
/\bget\s+(?:the\s+)?(?:data|rows|sample|columns|results)\b/i,
/\banalyze\b/i,
/\binvestigate\b/i,
/\bcheck\b/i,
/\binspect\b/i,
/\bgenerate\b/i,
/\bcreate\b/i,
/\blist\b/i,
/\bcompare\b/i,
/\bcount\b/i,
/\bsample\b/i,
];
/**
* Detect whether the assistant message ends with a proposal-style question
* such as "Should I execute this query?" / "需要我拉取这两个表的数据吗?".
*
* Heuristic:
* - Looks at the last non-empty line.
* - Must end with a question mark (Chinese ? or English ?).
* - Must contain BOTH a first-person ask phrase AND an actionable intent.
*
* Returns false for generic clarifying questions (no actionable verb).
*/
export function looksLikeActionProposal(content: string): boolean {
if (!content) return false;
const lastLine = lastNonEmptyLine(content);
if (!lastLine) return false;
// Must be a question.
if (!/[??]\s*$/.test(lastLine)) return false;
const isZh = containsChinese(lastLine);
const askPhrases = isZh ? ZH_ASK_PHRASES : EN_ASK_PHRASES;
const actionPhrases = isZh ? ZH_ACTION_PHRASES : EN_ACTION_PHRASES;
const hasAsk = askPhrases.some((re) => re.test(lastLine));
if (!hasAsk) return false;
const hasAction = actionPhrases.some((re) => re.test(lastLine));
return hasAction;
}
// Short affirmative words/phrases. Must match (after stripping punctuation /
// whitespace) the entire reply for it to count — long replies fall through.
const ZH_AFFIRMATIVE = [/^需要$/, /^需要的$/, /^要$/, /^要的$/, /^好$/, /^好的$/, /^可以$/, /^行$/, /^是$/, /^是的$/, /^对$/, /^对的$/, /^嗯$/, /^嗯嗯$/, /^OK$/i, /^OKK*$/i, /^没问题$/, /^请$/, /^麻烦了$/, /^来吧$/, /^继续$/];
const EN_AFFIRMATIVE = [/^yes$/i, /^yeah$/i, /^yep$/i, /^y$/i, /^ok$/i, /^okay$/i, /^k$/i, /^sure$/i, /^go$/i, /^go\s+ahead$/i, /^do\s+it$/i, /^please\s+do$/i, /^please$/i, /^proceed$/i, /^continue$/i, /^confirm(?:ed)?$/i];
const ZH_NEGATIVE = [/^不$/, /^不用$/, /^不用了$/, /^不需要$/, /^不要$/, /^别$/, /^先不$/, /^先不(?:用|要)$/, /^算了$/, /^不必$/, /^取消$/, /^停$/, /^先别$/];
const EN_NEGATIVE = [/^no$/i, /^nope$/i, /^nah$/i, /^n$/i, /^don'?t$/i, /^do\s+not$/i, /^not\s+needed$/i, /^skip$/i, /^cancel$/i, /^stop$/i, /^never\s*mind$/i, /^nvm$/i, /^hold\s+off$/i, /^not\s+now$/i];
/**
* Detect "short affirmative" user replies like 需要 / 好 / 可以 / 是 / 对 /
* 嗯 / yes / ok / sure / go ahead / do it.
*
* Long messages (multiple sentences, or words mixed with extra context)
* intentionally do NOT match — those should be sent to the LLM normally.
*/
export function isShortAffirmative(content: string): boolean {
const cleaned = stripOuterPunctuation(content);
if (!cleaned) return false;
// Reject when the reply has multiple words/lines unless still very short
// and matches a known phrase (e.g. "go ahead" / "do it" / "好的").
if (cleaned.length > 24) return false;
const all = [...ZH_AFFIRMATIVE, ...EN_AFFIRMATIVE];
return all.some((re) => re.test(cleaned));
}
/**
* Detect "short negative" user replies like 不用 / 不需要 / 不要 / no /
* nope / don't / not needed.
*/
export function isShortNegative(content: string): boolean {
const cleaned = stripOuterPunctuation(content);
if (!cleaned) return false;
if (cleaned.length > 24) return false;
const all = [...ZH_NEGATIVE, ...EN_NEGATIVE];
return all.some((re) => re.test(cleaned));
}
+166
View File
@@ -0,0 +1,166 @@
import type { AiAction } from "@/lib/ai/ai";
export type AiSkillRiskPolicy = "readonly" | "readonly_preferred" | "confirmed_write" | "sample_write";
export type AiSkillContextNeed = "currentSql" | "schema" | "indexes" | "foreignKeys" | "lastError" | "lastResultPreview" | "databaseDialect";
export interface LocalizedAiSkillText {
en: string;
zh: string;
}
export interface LocalizedAiSkillLines {
en: string[];
zh: string[];
}
export interface AiSkillDefinition {
id: string;
action: AiAction;
title: LocalizedAiSkillText;
riskPolicy: AiSkillRiskPolicy;
contextNeeds: AiSkillContextNeed[];
userInstruction: LocalizedAiSkillText;
systemRules: LocalizedAiSkillLines;
outputContract: LocalizedAiSkillLines;
}
export const AI_SKILL_DEFINITIONS: AiSkillDefinition[] = [
{
id: "generate_sql",
action: "generate",
title: {
en: "Generate SQL",
zh: "生成 SQL",
},
riskPolicy: "readonly_preferred",
contextNeeds: ["schema", "indexes", "foreignKeys", "databaseDialect"],
userInstruction: {
en: "Generate a SQL query that satisfies the user's request. Return the SQL in a ```sql code block first, followed by a brief note if needed. Use foreign key relationships from the schema to infer correct JOIN conditions.",
zh: "根据用户请求生成 SQL。先在 ```sql 代码块中返回 SQL,必要时附简短说明。利用 Schema 中的外键关系推断正确的 JOIN 条件。",
},
systemRules: {
en: ["Use foreign key relationships to infer JOIN conditions. Return the SQL first and avoid long explanations."],
zh: ["利用外键关系推断 JOIN 条件。生成操作优先返回 SQL,避免长篇解释。"],
},
outputContract: {
en: ["Output format: put only the final recommended SQL in the first ```sql code block; add at most 3 practical notes after it. If required information is missing, ask one clarifying question first."],
zh: ["输出格式:第一个 ```sql 代码块只放最终推荐 SQL;SQL 后最多 3 条实用说明。信息不足时先提出一个澄清问题。"],
},
},
{
id: "explain_sql",
action: "explain",
title: {
en: "Explain SQL",
zh: "解释 SQL",
},
riskPolicy: "readonly",
contextNeeds: ["currentSql", "schema", "indexes", "foreignKeys", "lastResultPreview"],
userInstruction: {
en: "Explain the current SQL step by step. Point out risky operations, implicit assumptions, and potential performance issues. Reference index and foreign key info from the schema when relevant.",
zh: "逐步解释当前 SQL。指出危险操作、隐含假设和潜在性能问题。结合 Schema 中的索引和外键信息分析。",
},
systemRules: {
en: ["Explain what the SQL does without changing it. Reference schema, indexes, foreign keys, result preview, and risky assumptions when relevant."],
zh: ["解释当前 SQL 的作用,不要改写 SQL。必要时结合 Schema、索引、外键、结果预览和风险假设说明。"],
},
outputContract: {
en: ["Output format: summarize the SQL purpose first, then explain execution logic, risks, and performance notes step by step."],
zh: ["输出格式:先概括 SQL 目的,再按步骤解释执行逻辑、风险点和性能注意事项。"],
},
},
{
id: "optimize_sql",
action: "optimize",
title: {
en: "Optimize SQL",
zh: "优化 SQL",
},
riskPolicy: "readonly",
contextNeeds: ["currentSql", "schema", "indexes", "foreignKeys"],
userInstruction: {
en: "Rewrite or suggest improvements for the current SQL. Return the improved SQL in a ```sql code block first, followed by short notes explaining the changes. Use the index information in the schema to suggest index-aware optimizations (e.g., avoid full table scans, leverage existing indexes).",
zh: "重写或优化当前 SQL。先在 ```sql 代码块中返回优化后的 SQL,然后简要说明改动。利用 Schema 中的索引信息建议索引友好的优化(如避免全表扫描、利用现有索引)。",
},
systemRules: {
en: ["Use the index information in the schema to suggest optimizations. Point out which conditions hit indexes and which cause full table scans."],
zh: ["利用 Schema 中的索引信息建议优化。指出哪些查询条件可以命中索引、哪些会导致全表扫描。"],
},
outputContract: {
en: ["Output format: provide the optimized SQL first, then explain the key changes in at most 3 notes."],
zh: ["输出格式:先给优化后的 SQL,再用最多 3 条说明解释关键改动。"],
},
},
{
id: "fix_sql",
action: "fix",
title: {
en: "Fix SQL",
zh: "修复 SQL",
},
riskPolicy: "readonly_preferred",
contextNeeds: ["currentSql", "schema", "lastError", "lastResultPreview", "databaseDialect"],
userInstruction: {
en: "Fix the current SQL using the provided error message and result context. Return the corrected SQL in a ```sql code block first, followed by a brief explanation of the root cause.",
zh: "根据报错信息和结果上下文修复当前 SQL。先在 ```sql 代码块中返回修正后的 SQL,再简要说明根因。",
},
systemRules: {
en: ["Carefully analyze the error message to identify the root cause. Return the corrected SQL first, then briefly explain."],
zh: ["仔细分析错误信息,定位根因。先返回修正后的 SQL,再简要解释。"],
},
outputContract: {
en: ["Output format: corrected SQL, error cause, change notes."],
zh: ["输出格式:修复后的 SQL、错误原因、改动说明。"],
},
},
{
id: "convert_sql",
action: "convert",
title: {
en: "Convert SQL Dialect",
zh: "转换 SQL 方言",
},
riskPolicy: "readonly_preferred",
contextNeeds: ["currentSql", "schema", "databaseDialect"],
userInstruction: {
en: "Convert the current SQL to the target dialect requested by the user. Return the converted SQL in a ```sql code block first. Note any syntax differences or incompatibilities.",
zh: "将当前 SQL 转换为用户指定的目标方言。先在 ```sql 代码块中返回转换后的 SQL,再说明语法差异。",
},
systemRules: {
en: ["Convert only to the target dialect requested by the user. Preserve the query intent and call out syntax that cannot be converted safely."],
zh: ["只转换到用户指定的目标方言。保持查询意图,并指出无法安全转换的语法。"],
},
outputContract: {
en: ["Output format: provide the converted SQL first, then note important target-dialect syntax differences or incompatibilities."],
zh: ["输出格式:先给转换后的 SQL,再说明目标方言下的重要语法差异或不兼容点。"],
},
},
{
id: "sample_data",
action: "sampleData",
title: {
en: "Generate Sample Data",
zh: "生成样例数据",
},
riskPolicy: "sample_write",
contextNeeds: ["schema", "databaseDialect"],
userInstruction: {
en: "Generate safe sample INSERT statements or mock data for the current schema. Do not use real production data. Return SQL in a ```sql code block.",
zh: "为当前 Schema 生成安全的示例 INSERT 语句或模拟数据。不使用真实生产数据。在 ```sql 代码块中返回 SQL。",
},
systemRules: {
en: ["Generate mock data only. Do not use or imply real production data, credentials, personal data, or secrets."],
zh: ["只生成模拟数据。不要使用或暗示真实生产数据、凭据、个人数据或密钥。"],
},
outputContract: {
en: ["Output format: provide safe sample SQL first, then explain which values are mock data."],
zh: ["输出格式:先给安全的示例 SQL,再说明哪些值是模拟数据。"],
},
},
];
export function aiSkillForAction(action: AiAction): AiSkillDefinition {
const skill = AI_SKILL_DEFINITIONS.find((item) => item.action === action);
if (!skill) throw new Error(`Missing AI skill definition for action: ${action}`);
return skill;
}
@@ -0,0 +1,127 @@
import type { ConnectionConfig } from "@/types/database";
export type ConnectionEnvironment = "production" | "non_production" | "unknown";
export type AiSqlExecutionAction = "auto_execute" | "confirm" | "block";
export type AiSqlExecutionCategory = "read" | "low_risk_write" | "write" | "schema_change" | "dangerous" | "unknown";
export interface AiSqlExecutionDecision {
action: AiSqlExecutionAction;
environment: ConnectionEnvironment;
category: AiSqlExecutionCategory;
reasons: string[];
}
const READ_RE = /^(SELECT|WITH|SHOW|DESCRIBE|DESC|EXPLAIN)\b/i;
const INSERT_RE = /^INSERT\b/i;
const UPDATE_RE = /^UPDATE\b/i;
const DELETE_RE = /^DELETE\b/i;
const CONFIRM_WRITE_RE = /^(MERGE|REPLACE)\b/i;
const BLOCK_RE = /^(DROP|TRUNCATE|ALTER|RENAME)\b/i;
const SCHEMA_RE = /^(CREATE)\b/i;
const PRODUCTION_RE = /\b(prod|prd|production)\b|生产|正式/i;
const NON_PRODUCTION_RE = /\b(local|localhost|dev|develop|development|test|testing|stage|staging|sandbox|demo)\b|本地|开发|测试|预发/i;
const LOCAL_HOST_RE = /^(localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|::1)$/i;
const NEGATIVE_EXECUTION_RE = /(不要|别|不用|禁止|只生成|仅生成|只写|仅写).{0,12}(执行|运行|跑)|do\s+not\s+execute|don't\s+execute|dont\s+execute|without\s+executing|only\s+(generate|write|return)/i;
export function stripAiSqlComments(sql: string): string {
return sql
.replace(/\/\*[\s\S]*?\*\//g, " ")
.replace(/--.*$/gm, " ")
.replace(/#.*$/gm, " ");
}
function sqlStatements(sql: string): string[] {
return stripAiSqlComments(sql)
.split(";")
.map((stmt) => stmt.trim())
.filter(Boolean);
}
function classifyStatement(statement: string): AiSqlExecutionCategory {
if (READ_RE.test(statement)) return "read";
if (BLOCK_RE.test(statement)) return "dangerous";
if (SCHEMA_RE.test(statement)) return "schema_change";
if (INSERT_RE.test(statement)) return "low_risk_write";
if (UPDATE_RE.test(statement)) return isScopedUpdate(statement) ? "low_risk_write" : "dangerous";
if (DELETE_RE.test(statement) || CONFIRM_WRITE_RE.test(statement)) return "write";
return "unknown";
}
function isScopedUpdate(statement: string): boolean {
const whereMatch = statement.match(/\bWHERE\b([\s\S]*)$/i);
if (!whereMatch) return false;
const where = whereMatch[1];
if (/\b1\s*=\s*1\b|\btrue\b/i.test(where)) return false;
return /\b[\w"`.[\]]*(?:id|_id|uuid|key)[\w"`.[\]]*\s*=\s*(?:'[^']+'|"[^"]+"|`[^`]+`|[\w.-]+)/i.test(where);
}
export function classifyConnectionEnvironment(connection?: ConnectionConfig): ConnectionEnvironment {
if (!connection) return "unknown";
const parts = [connection.name, connection.host, connection.database, connection.connection_string].filter(Boolean);
const signal = parts.join(" ");
if (PRODUCTION_RE.test(signal)) return "production";
if (LOCAL_HOST_RE.test(connection.host) || NON_PRODUCTION_RE.test(signal)) return "non_production";
return "unknown";
}
export function classifyAiSqlExecution(sql: string, connection?: ConnectionConfig): AiSqlExecutionDecision {
const environment = classifyConnectionEnvironment(connection);
const statements = sqlStatements(sql);
const reasons: string[] = [];
if (!statements.length) {
return { action: "block", environment, category: "unknown", reasons: ["empty_sql"] };
}
const categories = statements.map(classifyStatement);
const hasMultipleStatements = statements.length > 1;
if (hasMultipleStatements) reasons.push("multi_statement");
if (categories.includes("dangerous")) {
return { action: "block", environment, category: "dangerous", reasons };
}
if (categories.includes("unknown")) {
return { action: "confirm", environment, category: "unknown", reasons };
}
if (categories.every((category) => category === "read")) {
return { action: "auto_execute", environment, category: "read", reasons };
}
if (hasMultipleStatements) {
return { action: "confirm", environment, category: "write", reasons };
}
const [category] = categories;
if (category === "low_risk_write") {
return {
action: environment === "non_production" ? "auto_execute" : "confirm",
environment,
category,
reasons,
};
}
return {
action: "confirm",
environment,
category,
reasons,
};
}
export function shouldAttemptAiAutoExecute(instruction: string, action: string): boolean {
if (action !== "generate") return false;
const normalized = instruction.trim();
if (!normalized || NEGATIVE_EXECUTION_RE.test(normalized)) return false;
return true;
}
export function extractFirstSqlCodeBlock(content: string): string | undefined {
const match = content.match(/```(?:sql|mysql|postgresql|sqlite|tsql|clickhouse)?\s*\n([\s\S]*?)```/i);
const sql = match?.[1]?.trim();
return sql || undefined;
}
+111
View File
@@ -0,0 +1,111 @@
export interface AiTableMention {
raw: string;
schema?: string;
table: string;
}
export const AI_TABLE_MENTION_SCHEMA_LIMIT = 8;
export const AI_TABLE_MENTION_CANDIDATE_LIMIT = 200;
const SIMPLE_IDENTIFIER_RE = /^[\p{L}_][\p{L}\p{N}_$]*$/u;
function isMentionBoundary(char: string | undefined): boolean {
return !char || /\s|[([{,;:]/.test(char);
}
function isUnquotedMentionChar(char: string): boolean {
return /[\p{L}\p{N}_$.-]/u.test(char);
}
function readQuotedSegment(source: string, start: number): { value: string; end: number } | null {
const quote = source[start];
if (quote !== '"' && quote !== "`") return null;
let value = "";
for (let i = start + 1; i < source.length; i++) {
const char = source[i];
if (char === quote) {
if (source[i + 1] === quote) {
value += quote;
i++;
continue;
}
return { value, end: i + 1 };
}
value += char;
}
return null;
}
function readMentionToken(source: string, start: number): { raw: string; parts: string[]; end: number } | null {
let i = start;
const parts: string[] = [];
let raw = "";
while (i < source.length) {
const quoted = readQuotedSegment(source, i);
if (quoted) {
parts.push(quoted.value);
raw += source.slice(i, quoted.end);
i = quoted.end;
} else {
let value = "";
const valueStart = i;
while (i < source.length && isUnquotedMentionChar(source[i]) && source[i] !== ".") {
value += source[i];
i++;
}
if (!value) break;
parts.push(value);
raw += source.slice(valueStart, i);
}
if (source[i] !== ".") break;
raw += ".";
i++;
}
const usableParts = parts.filter(Boolean);
if (!usableParts.length) return null;
return { raw, parts: usableParts, end: i };
}
export function parseAiTableMentions(text: string): AiTableMention[] {
const mentions: AiTableMention[] = [];
const seen = new Set<string>();
for (let i = 0; i < text.length; i++) {
if (text[i] !== "@" || !isMentionBoundary(text[i - 1])) continue;
const token = readMentionToken(text, i + 1);
if (!token) continue;
const table = token.parts[token.parts.length - 1];
const schema = token.parts.length > 1 ? token.parts[token.parts.length - 2] : undefined;
const key = `${schema || ""}.${table}`.toLowerCase();
if (!seen.has(key)) {
seen.add(key);
mentions.push({ raw: `@${token.raw}`, schema, table });
}
i = token.end - 1;
}
return mentions;
}
export function formatAiTableMention(schema: string | undefined, table: string): string {
const parts = [schema, table].filter((part): part is string => !!part);
return `@${parts.map(formatMentionPart).join(".")}`;
}
function formatMentionPart(part: string): string {
if (SIMPLE_IDENTIFIER_RE.test(part)) return part;
return `"${part.replace(/"/g, '""')}"`;
}
export function aiTableMentionKey(schema: string | undefined, table: string): string {
return `${schema || ""}.${table}`.toLowerCase();
}
export function filterAiTableMentionCandidates<T extends { name: string }>(candidates: T[], tableFilter: string, limit = AI_TABLE_MENTION_CANDIDATE_LIMIT): T[] {
const normalizedFilter = tableFilter.toLowerCase();
return candidates.filter((candidate) => !normalizedFilter || candidate.name.toLowerCase().includes(normalizedFilter)).slice(0, limit);
}