Agents
Build a ToolLoopAgent from a stored agent with its tools, approvals and knowledge search, and check input and output with a moderation middleware.
better-supabase/ai-sdk/agents runs an agent with
the AI SDK. It picks the tools the agent may use, asks for approval where
the tool policies say so, and adds a knowledge search tool for the agent's
scopes.
pnpm add aiRuntime
import { gateway } from "ai";
import { createAgentRuntime } from "better-supabase/ai-sdk/agents";
const runtime = createAgentRuntime({
agent,
model: (modelId) => gateway(modelId ?? "openai/gpt-5-mini"),
tools: { ...appTools, ...connectorTools },
policies: await chats.tools.policies(organizationId).orThrow(),
knowledge: { knowledge, organizationId },
instructions: "Answer in the user's language.",
});
const result = await runtime.stream({ messages });createAgentRuntime returns a ToolLoopAgent. Its instructions are the
app's instructions followed by the agent's own, and it stops after 20
steps unless you pass stopWhen. With knowledge, the model gets a
search_knowledge tool limited to the agent's knowledge scopes.
| Helper | Returns |
|---|---|
agentTools | The tools the agent lists (all of them when it lists none), minus deny |
agentToolApproval | user-approval for every tool whose policy is ask |
agentScopes | The agent's knowledge scopes, with agent resolved to its id |
An ask tool doesn't run until the user approves it: the stream carries a
tool-approval-request part, and the chat route stores
the approval.
Your own approval check
toolApproval takes the AI SDK's tool approval function (typed as
AgentToolApprovalFunction), for checks such as an authorization call or a
spending limit. It runs first for every call, and the tenant's policies then
apply on top: a tool whose policy is ask still needs the user's approval
when your check approves it, and a deny from your check always wins. A check
that throws denies the call.
const runtime = createAgentRuntime({
agent,
model,
tools,
policies,
toolApproval: async ({ toolCall }) =>
(await mayRun(user, toolCall.toolName))
? { type: "approved" }
: { type: "denied", reason: "Not allowed for this user" },
});Caller and actor
Pass caller with the user id from the verified session. That user is the
principal of every check the runtime makes and the user the AI Gateway
bills; the agent row is only the actor ({ kind: "agent", id }) and never
becomes the subject. For a run nobody invoked, such as a schedule, pass the
user who published the agent (agent.ownerId).
const runtime = createAgentRuntime({
agent,
model,
tools,
caller: { userId: session.userId, organizationId },
});The runtime passes the same context to authorizeModel, authorizeTool,
results and the AI SDK's runtimeContext: userId, organizationId
(the caller's tenant, else the agent's) and actor. A runtimeContext
passed to generate or stream can't replace these keys.
agentRunContext(agent, caller) builds it for your own code.
Delegated tools
When the session itself belongs to an agent (another agent called this one
with a token from agentClaims), pass its actor as actor. If its act
level lists tools, the run gets only those tools, and a call to any other
is denied before it runs. assertToolDelegated(actor, toolName) throws the
same refusal, a forbidden DbException with the code
AGENT_TOOL_NOT_DELEGATED, for your own checks. A level without tools
delegates every tool, and tools: [] delegates none. A read-only agent makes
the run's act read-only too, so its tools can't write either.
Only the runtime and assertToolDelegated read tools. Route guards and row
level security don't, so code that runs a tool outside the runtime must call
assertToolDelegated itself. Other libraries that read the same act claim
may deny any tool the list doesn't name, so set tools when you mint a token
another service checks.
const runtime = createAgentRuntime({
agent,
model,
tools,
caller: { userId: session.userId, organizationId },
actor: session.actor,
});Model access
authorizeModel(modelId, context) runs before every model call, with the
model's id (the string, or modelId of a model object). false or a
throw refuses the run with a forbidden DbException (code
AI_MODEL_NOT_ALLOWED, status 403) before the model is called, so no
tokens are spent. Every model is allowed without it, so set it when some
plans or roles may not use expensive models.
const runtime = createAgentRuntime({
agent,
model,
caller,
authorizeModel: (modelId, { organizationId }) =>
plans.allowsModel(organizationId, modelId),
});Tool permissions
Each tool is the operation ai.tool.<name>. The runtime reads its
permission from the authorization provider's operations first and from
permissions (the tool's own key) otherwise. false in permissions
marks a tool that needs no permission. With authorizeTool, every call
needs the caller to hold that permission: a tool with no permission, a
false answer and a throw all deny the call before toolApproval runs.
That includes search_knowledge: give it a permission, or false when
the knowledge block's own access rules are enough.
toolOperations names another operation for a tool, such as
{ void_invoice: "invoices.void" }, so an AI tool and an MCP tool that do
the same thing check one entry in the provider's table.
const runtime = createAgentRuntime({
agent,
model,
tools,
caller,
operations: config.authorization?.operations,
permissions: { search_docs: "docs.read", send_email: "email.send" },
authorizeTool: (permission, { userId, organizationId }) =>
can(userId, organizationId, permission),
});An operation whose provider entry has meta.risk: "high" waits for the
user's approval, as an ask tool does. agentToolOperation(name, operations, permissions) returns the operation, its permission and the
provider's risk, effects and title, for a settings page or an audit
entry.
Search results
results drops knowledge hits the caller may not read. It gets the hits
and the run context with toolName and query, and runs before the
reranker, onHits and the model see them. A throw fails the tool call.
const runtime = createAgentRuntime({
agent,
model,
caller,
knowledge: { knowledge, organizationId },
results: (hits, { userId }) =>
hits.filter((hit) => mayRead(userId, hit.documentId)),
});searchTool and recallTool take the same results option when you
build them yourself.
AI Gateway attribution
With caller or gateway, every model call carries
gatewayOptions: the caller's id as
user, then the tags org:<tenant>, feature:<feature> (default
agent), agent:<id> and your tags. gateway.options adds gateway
options such as order; a user in it is dropped, and model output or
tool input can't change these options.
const runtime = createAgentRuntime({
agent,
model,
caller,
gateway: { feature: "support", tags: ["team:billing"] },
});The attribution is applied in prepareCall, merged into the call's own
providerOptions: the library's user always wins, tags are the union, and
any other gateway key you set keeps your value.
Telemetry, settings and long chats
createAgentRuntime sets telemetry.functionId to agent:<id> and exposes the
run's organizationId to the integrations (includeRuntimeContext), so
meterTelemetry can meter the tenant. Without that setting the AI SDK drops
the runtime context before telemetry sees it, so a generateText call you make
yourself needs the same option. What you pass as telemetry wins. A per-call
telemetry.integrations replaces the integrations you registered once, such as
meterTelemetry, so list both.
Other ToolLoopAgent settings go in settings (toolCallConcurrency,
repairToolCall, output, callOptionsSchema and the sampling settings).
Your prepareCall runs first and the library adds the run context and the
gateway attribution to what it returns. Your prepareStep runs after the model
check. compact takes the options of pruneMessages and prunes old reasoning
and tool calls from the messages of every step. toolApprovalSecret signs
approval requests with experimental_toolApprovalSecret.
const runtime = createAgentRuntime({
agent,
model,
settings: { toolCallConcurrency: 2 },
compact: {
reasoning: "before-last-message",
toolCalls: "before-last-2-messages",
},
toolApprovalSecret: process.env.AI_APPROVAL_SECRET,
});An agent's skills are not sent to the model for you. Map them to your
provider's options in prepareCall, such as Anthropic's container.skills
under providerOptions.anthropic. For local debugging, register the AI SDK's
DevTools integration only in development, and remember it too is replaced by
a per-call integrations list.
Workflow agent
createWorkflowAgentRuntime from better-supabase/ai-sdk/workflow builds a
WorkflowAgent from the same options: the same tools, instructions, runtime
context, gateway attribution and authorizeModel check. The tenant's ask
tools, high-risk operations and your toolApproval check go to the agent's
toolApproval setting, which runs in workflow context: a call that asks waits
for the user, and a denied call becomes an execution-denied tool result that
the model sees, where earlier versions threw from the tool. toolApprovalSecret
({ environmentVariable }) signs the approval requests with AI SDK 7's
experimental_toolApprovalSecret.
import { createWorkflowAgentRuntime } from "better-supabase/ai-sdk/workflow";
const agent = createWorkflowAgentRuntime({
agent: row,
model,
tools,
policies,
caller,
toolApprovalSecret: { environmentVariable: "AI_APPROVAL_SECRET" },
});Moderation
import { wrapLanguageModel } from "ai";
import { moderationMiddleware } from "better-supabase/ai-sdk/agents";
const model = wrapLanguageModel({
model: gateway("openai/gpt-5-mini"),
middleware: moderationMiddleware({
chats,
organizationId,
chatId,
check: async (text, stage) => classify(text),
}),
});check gets the last user message (input) and the answer (output) and
returns a verdict with an action and a category, or nothing. Every
verdict is recorded in the AI chat moderation log.
A block verdict throws ModerationBlockedError before the model runs, or
after it answers; in a stream it ends the stream with an error part.
Skills
An agent skill can carry files (files), a contentHash and the provider references of earlier
uploads (providerRefs). syncSkill uploads the files with the SDK's uploadSkill when the hash
changed and records the reference with recordSkillSync. anthropicSkillOptions and
openaiShellSkills turn the references into provider options, and harnessSkills builds inline
skills for a harness agent.
import {
syncSkill,
anthropicSkillOptions,
} from "better-supabase/ai-sdk/agents";
await syncSkill({
skill,
agents,
api: anthropic.skills,
provider: "anthropic",
read,
});
const providerOptions = anthropicSkillOptions(skills);The agents SQL module moves to version 2, so run better-supabase upgrade.
Harness agents
harnessRoute runs a HarnessAgent (@ai-sdk/harness/agent) as a chat turn that survives between
requests. It authorizes the caller, locks the chat (a second turn answers 409), resumes the
session from the stored state, streams the turn, then detaches the session and stores the resume
state sealed with harnessStateCipher. The cipher uses AES-GCM with the chat and harness ids as
associated data, so a value moved to another chat does not open, and a key list lets you rotate
keys.
import {
harnessRoute,
harnessStateCipher,
} from "better-supabase/ai-sdk/agents";
const route = harnessRoute({
agent,
sessions,
cipher: harnessStateCipher([{ id: "2026-11", key: process.env.HARNESS_KEY }]),
authorize: ({ userId }, chatId) => canUseChat(userId, chatId),
steering: chatSteering(chat),
});A message sent while a turn runs goes through steerRoute. It is saved as a chat message, and the
running turn reads new messages and passes them to session.experimental_steerTurn. This reuses
the chat table instead of a queue: the queue block has static named queues and cannot claim a
message by chat (ADR 1157).
Tenant tool context
tenantToolsContext(tools, { organizationId, userId }) fills the SDK's toolsContext for every
tool that declares tenantContextSchema as its contextSchema, so a tool reads the tenant from
its typed context instead of a closure.
Tool guardrails
guardTools(tools, guardrails) wraps each tool's execute. The input is checked before the tool
runs: a block returns the refusal as the tool result and a redaction rewrites the input. The
output is checked after, and each chunk of a streaming tool is checked as it passes.
Last updated on