Assistant UI
Adapters
Actions are the API operations you've registered for the agent under Actions. The actions adapter is how they run: it's the code in your page that makes the request. The assistant has no credentials of its own, so every action runs in the user's own browser session, and the agent can do nothing the user couldn't.
How an action runs
- The agent decides to call an action. It calls it as a tool named
action__<slug>, where the slug comes from your catalog. - If the action needs approval, the assistant asks the user first, in its own card. Nothing reaches your adapter until they approve.
- Teaflask builds the request from your catalog entry, an
ActionIntent, and sends it to the page. The method and path come from the catalog. The agent supplies only argument values, which are checked against the action's schemas. - Your adapter makes the request to your API.
- The response's status and body go back to the agent. With the
cookiesandheaderskinds, a404or422counts as your API's answer, not a failure, so the agent can explain it to the user. Bodies over about 16,000 characters are cut short.
The intent never contains an origin. The request goes wherever your adapter sends it and nowhere else.
Choose a kind
| Kind | Use it when your API… | The package |
|---|---|---|
cookies |
authenticates with a session cookie | builds the URL and fetches with the browser's cookies |
headers |
needs an Authorization header or similar |
builds the URL and fetches with the headers you return |
request |
is best reached through your own API client | hands you the intent; you make the request |
Prefer cookies or headers when either fits. The package reads the response itself, so the agent gets your API's real status and error body. A request adapter reports only what you return or throw.
A GraphQL API is the exception: run its actions with request, through your app's own GraphQL client. GraphQL shows how.
Cookies
import type { ActionsAdapter } from "@teaflask/assistant";
export const actionsAdapter: ActionsAdapter = {
kind: "cookies",
baseUrl: "https://app.example.com/api",
};
The package fetches baseUrl plus the action's path with credentials: "include". If your API is on a different origin from the page, it has to allow credentialed CORS from the page's origin, and your cookie settings, including SameSite, have to let the browser send the cookie.
Headers
import type { ActionsAdapter } from "@teaflask/assistant";
export const actionsAdapter: ActionsAdapter = {
kind: "headers",
baseUrl: "https://api.example.com/v1",
getHeaders: async () => ({
Authorization: `Bearer ${await getAccessToken()}`,
}),
};
getAccessToken stands for your own auth code. getHeaders runs before every request and receives the intent. It can be async, so it can refresh a token. Its headers override the package's Content-Type, and if it throws, the action is reported as failed.
This kind also suits a same-origin cookie session that needs an extra header, such as a CSRF token: the browser sends the cookie and you return the header. It doesn't send cookies to another origin. For a cross-origin API that needs cookies and custom headers together, use request.
Your own client
import type { ActionIntent, ActionsAdapter } from "@teaflask/assistant";
export const actionsAdapter: ActionsAdapter = {
kind: "request",
async execute(intent: ActionIntent) {
const response = await apiClient.request({
method: intent.method,
url: expandPath(intent.pathTemplate, intent.pathParams),
params: intent.query,
data: intent.body,
});
return response.data;
},
};
apiClient stands for your authenticated client and expandPath for a helper that fills each {name} in the path with its URL-encoded value.
Return the parsed response body. Whatever execute resolves with reaches the agent as a success with status 200. To report a failure, throw.
That makes one thing important: a client that resolves on error responses will tell the agent a failed action succeeded, and the agent will tell your user so. If your client doesn't throw on non-2xx responses, check the status in execute and throw.
The agent gets more to work with if what you throw carries your API's answer. An error with a numeric status and an error object holding a string code, plus optionally details as a list of { path, message } problems, reaches the agent with that status, code and field problems. Then it can tell the user which field to fix. A plain Error reaches it as its message alone.
Give the assistant the adapter
Define the adapter once, at module scope, and pass it to the assistant you mounted in your app shell:
<TeaflaskAssistant publishableKey="pk_live_…" actionsAdapter={actionsAdapter} />
If you mount a TeaflaskAssistantProvider yourself, for a full page or your own interface, pass it there instead. On the script tag, it's a property on the element:
<script type="module">
document.querySelector("teaflask-assistant").actionsAdapter = {
kind: "cookies",
baseUrl: "https://app.example.com/api",
};
</script>
If your page sends a Content Security Policy, add your API's origin to connect-src.
What the intent contains
interface ActionIntent {
action: { slug: string; title: string };
method: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE";
pathTemplate: string; // "/orders/{order_id}"
pathParams: Record<string, unknown>; // { order_id: "ord_123" }
query: Record<string, unknown>;
body?: unknown;
graphql?: ActionIntentGraphQL; // only on a GraphQL action
}
interface ActionIntentGraphQL {
operationName: string; // "RenamePost"
operationType: "query" | "mutation";
document: string;
variables: Record<string, unknown>;
}
The cookies and headers kinds turn it into a request for you:
- They fill the path's placeholders with URL-encoded values.
- They add each query value as its own parameter. Strings, numbers and booleans are sent as text, arrays and objects as JSON text, and
nullor missing values are left out. - They send the body as JSON.
A request adapter does all of that itself. On a GraphQL action, graphql carries the operation; see GraphQL.
GraphQL
A GraphQL action is one operation your app's own code defines, such as a RenamePost mutation, so the agent can do what your app's screens do and nothing more.
Its intent is a POST to your GraphQL endpoint. Its body is the standard GraphQL request, { query, operationName, variables }, and its graphql field carries the operation itself: operationName, operationType ("query" or "mutation"), document and the validated variables.
Run GraphQL actions with a request adapter, through the GraphQL client your app already uses. Your client keeps everything your app set up around it: its auth, its persisted queries and its cache. The request goes out the way your app's own requests do, and screens that show what an action changed can update from the cache. Copy the adapter for your client below, call it with your client, and pass what it returns as actionsAdapter.
Find the operation by name
An adapter can run the operation in one of two ways. Looking operationName up among your app's own operations sends exactly the request your app sends. Parsing document lets your client print the operation again, and an API that accepts only its own registered requests, through a persisted query list, trusted documents or a safelist of operation hashes, may refuse the printed text. Without such an allowlist, either way works.
Prefer finding it by name. Each by-name adapter below takes your app's own operations, as its section describes, and throws when none has the action's name, so the action is reported as failed and nothing is sent.
Resolve the whole response
Resolve execute with the whole GraphQL response, { data, errors }, even when it carries errors, never data alone. GraphQL errors are your API's answer, not a failure: the agent reads them beside the data, tells the user what's missing, and after a mutation checks what already changed before it retries. Reject only when no GraphQL response arrived, such as on a network failure. The action is then reported as failed.
That includes a response whose data is null, such as a mutation whose result field failed: resolve { data: null, errors }. Many clients reject a response that carries errors, some only when its data is null. Each adapter below turns that back into the whole response.
A response over about 16,000 characters is cut short. One that carries errors keeps all of them unless the errors alone exceed the limit: its other top-level fields, such as extensions, are dropped first, and its data is shortened only if it still doesn't fit. A response without errors is cut whole, like any other body.
Apollo Client
apolloByNameAdapter(client, operations) runs your exported document of the same name through your ApolloClient, so its links, such as persisted queries and auth, and its cache apply. Pass the module your documents are exported from, for example import * as operations from "./graphql/operations". apolloAdapter(client) parses document instead.
Both run with errorPolicy: "all". Without it, Apollo rejects a response that carries errors, and the agent would read a failure instead of your API's answer. Queries use fetchPolicy: "network-only", so the agent reads your API rather than the cache.
// Apollo Client: run a GraphQL action through your app's own ApolloClient,
// so its links (persisted queries, auth) and its cache apply. errorPolicy
// "all" resolves a response that carries errors instead of rejecting it;
// the adapter hands the assistant the whole response, errors included.
import {
CombinedGraphQLErrors,
type ApolloClient,
type DocumentNode,
} from "@apollo/client";
import type {
ActionIntent,
ActionIntentGraphQL,
RequestActionsAdapter,
} from "@teaflask/assistant";
import { parse } from "graphql";
function graphqlOf(intent: ActionIntent): ActionIntentGraphQL {
if (intent.graphql === undefined)
throw new Error(`"${intent.action.title}" is not a GraphQL action.`);
return intent.graphql;
}
async function run(
client: ApolloClient,
document: DocumentNode,
operation: ActionIntentGraphQL,
) {
const { variables } = operation;
const result =
operation.operationType === "mutation"
? await client.mutate({
mutation: document,
variables,
errorPolicy: "all",
})
: await client.query({
query: document,
variables,
errorPolicy: "all",
fetchPolicy: "network-only",
});
// GraphQL errors are an answer; anything else (the network) is a failure.
if (result.error !== undefined && !CombinedGraphQLErrors.is(result.error))
throw result.error;
const data = result.data ?? null;
return result.error === undefined
? { data }
: { data, errors: result.error.errors };
}
/** Runs the operation's document, parsed, through your client. */
export function apolloAdapter(client: ApolloClient): RequestActionsAdapter {
return {
kind: "request",
async execute(intent) {
const operation = graphqlOf(intent);
return run(client, parse(operation.document), operation);
},
};
}
/** Runs your app's own exported document of the same name — the request
* your app already sends, whatever order its fragments are in. */
export function apolloByNameAdapter(
client: ApolloClient,
operations: Record<string, unknown>,
): RequestActionsAdapter {
const byName = new Map<string, DocumentNode>();
for (const value of Object.values(operations)) {
const document = value as DocumentNode;
if (document?.kind !== "Document") continue;
for (const definition of document.definitions) {
if (definition.kind === "OperationDefinition" && definition.name)
byName.set(definition.name.value, document);
}
}
return {
kind: "request",
async execute(intent) {
const operation = graphqlOf(intent);
const document = byName.get(operation.operationName);
if (document === undefined)
throw new Error(
`No exported document is named ${operation.operationName}.`,
);
return run(client, document, operation);
},
};
}
urql
urqlAdapter(client) hands your urql Client the operation's document as text, so your exchanges, such as auth and the cache, apply. It resolves the whole response and rejects on a network error.
urql sends the text it's given. An API that accepts only its own registered requests accepts it when that text is the text your app registered. If it refuses one, see When your API accepts only its own requests.
// urql with gql tags: run a GraphQL action through your app's own urql
// Client, so its exchanges (auth, cache) apply. The adapter resolves the
// whole response — errors included — and rejects on a network error.
import type {
ActionIntent,
ActionIntentGraphQL,
RequestActionsAdapter,
} from "@teaflask/assistant";
import type { Client } from "urql";
function graphqlOf(intent: ActionIntent): ActionIntentGraphQL {
if (intent.graphql === undefined)
throw new Error(`"${intent.action.title}" is not a GraphQL action.`);
return intent.graphql;
}
/** Hands urql the operation's document as text; urql parses and sends it. */
export function urqlAdapter(client: Client): RequestActionsAdapter {
return {
kind: "request",
async execute(intent) {
const { document, operationType, variables } = graphqlOf(intent);
const result =
operationType === "mutation"
? await client.mutation(document, variables).toPromise()
: await client
.query(document, variables, { requestPolicy: "network-only" })
.toPromise();
if (result.error?.networkError) throw result.error.networkError;
const data = result.data ?? null;
const errors = result.error?.graphQLErrors ?? [];
return errors.length > 0 ? { data, errors } : { data };
},
};
}
urql with codegen persisted documents
With the graphql-codegen client preset and persisted documents, urqlByNameAdapter(client, generated) looks the operation up by name in your generated gql/graphql module and runs that document through your urql Client. Pass that module, for example import * as generated from "./gql/graphql". The request carries the persisted id your build registered.
// urql with the graphql-codegen client preset and persisted documents:
// look the operation up by name in your generated gql/graphql module and
// run that document through your own urql Client, so the request carries
// the persisted id your app's build registered.
import type {
ActionIntent,
ActionIntentGraphQL,
RequestActionsAdapter,
} from "@teaflask/assistant";
import type { Client, TypedDocumentNode } from "urql";
function graphqlOf(intent: ActionIntent): ActionIntentGraphQL {
if (intent.graphql === undefined)
throw new Error(`"${intent.action.title}" is not a GraphQL action.`);
return intent.graphql;
}
/** `generated` is your codegen output: `import * as generated from "./gql/graphql"`. */
export function urqlByNameAdapter(
client: Client,
generated: Record<string, unknown>,
): RequestActionsAdapter {
const byName = new Map<string, TypedDocumentNode>();
for (const value of Object.values(generated)) {
const document = value as TypedDocumentNode;
if (document?.kind !== "Document") continue;
for (const definition of document.definitions) {
if (definition.kind === "OperationDefinition" && definition.name)
byName.set(definition.name.value, document);
}
}
return {
kind: "request",
async execute(intent) {
const { operationName, operationType, variables } = graphqlOf(intent);
const document = byName.get(operationName);
if (document === undefined)
throw new Error(`No generated document is named ${operationName}.`);
const result =
operationType === "mutation"
? await client.mutation(document, variables).toPromise()
: await client
.query(document, variables, { requestPolicy: "network-only" })
.toPromise();
if (result.error?.networkError) throw result.error.networkError;
const data = result.data ?? null;
const errors = result.error?.graphQLErrors ?? [];
return errors.length > 0 ? { data, errors } : { data };
},
};
}
graphql-request
graphqlRequestByNameAdapter(client, operations) runs your exported document of the same name through your GraphQLClient, so its headers and middleware apply. Pass the module your documents are exported from, for example import * as operations from "./graphql/operations". graphqlRequestAdapter(client) parses document instead. graphql-request throws a ClientError when a response carries errors, and both adapters turn it back into the whole response.
If your operations are strings rather than documents, use the plain fetch adapter.
// graphql-request with DocumentNodes: run a GraphQL action through your
// app's own GraphQLClient (its headers and middleware apply).
// graphql-request throws a ClientError when a response carries errors;
// the adapter turns that back into the whole response.
import type {
ActionIntent,
ActionIntentGraphQL,
RequestActionsAdapter,
} from "@teaflask/assistant";
import { type DocumentNode, parse } from "graphql";
import { ClientError, type GraphQLClient } from "graphql-request";
function graphqlOf(intent: ActionIntent): ActionIntentGraphQL {
if (intent.graphql === undefined)
throw new Error(`"${intent.action.title}" is not a GraphQL action.`);
return intent.graphql;
}
async function run(
client: GraphQLClient,
document: DocumentNode,
variables: Record<string, unknown>,
) {
try {
return { data: await client.request({ document, variables }) };
} catch (error) {
if (error instanceof ClientError && typeof error.response === "object") {
return {
data: error.response.data ?? null,
errors: error.response.errors,
};
}
throw error;
}
}
/** Parses the operation's document; graphql-request prints and sends it. */
export function graphqlRequestAdapter(
client: GraphQLClient,
): RequestActionsAdapter {
return {
kind: "request",
async execute(intent) {
const { document, variables } = graphqlOf(intent);
return run(client, parse(document), variables);
},
};
}
/** Runs your app's own exported document of the same name. */
export function graphqlRequestByNameAdapter(
client: GraphQLClient,
operations: Record<string, unknown>,
): RequestActionsAdapter {
const byName = new Map<string, DocumentNode>();
for (const value of Object.values(operations)) {
const document = value as DocumentNode;
if (document?.kind !== "Document") continue;
for (const definition of document.definitions) {
if (definition.kind === "OperationDefinition" && definition.name)
byName.set(definition.name.value, document);
}
}
return {
kind: "request",
async execute(intent) {
const { operationName, variables } = graphqlOf(intent);
const document = byName.get(operationName);
if (document === undefined)
throw new Error(`No exported document is named ${operationName}.`);
return run(client, document, variables);
},
};
}
Relay
relayByNameAdapter(environment, artifacts) looks the operation up by name among your compiled artifacts and executes it through your own Environment. Pass the artifacts as an array: import the default export of each __generated__/*Query.graphql and *Mutation.graphql module the agent may run, for example import FeedQuery from "./__generated__/FeedQuery.graphql", and list them, as in relayByNameAdapter(environment, [FeedQuery, RenamePostMutation]). An operation you leave out of the array can't run. The request carries the persisted id relay-compiler gave it, and the result lands in the store, so screens showing those records update. Relay runs only compiled operations, so this adapter works by name only. Relay rejects a response that carries errors and no data, and the adapter returns its errors as { data: null, errors }.
// Relay: look the operation up by name among your compiled artifacts and
// execute it through your own Environment — the request carries the
// persisted id relay-compiler gave it, and the result lands in the store,
// so screens showing those records update. Relay rejects a response that
// carries errors and no data; the adapter turns that back into the whole
// response.
import type {
ActionIntent,
ActionIntentGraphQL,
RequestActionsAdapter,
} from "@teaflask/assistant";
import {
type ConcreteRequest,
createOperationDescriptor,
type Environment,
} from "relay-runtime";
function graphqlOf(intent: ActionIntent): ActionIntentGraphQL {
if (intent.graphql === undefined)
throw new Error(`"${intent.action.title}" is not a GraphQL action.`);
return intent.graphql;
}
/** `artifacts` is an array of your compiled operations, the default exports
* of your `__generated__/*Query.graphql` and `*Mutation.graphql` modules:
* `import FeedQuery from "./__generated__/FeedQuery.graphql"`, then
* `relayByNameAdapter(environment, [FeedQuery, RenamePostMutation])`. */
export function relayByNameAdapter(
environment: Environment,
artifacts: readonly ConcreteRequest[],
): RequestActionsAdapter {
const byName = new Map(
artifacts.map((artifact) => [artifact.params.name, artifact]),
);
return {
kind: "request",
async execute(intent) {
const { operationName, operationType, variables } = graphqlOf(intent);
const artifact = byName.get(operationName);
if (artifact === undefined)
throw new Error(`No compiled operation is named ${operationName}.`);
const operation = createOperationDescriptor(artifact, variables);
const run =
operationType === "mutation"
? environment.executeMutation({ operation })
: environment.execute({ operation });
try {
return await run.toPromise();
} catch (error) {
// Relay's "No data returned" error keeps the response's errors.
const source = (error as { source?: { errors?: unknown } }).source;
if (Array.isArray(source?.errors))
return { data: null, errors: source.errors };
throw error;
}
},
};
}
Plain fetch
If your app sends operation strings with fetch, export them from one module and pass it to fetchByNameAdapter(endpoint, operations, init), with endpoint the URL your app posts its operations to and operations that module, for example import * as operations from "./graphql/operations". It sends the string named by the action as the request's query, byte for byte as your app wrote it, so an allowlist that holds your operation text or its hash accepts it. init takes your usual fetch options, such as credentials: "include" or an Authorization header, with headers in any form fetch accepts. It resolves the response's JSON whatever its status.
// Plain fetch with operation strings: export your app's GraphQL operation
// strings, and this adapter sends the one named by the action as its
// query, byte for byte the string your app wrote — so an allowlist that
// holds your app's own operation text (or its hash) accepts it.
import type {
ActionIntent,
ActionIntentGraphQL,
RequestActionsAdapter,
} from "@teaflask/assistant";
function graphqlOf(intent: ActionIntent): ActionIntentGraphQL {
if (intent.graphql === undefined)
throw new Error(`"${intent.action.title}" is not a GraphQL action.`);
return intent.graphql;
}
const operationNameOf = (text: string) =>
/^\s*(?:query|mutation)\s+([_A-Za-z]\w*)/m.exec(text)?.[1];
/** `operations` is your module of exported operation strings:
* `import * as operations from "./graphql/operations"`. `init` is your
* usual fetch options — credentials, and headers in any form fetch
* accepts (an object, a Headers, or [name, value] pairs). */
export function fetchByNameAdapter(
endpoint: string,
operations: Record<string, unknown>,
init: RequestInit = {},
): RequestActionsAdapter {
const byName = new Map<string, string>();
for (const value of Object.values(operations)) {
const name = typeof value === "string" ? operationNameOf(value) : undefined;
if (name !== undefined) byName.set(name, value as string);
}
return {
kind: "request",
async execute(intent) {
const { operationName, variables } = graphqlOf(intent);
const query = byName.get(operationName);
if (query === undefined)
throw new Error(`No exported operation is named ${operationName}.`);
const headers = new Headers(init.headers);
headers.set("content-type", "application/json");
const response = await fetch(endpoint, {
...init,
method: "POST",
headers,
body: JSON.stringify({ query, operationName, variables }),
});
// A GraphQL response is the answer, errors included, whatever its status.
return response.json();
},
};
}
When your API accepts only its own requests
The cookies and headers kinds post the intent's body as it is, with the operation's document as text. An API without an allowlist runs it. An API that accepts only its own registered requests refuses it, because it isn't the request your app sends. The same happens when a request adapter's printed text is refused.
When that happens, nothing runs. The agent learns that your API accepts only its own registered requests and that actions have to run through your app's own GraphQL client. It doesn't retry: it tells the user the action can't run from the assistant until your team connects the assistant to your app's GraphQL client. To fix it, use a request adapter that finds the operation by name.
Without an adapter
An assistant with no adapter still works. It answers questions and can still navigate and read the page if those are enabled. The agent knows it can't run actions on this page, so it asks the user to do the step themselves instead of trying and failing.
More resources
- Actions – registering actions, their schemas and their approval policies
- Tool views – drawing an action's result with your own components
- Identity – who the user is, a separate question from what they may do
- Install – passing settings on the npm package and the script tag, and the CSP entries