The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix(ai): assistant sql row cap (#51608)
Anthony Lioc3fd259904b3
diff --git a/apps/studio/components/ui/AlertError.test.tsx b/apps/studio/components/ui/AlertError.test.tsxindex f3349f47f77..9c56b849890 100644--- a/apps/studio/components/ui/AlertError.test.tsx+++ b/apps/studio/components/ui/AlertError.test.tsx@@ -65,3 +65,12 @@ test.each([false, true])(expect(screen.queryByRole('link', { name: /contact support/i })).not.toBeInTheDocument()})++test('support continues the error message inline when instructions are hidden', () => {+ customRender(+ <AlertError showInstructions={false} showErrorPrefix={false} error={{ message: 'oh no' }} />+ )+ const link = screen.getByRole('link', { name: 'contact support' })+ expect(link.closest('p')).toHaveTextContent('oh no. If the issue persists, contact support.')+ expect(screen.queryByRole('link', { name: 'Contact support' })).not.toBeInTheDocument()+})diff --git a/apps/studio/components/ui/AlertError.tsx b/apps/studio/components/ui/AlertError.tsxindex 61a312d2e6b..e7f1ef451dc 100644--- a/apps/studio/components/ui/AlertError.tsx+++ b/apps/studio/components/ui/AlertError.tsx@@ -52,6 +52,8 @@ export const AlertError = ({const hasInlineSupportLink =showInstructions && !hideContactSupport && SUPPORT_PHRASE_REGEX.test(description)const canShowSupportFallback = !hideContactSupport && !hasInlineSupportLink+ // Without instructions there's no sentence to link, so the fallback continues the message+ const isSupportFallbackInline = canShowSupportFallback && !showInstructions && !!error?.messageconst renderSupportLink = (text: string, key?: number) => (<SupportLink@@ -100,6 +102,12 @@ export const AlertError = ({<p>{showErrorPrefix && 'Error: '}{formattedErrorMessage}+ {isSupportFallbackInline && (+ <>+ {/[.!?]$/.test(formattedErrorMessage ?? '') ? ' ' : '. '}+ If the issue persists, {renderSupportLink('contact support')}.+ </>+ )}</p>)}{showInstructions && (@@ -107,7 +115,9 @@ export const AlertError = ({{hasInlineSupportLink ? renderDescriptionWithSupportLink(description) : description}</p>)}- {canShowSupportFallback && <p>{renderSupportLink('Contact support')}</p>}+ {canShowSupportFallback && !isSupportFallbackInline && (+ <p>{renderSupportLink('Contact support')}</p>+ )}{children}</>}diff --git a/apps/studio/data/sql/__tests__/utils.test.ts b/apps/studio/data/sql/__tests__/utils.test.tsindex 2a7e0714cf8..b74389effdb 100644--- a/apps/studio/data/sql/__tests__/utils.test.ts+++ b/apps/studio/data/sql/__tests__/utils.test.ts@@ -172,6 +172,12 @@ describe('applyAutoLimit', () => {const { appendAutoLimit } = applyAutoLimit(sql, limit)expect(appendAutoLimit).toBe(false)})+ test('Should return false if query uses `FETCH NEXT` instead of limit ', () => {+ const sql = safeSql`select * from countries offset 5 rows FETCH NEXT 5 rows only`+ const { sql: result, appendAutoLimit } = applyAutoLimit(sql, 100)+ expect(appendAutoLimit).toBe(false)+ expect(result).toBe(sql)+ })test('Should return false if query is not a select statement', () => {const sql = safeSql`create table test (id int8 primary key, name varchar);`const limit = 100diff --git a/apps/studio/data/sql/utils.ts b/apps/studio/data/sql/utils.tsindex 1f23256fd1c..541e59b8561 100644--- a/apps/studio/data/sql/utils.ts+++ b/apps/studio/data/sql/utils.ts@@ -65,7 +65,7 @@ export function applyAutoLimit(!hasComments &&!hasMultipleQueries &&cleanedSql.toLowerCase().startsWith('select') &&- !cleanedSql.toLowerCase().match(/fetch\s+first/i) &&+ !cleanedSql.toLowerCase().match(/fetch\s+(first|next)/i) &&!cleanedSql.match(/limit$/i) &&!cleanedSql.match(/limit;$/i) &&!cleanedSql.match(/limit [0-9]* offset [0-9]*\s*[;]?$/i) &&diff --git a/apps/studio/lib/ai/assistant-context.test.ts b/apps/studio/lib/ai/assistant-context.test.tsindex 8cba4064280..03f6185c9ce 100644--- a/apps/studio/lib/ai/assistant-context.test.ts+++ b/apps/studio/lib/ai/assistant-context.test.ts@@ -30,6 +30,17 @@ describe('buildAssistantContextMessages', () => {expect(messages).toEqual([])})+ it('tells the model the current opt-in level so it does not ask for access it has', () => {+ const messages = buildAssistantContextMessages({+ schemasString: NO_SCHEMA_ACCESS_MESSAGE,+ aiOptInLevel: 'schema_and_log_and_data',+ })++ expect(messages).toHaveLength(1)+ expect(messages[0].content).toContain('schema_and_log_and_data')+ expect(messages[0].content).toContain('update_opt_in_level')+ })+it('adds the support instructions in support mode', () => {const messages = buildAssistantContextMessages({schemasString: NO_SCHEMA_ACCESS_MESSAGE,diff --git a/apps/studio/lib/ai/assistant-context.ts b/apps/studio/lib/ai/assistant-context.tsindex b34a2499a8e..5d574a65d14 100644--- a/apps/studio/lib/ai/assistant-context.ts+++ b/apps/studio/lib/ai/assistant-context.ts@@ -1,3 +1,4 @@+import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'import {buildClickhouseLogsSchemaSection,CLICKHOUSE_LOGS_COMPLETION_INSTRUCTIONS,@@ -45,6 +46,7 @@ export function buildAssistantContextMessages({schemasString,supportMode,includesLogsSnippets,+ aiOptInLevel,now = new Date(),}: {projectRef?: string@@ -53,6 +55,8 @@ export function buildAssistantContextMessages({supportMode?: boolean/** Whether any user message in the conversation attached a logs (ClickHouse) query. */includesLogsSnippets?: boolean+ /** The organization's current opt-in level, so the model doesn't ask for access it already has. */+ aiOptInLevel?: AiOptInLevel/** Injected so tests can pin the clock. Lives here, not the system prompt, so Bedrock can cache the system prompt. */now?: Date}): AssistantContextMessage[] {@@ -66,6 +70,13 @@ export function buildAssistantContextMessages({})}+ if (aiOptInLevel) {+ messages.push({+ role: 'assistant',+ content: `The organization's AI opt-in level is ${aiOptInLevel}. Only call update_opt_in_level when the user asks to review or change it, or when a tool you need requires a higher level than this. Never call it for access the organization already has.`,+ })+ }+if (supportMode) {messages.push({role: 'assistant',diff --git a/apps/studio/lib/ai/generate-assistant-response.ts b/apps/studio/lib/ai/generate-assistant-response.tsindex 460633fd992..b9ac4eadd9c 100644--- a/apps/studio/lib/ai/generate-assistant-response.ts+++ b/apps/studio/lib/ai/generate-assistant-response.ts@@ -126,6 +126,7 @@ export async function generateAssistantResponse({schemasString,supportMode,includesLogsSnippets,+ aiOptInLevel,}),...(await convertToModelMessages(messages)),]diff --git a/apps/studio/lib/ai/tools/cap-read-query.test.ts b/apps/studio/lib/ai/tools/cap-read-query.test.tsnew file mode 100644index 00000000000..b4273021f57--- /dev/null+++ b/apps/studio/lib/ai/tools/cap-read-query.test.ts@@ -0,0 +1,73 @@+import { safeSql } from '@supabase/pg-meta'+import { describe, expect, it } from 'vitest'++import { capReadQuery } from './cap-read-query'++describe('capReadQuery', () => {+ it('appends a limit when applyAutoLimit can', () => {+ expect(capReadQuery(safeSql`select * from users`, 101)).toEqual({+ sql: 'select * from users limit 101;',+ isCappedInDatabase: true,+ })+ })++ it('wraps queries with an explicit large LIMIT', () => {+ const { sql, isCappedInDatabase } = capReadQuery(+ safeSql`select * from users limit 1000000;`,+ 101+ )+ expect(isCappedInDatabase).toBe(true)+ expect(sql).toBe(+ 'select * from (\nselect * from users limit 1000000\n) as capped_result limit 101;'+ )+ })++ it('wraps queries with LIMIT ALL instead of appending a second limit', () => {+ const { sql, isCappedInDatabase } = capReadQuery(safeSql`select * from users limit all`, 101)+ expect(isCappedInDatabase).toBe(true)+ expect(sql).toBe(+ 'select * from (\nselect * from users limit all\n) as capped_result limit 101;'+ )+ })++ it('wraps FETCH FIRST and CTE queries', () => {+ expect(+ capReadQuery(safeSql`select * from users fetch first 5000 rows only`, 101).isCappedInDatabase+ ).toBe(true)+ expect(+ capReadQuery(safeSql`with t as (select 1) select * from t`, 101).isCappedInDatabase+ ).toBe(true)+ })++ it('keeps a trailing line comment from swallowing the closing paren', () => {+ const { sql } = capReadQuery(safeSql`select * from users limit 5000 -- all`, 101)+ expect(sql).toContain('-- all\n)')+ })++ it('ignores keywords and semicolons inside literals and comments', () => {+ for (const q of [+ safeSql`select * from t where note = 'please update; into' limit 5000`,+ safeSql`select "update", $$delete;$$ from t limit 5000 -- insert`,+ safeSql`select * from t /* for update */ limit 5000`,+ ]) {+ expect(capReadQuery(q, 101).isCappedInDatabase).toBe(true)+ }+ })++ it('still rejects writes that follow a literal', () => {+ const q = safeSql`with d as (delete from t where a = 'x' returning *) select * from d`+ expect(capReadQuery(q, 101)).toEqual({ sql: q, isCappedInDatabase: false })+ })++ it('leaves multiple statements and writes untouched', () => {+ for (const q of [+ safeSql`select 1; select 2`,+ safeSql`with d as (delete from t returning *) select * from d`,+ safeSql`with t as (select 1) select * into new_t from t`,+ safeSql`with t as (select 1) select * from t for update`,+ safeSql`insert into t values (1)`,+ ]) {+ expect(capReadQuery(q, 101)).toEqual({ sql: q, isCappedInDatabase: false })+ }+ })+})diff --git a/apps/studio/lib/ai/tools/cap-read-query.ts b/apps/studio/lib/ai/tools/cap-read-query.tsnew file mode 100644index 00000000000..0f967b9a09e--- /dev/null+++ b/apps/studio/lib/ai/tools/cap-read-query.ts@@ -0,0 +1,46 @@+import { literal, safeSql, type SafeSqlFragment } from '@supabase/pg-meta'++import { applyAutoLimit, trimTrailingSemicolons } from '@/data/sql/utils'++const WRAPPABLE_START = /^\s*(\(|select\b|with\b|values\b|table\b)/i+// Statements that can't live inside a subquery (or that write), so they're left untouched+// applyAutoLimit doesn't recognise `LIMIT ALL` and would append a second LIMIT+const HAS_LIMIT_ALL = /\blimit\s+all\b/i+const UNWRAPPABLE = /\b(insert|update|delete|merge|into|for\s+(no\s+key\s+)?(update|share))\b/i++// Quoted text and comments, matched left to right so a quote inside a comment (or the reverse)+// can't desync the scan: E'..' strings, '..' strings, "..." identifiers, $tag$..$tag$ bodies,+// -- line comments and /* */ block comments+const LITERALS_AND_COMMENTS =+ /\be'(?:[^'\\]|\\.|'')*'|'(?:[^']|'')*'|"(?:[^"]|"")*"|(\$[a-z_]*\$)[\s\S]*?\1|--[^\n]*|\/\*[\s\S]*?\*\//gi++/** Keeps only the SQL tokens, so keywords inside literals and comments aren't mistaken for syntax. */+const stripLiteralsAndComments = (sql: string) => sql.replace(LITERALS_AND_COMMENTS, ' ')++/**+ * Caps a read query at `limit` rows inside the database. Falls back to wrapping the query in a+ * subquery when `applyAutoLimit` can't append a limit (e.g. an explicit large LIMIT or+ * FETCH FIRST, CTEs, trailing comments). Anything that can't be wrapped safely — multiple+ * statements, writes, or text we can't confidently classify — is returned unchanged, so callers+ * must still slice the result.+ */+export function capReadQuery(+ sql: SafeSqlFragment,+ limit: number+): { sql: SafeSqlFragment; isCappedInDatabase: boolean } {+ const auto = HAS_LIMIT_ALL.test(stripLiteralsAndComments(sql))+ ? undefined+ : applyAutoLimit(sql, limit)+ if (auto?.appendAutoLimit) return { sql: auto.sql, isCappedInDatabase: true }++ const core = trimTrailingSemicolons(sql.trim() as SafeSqlFragment)+ const tokens = stripLiteralsAndComments(core)+ // Any remaining `;` means multiple statements (or a literal containing one): don't guess+ if (tokens.includes(';') || !WRAPPABLE_START.test(tokens) || UNWRAPPABLE.test(tokens)) {+ return { sql, isCappedInDatabase: false }+ }++ // Newlines around the query keep a trailing `--` comment from swallowing the closing paren+ const wrapped = safeSql`select * from (\n${core}\n) as capped_result limit ${literal(limit)};`+ return { sql: wrapped, isCappedInDatabase: true }+}diff --git a/apps/studio/lib/ai/tools/studio-tools.test.ts b/apps/studio/lib/ai/tools/studio-tools.test.tsindex 8a175db6d9d..c5e1a65f307 100644--- a/apps/studio/lib/ai/tools/studio-tools.test.ts+++ b/apps/studio/lib/ai/tools/studio-tools.test.ts@@ -189,12 +189,12 @@ describe('ai/tools/studio-tools', () => {{projectRef: 'test-project',connectionString: 'encrypted-connection-string',- sql: 'SELECT email FROM users',+ sql: 'SELECT email FROM users limit 101;',},undefined,undefined)- expect(result).toEqual({ rows, optInLevel: 'schema' })+ expect(result).toEqual({ rows, totalRows: 1, optInLevel: 'schema' })expect((tools.execute_sql as any).toModelOutput({ output: result })).toEqual({type: 'text',value: NO_DATA_PERMISSIONS,@@ -226,18 +226,106 @@ describe('ai/tools/studio-tools', () => {{projectRef: 'test-project',connectionString: 'encrypted-connection-string',- sql: 'SELECT email FROM users',+ sql: 'SELECT email FROM users limit 101;',},undefined,undefined)- expect(result).toEqual({ rows, optInLevel: 'schema_and_log_and_data' })+ expect(result).toEqual({ rows, totalRows: 1, optInLevel: 'schema_and_log_and_data' })expect((tools.execute_sql as any).toModelOutput({ output: result })).toEqual({type: 'json',value: rows,})})+ it('should push a row limit into read queries but leave write queries untouched', async () => {+ vi.mocked(executeSql).mockResolvedValue({ result: [] })+ const tools = getStudioTools({ projectRef: 'test-project' })+ if (!tools.execute_sql.execute) throw new Error('execute is undefined')+ const options = { toolCallId: 'test', messages: [], context: {} }+ const base = { label: 'Query', chartConfig: { view: 'table' as const } }++ await tools.execute_sql.execute(+ { ...base, sql: 'SELECT * FROM users', isWriteQuery: false },+ options+ )+ await tools.execute_sql.execute(+ { ...base, sql: 'SELECT cron.schedule(1)', isWriteQuery: true },+ options+ )++ const sqls = vi.mocked(executeSql).mock.calls.map(([vars]) => vars.sql)+ expect(sqls).toEqual(['SELECT * FROM users limit 101;', 'SELECT cron.schedule(1)'])+ })++ it('should cap rows and say the total is unknown when the limit ran in the database', async () => {+ const rows = Array.from({ length: 101 }, (_, i) => ({ id: i }))+ vi.mocked(executeSql).mockResolvedValue({ result: rows })+ const tools = getStudioTools({ aiOptInLevel: 'schema_and_log_and_data' })+ const input = {+ sql: 'SELECT id FROM users',+ label: 'Get ids',+ chartConfig: { view: 'table' as const },+ isWriteQuery: false,+ }++ if (!tools.execute_sql.execute) throw new Error('execute is undefined')+ const result = await tools.execute_sql.execute(input, {+ toolCallId: 'test',+ messages: [],+ context: {},+ })++ const truncatedOutput = {+ rows: rows.slice(0, 100),+ hasMoreRows: true as const,+ optInLevel: 'schema_and_log_and_data' as const,+ }+ expect(result).toEqual(truncatedOutput)+ const modelOutput = await tools.execute_sql.toModelOutput?.({+ toolCallId: 'test',+ input,+ output: truncatedOutput,+ })+ expect(modelOutput).toMatchObject({+ type: 'json',+ value: { rows: rows.slice(0, 100), note: expect.stringContaining('more than 100 rows') },+ })+ expect(JSON.stringify(modelOutput)).toContain('Do not state a specific total')+ })++ it('should report the real total when the query could not be limited in the database', async () => {+ const rows = Array.from({ length: 150 }, (_, i) => ({ id: i }))+ vi.mocked(executeSql).mockResolvedValue({ result: rows })+ const tools = getStudioTools({ aiOptInLevel: 'schema_and_log_and_data' })+ const input = {+ sql: 'SELECT id FROM users; SELECT id FROM users',+ label: 'Get ids',+ chartConfig: { view: 'table' as const },+ isWriteQuery: false,+ }++ if (!tools.execute_sql.execute) throw new Error('execute is undefined')+ const result = await tools.execute_sql.execute(input, {+ toolCallId: 'test',+ messages: [],+ context: {},+ })++ const output = {+ rows: rows.slice(0, 100),+ totalRows: 150,+ optInLevel: 'schema_and_log_and_data' as const,+ }+ expect(result).toEqual(output)+ expect(+ await tools.execute_sql.toModelOutput?.({ toolCallId: 'test', input, output })+ ).toEqual({+ type: 'json',+ value: { rows: rows.slice(0, 100), note: 'Only the first 100 of 150 rows are included.' },+ })+ })+it('should validate rename_chat input schema correctly', () => {const tools = getStudioTools()const schema = tools.rename_chat.inputSchemadiff --git a/apps/studio/lib/ai/tools/studio-tools.ts b/apps/studio/lib/ai/tools/studio-tools.tsindex f219a3efb14..7f2ca4f325e 100644--- a/apps/studio/lib/ai/tools/studio-tools.ts+++ b/apps/studio/lib/ai/tools/studio-tools.ts@@ -3,7 +3,9 @@ import { tool } from 'ai'import { z } from 'zod'import { getAuthHeaders } from './auth-headers'+import { capReadQuery } from './cap-read-query'import type { ToolContext } from './types'+import { DEFAULT_CELL_ROW_LIMIT } from '@/components/interfaces/Explorer/QueryCell/QueryCell.utils'import { deployEdgeFunction } from '@/data/edge-functions/edge-functions-deploy-mutation'import { executeSql } from '@/data/sql/execute-sql-mutation'import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'@@ -16,7 +18,7 @@ import {STORAGE_PROMPT,} from '@/lib/ai/prompts'import { isOptInLevelAtLeast, updateOptInLevelInputSchema } from '@/lib/ai/tool-filter'-import { NO_DATA_PERMISSIONS } from '@/lib/ai/tools/tool-sanitizer'+import { NO_DATA_PERMISSIONS, toModelRows } from '@/lib/ai/tools/tool-sanitizer'import { fixSqlBackslashEscapes } from '@/lib/ai/util'const KNOWLEDGE = {@@ -69,20 +71,35 @@ export const getStudioTools = (ctx: ToolContext = {}) => {'Asks the user to execute a SQL statement and return the results. Requires user approval before executing.',inputSchema: executeSqlInputSchema,needsApproval: true,- execute: async ({ sql }, { abortSignal }) => {+ execute: async ({ sql, isWriteQuery }, { abortSignal }) => {// The `needsApproval: true` gate on this tool means the user has// explicitly approved this AI-generated SQL before execute runs —// that approval is the user gesture that promotes untrusted to safe.+ const approvedSql = acceptUntrustedSql(untrustedSql(sql))+ // Push the cap into the query so the database doesn't load rows we'd throw away. The+ // extra row lets `totalRows > DEFAULT_CELL_ROW_LIMIT` still signal a truncated result.+ const { sql: limitedSql, isCappedInDatabase } = isWriteQuery+ ? { sql: approvedSql, isCappedInDatabase: false }+ : capReadQuery(approvedSql, DEFAULT_CELL_ROW_LIMIT + 1)const { result } = await executeSql(- { projectRef, connectionString, sql: acceptUntrustedSql(untrustedSql(sql)) },+ { projectRef, connectionString, sql: limitedSql },abortSignal,authHeaders)- return { rows: Array.isArray(result) ? result : [], optInLevel: aiOptInLevel }+ const rows = Array.isArray(result) ? result : []+ // same row cap as the query cell, unbounded results freeze the chat and overflow the model+ const isCapped = rows.length > DEFAULT_CELL_ROW_LIMIT+ // When the limit ran in the database, `rows.length` stops at the cap and isn't a real total+ const hasMoreRows = isCappedInDatabase && isCapped+ return {+ rows: rows.slice(0, DEFAULT_CELL_ROW_LIMIT),+ ...(hasMoreRows ? { hasMoreRows } : { totalRows: rows.length }),+ optInLevel: aiOptInLevel,+ }},toModelOutput: ({ output }) => {return aiOptInLevel === 'schema_and_log_and_data'- ? { type: 'json', value: output.rows }+ ? { type: 'json', value: toModelRows(output.rows, output) }: { type: 'text', value: NO_DATA_PERMISSIONS }},}),diff --git a/apps/studio/lib/ai/tools/tool-sanitizer.test.ts b/apps/studio/lib/ai/tools/tool-sanitizer.test.tsindex 08f96df5d72..a9c2e84eccd 100644--- a/apps/studio/lib/ai/tools/tool-sanitizer.test.ts+++ b/apps/studio/lib/ai/tools/tool-sanitizer.test.ts@@ -290,6 +290,25 @@ describe('execute_sql rows are shared only up to the level they ran under', () =expect((sanitizeMessagePart(part, current) as ToolUIPart).output).toEqual(expected)})+ test('caps rows replayed to the model and notes the result is partial', () => {+ const manyRows = Array.from({ length: 101 }, (_, i) => ({ id: i }))+ const part = executeSqlPart({ rows: manyRows, optInLevel: 'schema_and_log_and_data' })+ expect((sanitizeMessagePart(part, 'schema_and_log_and_data') as ToolUIPart).output).toEqual({+ rows: manyRows.slice(0, 100),+ note: 'Only the first 100 of 101 rows are included.',+ })+ })++ test('does not report a total when more rows existed than were fetched', () => {+ const part = executeSqlPart({+ rows: Array.from({ length: 100 }, (_, i) => ({ id: i })),+ hasMoreRows: true,+ optInLevel: 'schema_and_log_and_data',+ })+ const output = (sanitizeMessagePart(part, 'schema_and_log_and_data') as ToolUIPart).output+ expect(output).toMatchObject({ note: expect.stringContaining('more than 100 rows') })+ })+test('output saved before the stamp existed stays hidden', () => {const part = executeSqlPart(rows)expect((sanitizeMessagePart(part, 'schema_and_log_and_data') as ToolUIPart).output).toBe(diff --git a/apps/studio/lib/ai/tools/tool-sanitizer.ts b/apps/studio/lib/ai/tools/tool-sanitizer.tsindex 82b81af2893..34dce217f03 100644--- a/apps/studio/lib/ai/tools/tool-sanitizer.ts+++ b/apps/studio/lib/ai/tools/tool-sanitizer.ts@@ -4,6 +4,7 @@ import { z } from 'zod'import { lowerOptInLevel, optInLevelSchema, type ToolName } from '../tool-filter'import { sanitizeNotebookRunOutput } from './notebook-run-output'import { sanitizeContractPart } from './registry'+import { DEFAULT_CELL_ROW_LIMIT } from '@/components/interfaces/Explorer/QueryCell/QueryCell.utils'import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'interface ToolSanitizer {@@ -14,6 +15,24 @@ interface ToolSanitizer {export const NO_DATA_PERMISSIONS ='The query was executed and the user has viewed the results but decided not to share in the conversation due to permission levels. Continue with your plan unless instructed to interpret the result. If you need the rows to answer and `update_opt_in_level` is available, call it with `schema_and_log_and_data`, unless the user already skipped that request in this chat.'+// the rows.length default covers chats saved before execute_sql sliced its rows+export const toModelRows = <T>(+ rows: T[],+ {+ totalRows = rows.length,+ hasMoreRows = false,+ }: { totalRows?: number; hasMoreRows?: boolean } = {}+) => {+ if (!hasMoreRows && totalRows <= DEFAULT_CELL_ROW_LIMIT) return rows++ return {+ rows: rows.slice(0, DEFAULT_CELL_ROW_LIMIT),+ note: hasMoreRows+ ? `The query matches more than ${DEFAULT_CELL_ROW_LIMIT} rows. Only the first ${DEFAULT_CELL_ROW_LIMIT} are included because results are capped to protect database performance, so the exact total is unknown. Tell the user it matched more than ${DEFAULT_CELL_ROW_LIMIT} rows and only the first ${DEFAULT_CELL_ROW_LIMIT} are shown. Do not state a specific total.`+ : `Only the first ${DEFAULT_CELL_ROW_LIMIT} of ${totalRows} rows are included.`,+ }+}+/*** `optInLevel` is the level the query ran under. Rows are shared only at the lower of that* and the current level, so rows from `schema` stay hidden after an upgrade to data.@@ -21,6 +40,8 @@ export const NO_DATA_PERMISSIONS =*/export const executeSqlOutputSchema = z.object({rows: z.array(z.unknown()),+ totalRows: z.number().optional(),+ hasMoreRows: z.boolean().optional(),optInLevel: optInLevelSchema,})@@ -34,7 +55,10 @@ const executeSqlSanitizer: ToolSanitizer = {const level = lowerOptInLevel(parsed.data.optInLevel, optInLevel)return {...tool,- output: level === 'schema_and_log_and_data' ? parsed.data.rows : NO_DATA_PERMISSIONS,+ output:+ level === 'schema_and_log_and_data'+ ? toModelRows(parsed.data.rows, parsed.data)+ : NO_DATA_PERMISSIONS,}}