-
Notifications
You must be signed in to change notification settings - Fork 213
First version of filters #1250
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
First version of filters #1250
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,27 +1,34 @@ | ||
| import { sqlIncludesFilterTemplate, stripSqlFilterBlocks, validateSqlFilterTemplate } from '@nao/shared/sql-template'; | ||
| import type { executeSql } from '@nao/shared/tools'; | ||
| import { executeSql as schemas } from '@nao/shared/tools'; | ||
|
|
||
| import { ExecuteSqlOutput, renderToModelOutput } from '../../components/tool-outputs'; | ||
| import { env } from '../../env'; | ||
| import { getExecuteSqlPartByQueryIdInChat, updateExecuteSqlPart } from '../../queries/execute-sql.queries'; | ||
| import { ToolContext } from '../../types/tools'; | ||
| import { detectQueryRowLimit, isReadOnlySqlQuery } from '../../utils/sql-filter'; | ||
| import { createTool } from '../../utils/tools'; | ||
| import { queryAppDb } from './query-app-db'; | ||
|
|
||
| export async function executeQuery( | ||
| { sql_query, database_id }: executeSql.Input, | ||
| { sql_query, database_id, query_id }: executeSql.Input, | ||
| context: ToolContext, | ||
| ): Promise<executeSql.Output> { | ||
| const templateWarnings = env.BETA_STORY_FILTERS_ENABLED ? validateSqlFilterTemplate(sql_query) : []; | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
|
||
| const effectiveSql = stripSqlFilterBlocks(sql_query); | ||
| if (templateWarnings.length > 0 && sqlIncludesFilterTemplate(effectiveSql)) { | ||
| throw new Error(`Invalid story filter SQL template: ${templateWarnings.join(' ')}`); | ||
| } | ||
| const writePermEnabled = context.agentSettings?.sql?.dangerouslyWritePermEnabled ?? false; | ||
| if (!writePermEnabled && !(await isReadOnlySqlQuery(sql_query))) { | ||
| if (!writePermEnabled && !(await isReadOnlySqlQuery(effectiveSql))) { | ||
| throw new Error( | ||
| 'Write SQL operations are disabled. Only SELECT queries are allowed. ' + | ||
| 'Enable "Dangerous write permissions" in the admin panel to allow INSERT, UPDATE, DELETE and DDL queries.', | ||
| ); | ||
| } | ||
|
|
||
| if (context.adminMode) { | ||
| return executeAppDbQuery(sql_query, context); | ||
| return withTemplateWarnings(await executeAppDbQuery(effectiveSql, context, query_id), templateWarnings); | ||
| } | ||
|
|
||
| const naoProjectFolder = context.projectFolder; | ||
|
|
@@ -32,7 +39,7 @@ export async function executeQuery( | |
| 'Content-Type': 'application/json', | ||
| }, | ||
| body: JSON.stringify({ | ||
| sql: sql_query, | ||
| sql: effectiveSql, | ||
| nao_project_folder: naoProjectFolder, | ||
| ...(database_id && { database_id }), | ||
| ...(Object.keys(envVars).length > 0 && { env_vars: envVars }), | ||
|
|
@@ -46,23 +53,30 @@ export async function executeQuery( | |
| } | ||
|
|
||
| const data = await response.json(); | ||
| const id = `query_${crypto.randomUUID().slice(0, 8)}` as const; | ||
| const id = query_id ?? (`query_${crypto.randomUUID().slice(0, 8)}` as const); | ||
|
|
||
| context.queryResults.set(id, { columns: data.columns, data: data.data }); | ||
|
|
||
| const appliedLimit = detectQueryRowLimit(sql_query); | ||
| const appliedLimit = detectQueryRowLimit(effectiveSql); | ||
|
|
||
| return { | ||
| _version: '1', | ||
| ...data, | ||
| id, | ||
| ...(appliedLimit !== null && { applied_limit: appliedLimit }), | ||
| }; | ||
| return withTemplateWarnings( | ||
| { | ||
| _version: '1', | ||
| ...data, | ||
| id, | ||
| ...(appliedLimit !== null && { applied_limit: appliedLimit }), | ||
| }, | ||
| templateWarnings, | ||
| ); | ||
| } | ||
|
|
||
| async function executeAppDbQuery(sqlQuery: string, context: ToolContext): Promise<executeSql.Output> { | ||
| async function executeAppDbQuery( | ||
| sqlQuery: string, | ||
| context: ToolContext, | ||
| queryId?: `query_${string}`, | ||
| ): Promise<executeSql.Output> { | ||
| const { columns, rows } = await queryAppDb(context.projectId, sqlQuery); | ||
| const id = `query_${crypto.randomUUID().slice(0, 8)}` as const; | ||
| const id = queryId ?? (`query_${crypto.randomUUID().slice(0, 8)}` as const); | ||
| context.queryResults.set(id, { columns, data: rows }); | ||
| const appliedLimit = detectQueryRowLimit(sqlQuery); | ||
| return { | ||
|
|
@@ -75,11 +89,60 @@ async function executeAppDbQuery(sqlQuery: string, context: ToolContext): Promis | |
| }; | ||
| } | ||
|
|
||
| export default createTool<executeSql.Input, executeSql.Output>({ | ||
| description: | ||
| function withTemplateWarnings(output: executeSql.Output, templateWarnings: string[]): executeSql.Output { | ||
| if (templateWarnings.length === 0) { | ||
| return output; | ||
| } | ||
| return { ...output, template_warnings: templateWarnings }; | ||
| } | ||
|
|
||
| async function updateExistingQuery( | ||
| input: executeSql.Input & { query_id: `query_${string}` }, | ||
| context: ToolContext, | ||
| ): Promise<executeSql.Output> { | ||
| const existing = await getExecuteSqlPartByQueryIdInChat(context.chatId, input.query_id); | ||
| if (!existing) { | ||
| throw new Error( | ||
| `Query ${input.query_id} not found in this chat. Use execute_sql without query_id to create a new query.`, | ||
| ); | ||
| } | ||
|
|
||
| const nextInput: executeSql.Input = { | ||
| sql_query: input.sql_query, | ||
| database_id: input.database_id ?? existing.toolInput.database_id, | ||
| name: input.name ?? existing.toolInput.name, | ||
| }; | ||
|
|
||
| const output = await executeQuery({ ...nextInput, query_id: input.query_id }, context); | ||
| await updateExecuteSqlPart(existing.toolCallId, nextInput, output); | ||
| return output; | ||
| } | ||
|
|
||
| function buildExecuteSqlToolDescription() { | ||
| return [ | ||
| 'Execute a SQL query against the connected database and return the results. If multiple databases are configured, specify the database_id.', | ||
| ...(env.BETA_STORY_FILTERS_ENABLED | ||
| ? [ | ||
| 'Story filters may be embedded as SQL template blocks that are stripped when this tool runs in chat.', | ||
| 'Correct syntax: WHERE 1 = 1 {% filter country %} AND country IN ({{ filters.country.sql }}) {% endfilter %}.', | ||
| "For date_range filters, {{ filters.<id>.sql }} already expands to 'start' AND 'end', so write: {% filter period %} AND order_date BETWEEN {{ filters.period.sql }} {% endfilter %}.", | ||
| 'Never use filters.<id>.start, .end, .value, or placeholders outside {% filter %} blocks — placeholders outside blocks are rejected; other invalid templates return template_warnings.', | ||
| 'Prefer query_id when adding story filter templates so existing <chart>/<table> tags keep working.', | ||
| ] | ||
| : []), | ||
| 'To edit a previous query in-place (keep the same query_id for charts/stories), pass query_id from an earlier execute_sql result.', | ||
| ].join(' '); | ||
| } | ||
|
|
||
| export default createTool<executeSql.Input, executeSql.Output>({ | ||
| description: buildExecuteSqlToolDescription(), | ||
| inputSchema: schemas.InputSchema, | ||
| outputSchema: schemas.OutputSchema, | ||
| execute: executeQuery, | ||
| execute: async (input, context) => { | ||
| if (input.query_id) { | ||
| return updateExistingQuery({ ...input, query_id: input.query_id }, context); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: Editing a query creates a second persisted Prompt for AI agents |
||
| } | ||
| return executeQuery(input, context); | ||
| }, | ||
| toModelOutput: ({ output }) => renderToModelOutput(ExecuteSqlOutput({ output }), output), | ||
| }); | ||
Uh oh!
There was an error while loading. Please reload this page.