Commit Graph
4 Commits
Author SHA1 Message Date
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
Charis 51b7cd6a4b refactor(studio): declare Assistant tool availability on contracts (#52396)
## What

Assistant tool contracts now declare where they're available, and
`getTools` builds tools from the registry.

- `ToolContract` and `RemoteToolContract` gain `availability: {
environments, requires? }`, both read-only sets. `environments` is
`platform` and/or `self-hosted`; `requires` is any of `explorer`,
`supportMode`, `baseUrl`.
- New `tools/registry.server.ts` maps every contract to its factory in
`TOOL_FACTORIES`; its type makes a missing or mismatched factory a
compile error. `buildLocalTools` builds only the tools available for a
request.
- `getTools` no longer branches per tool module. Local contract tools
take precedence over remote MCP tools with the same name. The
self-hosted fallback tools are unchanged for now.
- Deleted the per-module getters (`studio-tools.ts`, `schema-tools.ts`,
`report-tools.ts`, `notebook-tools.ts`, `incident-tools.ts`,
`support-tools.ts`); their tests now call the factories directly.

## Behavior changes

- Self-hosted no longer offers `deploy_edge_function`. Its server half
calls `/v1/projects/{ref}/functions/deploy`, which self-hosted Studio
doesn't serve.
- Self-hosted no longer offers the support tools (`escalate_to_human`,
`resolve_support_conversation`) in support mode.
- Platform offers `list_databases` without the Explorer flag.

Everything else produces the same tool set as before.

## Tests

- `index.availability.test.ts` asserts the exact tool names for every
combination of environment, Explorer, support mode, and `baseUrl`.
- `registry.test.ts` checks registry invariants: keys match contract
names, every contract has a factory, and a name in both the local and
remote maps has disjoint environments and matching gates.

This is the first step in moving the self-hosted Assistant tools to
contracts.

## 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-27 18:06:55 +00:00
Charis 9ae8432dc7 refactor(studio): migrate create, delete, and run notebook tools to tool contracts (#51754)
## Summary

Migrates the create, delete, and run notebook assistant tools to the
tool contract + server pattern used by `update_notebook`. Each tool now
defines its schema once in a shared contract, with server-only execution
split into a `.server.ts` module. This removes duplicated client-side
schemas and gives the three tools one shared notebook mutation output
schema.

## Changes

- Add `create-notebook`, `delete-notebook`, and `run-notebook` tool
contracts, each with a `.server.ts` implementation.
- Remove the duplicated client-side schemas for these tools from
`notebook-tools.ts` and the registry.
- Add `notebook-mutation-output.ts` as the single output schema shared
by the notebook mutation tools.
- Add `lib/ai/opt-in-level.ts` with the opt-in level helpers, extracted
from the existing module to break an import cycle.
- Add optional `ToolContract.outputOnInvalid` so `run_notebook` history
replay can reuse a stored output when input fails validation.
- Update the AI assistant panel renderers (proposal, run, opt-in modal
and request) and the tool filter, sanitizer, and cache invalidation to
use the new contracts.

## Deviations worth reviewing

- **`outputOnInvalid` on `ToolContract`.** This is a new optional hook.
It exists so `run_notebook` history replay can return a valid output
when stored input no longer passes validation. Reviewers should confirm
this is the right level for the hook rather than handling it inside the
tool.
- **`opt-in-level.ts` extraction.** The helpers were moved into their
own module to break a circular import between the tool modules and the
opt-in components. This adds one file, but no behavior change is
intended.
- **`create-notebook` contract imports the data-layer
`notebook-schema`.** This matches `update-notebook`. It should be moved
behind the contract before the planned ESLint rule step, which restricts
contract modules from importing data-layer code.

## Testing

- `vitest` for `lib/ai`, `components/ui/AIAssistantPanel`, and `state`:
920 tests pass across 71 files.
- `tsc`: one error remains in `packages/ui-patterns`
(`InstructionBlocks.tsx`), which is unrelated to this change. I have not
verified whether it also fails on the base branch.
- ESLint reports no errors on the changed files (9 `no-explicit-any`
warnings in `tool-filter.ts` and its test); Prettier is clean.
- Not run: knip and the lint ratchet.
2026-10-15 11:16:58 -04:00
Charis cd6afdd8b2 refactor(studio): add tool contracts and migrate update_notebook (#51626)
## Summary

Each assistant tool's identity and contract is currently written in up
to nine places that nothing ties together at compile time. This PR adds
a contract/server split and migrates `update_notebook`, the tool with
the most copies, as the first proof of the design.

- **Contract** (`lib/ai/tools/update-notebook.ts`): isomorphic file with
the input and output schemas, approval flag, minimum opt-in level, and
`toModelOutput`, the single rule for what the model may see.
- **Server** (`update-notebook.server.ts`): the executable tool, built
with `approvalGatedToolFromContract`.
- **Registry** (`registry.ts`): collects contracts, derives a typed
`StudioUIMessage`, and provides `sanitizeContractPart` for history
replay.
- **Shared types** (`types.ts`): `ToolContract`, `ToolContext`,
`ToolFactory`, plus a single `getAuthHeaders` replacing three variants.
- **Approval gate** (`approval-gate.ts`): approval-gated tools get
`acceptUntrustedSql` / `acceptUntrustedLogsSql` through a gate passed to
`execute`, and `*.server.ts` files can't import the raw functions
(ESLint).
- **Opt-in level**: `update_notebook` is gated by its contract's
`minOptInLevel`. `TOOL_CATEGORY_MAP` is now typed against `ToolName` and
excludes migrated tools, which exposed `get_active_incidents` missing
from the name enum.

Removed duplicates: the `update_notebook` sanitizer in
`tool-sanitizer.ts`, the client-side `stripNotebookSnapshot`, and the
copied update schemas in `Message.utils.ts`.

## Behavior changes

- The client no longer strips `previous_content` from `update_notebook`
outputs before sending history, so requests carry the previous notebook
snapshot. The server still strips it before the model sees it.
- On history replay, an `update_notebook` output that doesn't match its
schema is dropped instead of passed through minus `previous_content`.

## Testing

- New `registry.test.ts` (typed parts, replay sanitizer) and a contract
case in `tool-filter.test.ts`.
- Studio typecheck, lint ratchet, knip, Prettier and the affected vitest
suites pass.
2026-10-14 10:44:38 -04:00