Files
supabase/apps/studio/lib/ai/tools/update-opt-in-level.ts
Charis 6aefa45d2b refactor(studio): build the Assistant tool prompt from contracts (#52422)
Stacked on supabase/supabase#52398.

## What

The chat system prompt's tool guidance now comes from the contracts
available to the request, so the prompt never names a tool the request
doesn't have.

* `ToolContract` and `RemoteToolContract` gain an optional
`promptGuidance`: rules for using the tool that its description doesn't
cover.
* `buildToolsPrompt` generates a `## Tools` section: every available
tool by name, sorted, plus a section with the guidance of each tool that
has any. Tool descriptions aren't repeated, since the model already gets
them in the tool definitions.
* `getToolRequest` computes the environment and satisfied requirements
once, for both `getTools` and the prompt.
* `buildSystemPrompt` assembles the full chat system prompt, used by
`generateAssistantResponse` and by the tests.
* Rules that named a tool move out of `GENERAL_PROMPT`, `CHAT_PROMPT`,
`LIMITATIONS_PROMPT`, `NOTEBOOKS_PROMPT` (deleted), the hardcoded
Available Knowledge list, and the opt-in, support-mode, and logs-snippet
context messages into the `promptGuidance` of the tool each rule is
about.
* `SECURITY_PROMPT` is unchanged because it's shared with code
completion.

## Prompt changes

* Platform: the same guidance, reorganized under the tool it applies to.
Small rewording: the two `search_docs` rules are merged, the opt-in rule
no longer starts with "if `update_opt_in_level` is available", and two
typos are fixed. The tool list also names tools the old prompt didn't
mention.
* Self-hosted: the prompt lists only `execute_sql`, `load_knowledge`,
and `rename_chat`, and no longer mentions platform-only tools like
`search_docs`, `query_logs`, notebooks, or the opt-in tool. The
self-hosted fallback tools aren't listed until they become contracts in
a later PR.

## Prompt caching

The tools section varies with the actual provided tools. That adds no
cache misses: providers cache tool definitions before the system prompt,
so a change to the tool set already invalidates the cached system prompt
([Anthropic](<https://platform.claude.com/docs/en/build-with-claude/prompt-caching#what-invalidates-the-cache>),
[Bedrock](<https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html#prompt-caching-converse>),
[OpenAI](<https://developers.openai.com/api/docs/guides/prompt-caching>)).

## Tests

* For every combination of environment, Explorer, support mode, and base
URL, the system prompt and context messages name only tools available to
that request.
* Outside its generated section, the system prompt names no tools except
`execute_sql` in the shared `SECURITY_PROMPT`.
* Labeled `run-evals` to check the reworded prompt for regressions.

## Checklist

Check all before review:

- [X] I have read
[CONTRIBUTING.md](<https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md>)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](<https://github.com/supabase/supabase/tree/master/apps/docs/style-guide>)
2026-10-30 15:42:18 -04:00

56 lines
3.5 KiB
TypeScript

import { z } from 'zod'
import type { ToolContract } from './types'
import { isOptInLevelAtLeast, optInLevelSchema } from '@/lib/ai/opt-in-level'
/** What the model sends. */
const modelInputSchema = z.object({
requiredLevel: z
.enum(['schema', 'schema_and_log', 'schema_and_log_and_data'])
.optional()
.describe(
'The lowest opt-in level that unlocks what you need: `schema` for table and column metadata, `schema_and_log` for logs, `schema_and_log_and_data` for query results. Omit it when the user just wants to review or change the setting, for example to lower it.'
),
})
/**
* Input as stored on the message. `levelWhenAsked` is the org's level when the call was made.
* Optional because older chats may lack it.
*/
const storedInputSchema = modelInputSchema.extend({
levelWhenAsked: optInLevelSchema.optional(),
})
type StoredInput = z.infer<typeof storedInputSchema>
const outputSchema = z.object({
levelAfterReview: optInLevelSchema,
sufficient: z.boolean().optional(),
status: z.string().optional(),
})
type Output = z.infer<typeof outputSchema>
export const contract = {
name: 'update_opt_in_level',
description:
'Asks the user to review or change the organization-wide AI opt-in level. Call it with `requiredLevel` when a tool needs a higher level than the organization has or you need to read query results. Call it without `requiredLevel` whenever the user asks to change the setting, including lowering it. Do not call it again in the same chat after the user skipped it unless they ask.',
inputSchema: storedInputSchema,
createInputSchema: ({ aiOptInLevel }) =>
modelInputSchema.transform(({ requiredLevel }) => ({
levelWhenAsked: aiOptInLevel,
...(requiredLevel && !isOptInLevelAtLeast(aiOptInLevel, requiredLevel) && { requiredLevel }),
})),
outputSchema,
minOptInLevel: null,
availability: {
environments: new Set(['platform']),
},
needsApproval: true,
promptGuidance: `- The organization's opt-in level, stated in the conversation context, limits which tools you can use and whether you can read query results. When a tool needs a higher level, or you need the rows from \`execute_sql\`, call \`update_opt_in_level\` with the lowest \`requiredLevel\` that unlocks it. Call it before the blocked tool and wait for the answer, never in the same step as that tool. Do not tell the user you have no access without calling it first. If the current level already allows what you need, use the tool directly; never call \`update_opt_in_level\` for access the organization already has.
- You cannot change the setting yourself, but \`update_opt_in_level\` lets the user do it. Whenever the user asks to review, change, raise, or lower the opt-in level, call it. Omit \`requiredLevel\` unless they asked for a specific access or you need it, so you never pick a level for them. Never tell them to ask an owner or admin before calling it, because the card shows that itself if they lack permission.
- After the result, if the user only asked to change the setting, say in one short sentence what the level is now and stop. If they had another request, report the level in one short sentence, then call the tool you needed again and continue (approving does not re-run earlier queries). Do not call \`update_opt_in_level\` again just to confirm it.
- Only an explicit skip of \`update_opt_in_level\` means the user declined. Do not request that level again in this chat unless they ask. Answer without that data and suggest alternatives.`,
toModelOutput: (output) => output,
} as const satisfies ToolContract<StoredInput, Output>