Files
supabase/apps/studio/lib/ai/tools/tool-from-contract.ts
Charis 96d51239c6 refactor(studio): migrate update_opt_in_level to a tool contract (#52081)
## Problem

`update_opt_in_level` is the last local assistant tool not on the tool
contract pattern. Its input schema is built for each request: a
transform captures the org's opt-in level, stamps `levelWhenAsked`, and
drops `requiredLevel` when the org already has it. The SDK stores that
parsed value, and the approval card reads it before the tool runs. A
contract has one static `inputSchema`, so this didn't fit.

Separately, `pages/api/ai/sql/policy.ts` passes every assistant tool to
a one-shot `generateText` and only removes `update_opt_in_level`. Any
tool with `needsApproval` (`execute_sql`, `deploy_edge_function`, the
notebook mutation and run tools) stops the step loop with no result, so
`output` is never set and the route returns a 500.

## Solution

- `ToolContract` gains an optional `createInputSchema(ctx)`.
`toolFromContract` parses with it when present. `inputSchema` stays the
shape stored on the message, which is what history replay and the client
parse.
- `update_opt_in_level` moves to `update-opt-in-level.ts` and
`update-opt-in-level.server.ts`:
- The per-request transform becomes `createInputSchema`; the stored
shape is `inputSchema`.
- The output schema moves out of `OptInRequest.tsx` into the contract;
`toModelOutput` returns it unchanged, since it only contains level
names.
- `minOptInLevel: null` and `needsApproval: true`, as before. It uses
plain `toolFromContract`, since it promotes no SQL.
- Registered in `TOOL_CONTRACTS`, removed from `TOOL_CATEGORY_MAP`.
`getOptInTools` still registers it on platform at every level.
- `Message.Parts.tsx`, `OptInRequest.tsx`, and `evals/opt-in-replay.ts`
use the contract's schemas; the old schemas in `tool-filter.ts` and
`studio-tools.ts` are removed.
- `ToolContext.aiOptInLevel` is now required. The `'schema'` defaults in
`toolFromContract`, `execute-sql.server.ts`, and
`run-notebook.server.ts` are gone, and every caller passes the real
level. The eval mocks pin the mocked studio tools to `'schema'` so eval
results don't shift.
- New `withoutApprovalTools(tools)` in `tool-filter.ts` drops any tool
whose `needsApproval` is set (including a function, and privacy-stubbed
tools). `policy.ts` uses it instead of deleting one tool.

## Behavior changes

- Replayed `update_opt_in_level` outputs are validated against the
output schema and dropped if invalid (previously unchecked).
- The policy generator no longer offers approval-gated tools to the
model.

## Testing

- New `update-opt-in-level.test.ts` (transform, per-request schema,
execute at a new level, replay) and `tool-from-contract.test.ts`
(`createInputSchema` used when present and receives the context).
- `withoutApprovalTools` tests in `tool-filter.test.ts`.
- `pnpm exec vitest run lib/ai components/ui/AIAssistantPanel evals`
passes in `apps/studio`.
2026-10-21 16:18:20 -04:00

47 lines
1.8 KiB
TypeScript

import type { Tool, ToolExecutionOptions } from 'ai'
import { approvalGate, type ApprovalGate } from './approval-gate'
import type { ToolContext, ToolContract } from './types'
/**
* Builds the SDK tool for a contract. Description, input schema, approval and the model's
* view of the output all come from the contract; only `execute` is supplied.
*/
export function toolFromContract<TInput, TOutput>(
contract: ToolContract<TInput, TOutput>,
ctx: ToolContext,
execute: (input: TInput, options: ToolExecutionOptions<unknown>) => PromiseLike<TOutput> | TOutput
): Tool<TInput, TOutput> {
const { toModelOutput } = contract
// The SDK's `Tool` type is conditional on whether `TOutput` is `never`, which TypeScript
// can't resolve for a generic `TOutput`. Each factory's `ToolFactory<typeof contract>`
// annotation checks the concrete types instead.
return {
description: contract.description,
inputSchema: contract.createInputSchema?.(ctx) ?? contract.inputSchema,
needsApproval: contract.needsApproval,
execute,
toModelOutput: ({ output }: { output: TOutput }) => ({
type: 'json' as const,
value: toModelOutput(output, ctx.aiOptInLevel),
}),
} as unknown as Tool<TInput, TOutput>
}
/**
* Like `toolFromContract`, for a contract that requires user approval. `execute` also receives
* the `ApprovalGate`, which is how it gets the functions that promote untrusted SQL.
*/
export function approvalGatedToolFromContract<TInput, TOutput>(
contract: ToolContract<TInput, TOutput> & { readonly needsApproval: true },
ctx: ToolContext,
execute: (
input: TInput,
options: ToolExecutionOptions<unknown>,
gate: ApprovalGate
) => PromiseLike<TOutput> | TOutput
): Tool<TInput, TOutput> {
return toolFromContract(contract, ctx, (input, options) => execute(input, options, approvalGate))
}