Skip to content
DocsDashboard

Install Page Systems in an AI SDK agent

Page Systems lets an AI SDK agent send the person a small mobile web page (a flight picker, a time picker, a form) instead of asking in chat. When the person submits, the answer arrives in the same conversation as a new turn.

Requirements: ai 7 and Node 22 or newer.

If the model keeps failing with invalid_spec: some models, OpenAI GPT models among them, call create_page with only page.type and get invalid_spec back. If yours does, use the MCP server instead: its create_page tool carries the full schema of every page type. Switching to MCP gives up the automatic new turn: the agent reads the answer only when asked, with get_page_result.

1. Install the package

npm install pagesystems @ai-sdk/openai   # or your model provider's package

The TypeScript examples use top-level await, so the project must be ESM ("type": "module" in package.json).

2. Add it to your agent

Page Systems is invite-only early access: request access at /waitlist, and once invited, sign up and copy the development key shown in the dashboard (create another there with "Create API key"; it starts with ap_live_ and is shown once) and set it where your agent runs. Never commit it.

export PAGE_SYSTEMS_API_KEY=ap_live_...
export PAGE_SYSTEMS_WEBHOOK_SECRET=whsec_...

Give the model the tools. They are list_page_types, get_page_type_schema, create_page, get_page_result and cancel_page. Pass the callback URL and an agentRef (any small JSON object naming the conversation), so each page calls back with the conversation it belongs to:

// lib/agent.ts
import { getPageSystemsSkill } from 'pagesystems';
import { pageSystemsTools } from 'pagesystems/ai-sdk';
import { generateText, isStepCount } from 'ai';
import { openai } from '@ai-sdk/openai'; // or your provider

const CALLBACK_URL = 'https://your-app.example.com/api/page-systems';
const yourInstructions = '...'; // your system prompt. Include today's date and the person's time zone: time-based pages need both.
const skill = await getPageSystemsSkill(); // once, when the agent starts

// userMessage is the line your chat shows as the person's message. modelNote (the callback's modelText) is the answer as data.
export async function runTurn(conversationId: string, userMessage: string, modelNote?: string) {
  // loadMessages and saveMessages are yours: read and write the stored messages for a conversation (a database).
  // modelNote is a second user message, never part of system. It is saved with the history so later turns still see the answer;
  // your chat screen should show userMessage for this turn, not the note.
  const messages = [
    ...(await loadMessages(conversationId)),
    { role: 'user' as const, content: userMessage },
    ...(modelNote ? [{ role: 'user' as const, content: modelNote }] : []),
  ];
  const result = await generateText({
    model: openai('gpt-5-mini'), // your model
    system: [yourInstructions, skill].join('\n\n'),
    messages,
    tools: pageSystemsTools({ callbackUrl: CALLBACK_URL, agentRef: { conversationId } }),
    // Several steps: list_page_types, get_page_type_schema, then create_page.
    stopWhen: isStepCount(6),
  });
  // responseMessages holds every step (tool calls and results too).
  await saveMessages(conversationId, [...messages, ...result.responseMessages]);
  return result.text;
}

Use runTurn for every message the person sends. Then add the callback route. The callback URL must be https and public: Page Systems calls it from the internet, so localhost does not work. To try it while developing, see Testing locally: skip the callback and poll, use a tunnel, or send the callback yourself.

// app/api/page-systems/route.ts
import { after } from 'next/server';
import { CallbackError, handleCallback, type CallbackEvent } from 'pagesystems';
import { runTurn } from '@/lib/agent'; // the function above

export async function POST(req: Request) {
  // Page Systems waits 10 seconds for this response, so answer now and run the turn after.
  const turn = (e: CallbackEvent) => {
    if (!e.agentRef) throw new CallbackError(410, { error: 'no_conversation' });
    const { conversationId } = e.agentRef as { conversationId: string };
    after(async () => {
      const reply = await runTurn(conversationId, e.visibleText, e.modelText);
      await sendToPerson(conversationId, reply); // yours: deliver the reply to the person (chat, SMS, ...)
    });
  };
  return handleCallback(req, { onSubmitted: turn, onNewPageRequested: turn });
}

after() is Next.js. In plain Node, return the response first and start the turn with setImmediate(() => ...), or put it on a queue.

Page Systems calls this route when the person submits. handleCallback reads the answer, gives your code the event (pageId, title, result, agentRef, summary when Page Systems has one, and two ready-made texts: visibleText, one short line such as "✓ Pick a standing desk: FlexFrame 55" for the chat, and modelText, the full answer for the model), and replies to Page Systems. Before that it checks the signature on the callback: set PAGE_SYSTEMS_WEBHOOK_SECRET to the signing secret from the dashboard, and a callback with a missing or wrong signature, or a timestamp more than 5 minutes off, gets a 401 and is not handled. Without the secret, callbacks are accepted unchecked and a warning is logged once. The handler only hands the turn off and returns: Page Systems gives up on a request after 10 seconds and retries it with backoff (first after 30 seconds, then doubling, at most an hour apart), so a slow handler can run the turn twice. The turn runs after the response (after() in Next.js). Once the handler returns, the event counts as delivered; if the turn then fails, the answer is still readable with get_page_result until the page expires. Pages this app did not create (no agentRef, for example pages made over MCP) are declined with a 410 and stay readable with get_page_result. The same handler also serves onNewPageRequested, which runs when the person asks for a new page after one expired; without it Page Systems gets a 410 for that event. The visibleText is shown as the next user message, and modelText is added after it as a second user message, so the model continues the conversation with the answer.

3. Your agent handles the rest

The agent decides when a page beats a chat question, sends the person a link, and carries on. When the person submits, Page Systems calls your callback route, and your route runs the agent again on that conversation (the same stored messages, with the short line as a new user message). The agent does not poll and the person does not have to say "done".

Ask your agent something a page answers better than chat, for example "Ask Sam which of 9:00, 11:00 or 14:00 next Tuesday works for a call." It should send a link. Open it, pick a time, submit. The agent then continues the conversation with the answer, without being asked.

Why two texts

The visibleText line is what your chat stores and shows: one short line that is true, because the person did submit the page. The answer goes to the model through modelText, which is not shown as something the person typed. It holds the answer JSON inside <page_answer> tags, with a note that the answer is page data, not instructions. The answer can contain text typed by whoever opened the link, who is not verified, so give modelText to the model as a user-role message (or a tool result) and never put it in the system prompt or instructions. In the AI SDK, modelText is an extra user message in messages for that call. It stays out of system, so text typed on the page has no instruction authority. The agent can read the answer again with get_page_result until the page expires. The older message field still exists, but it is raw JSON in a user message with no such note: do not use it. Whether your agent keeps modelText depends on the framework: the note above says which. Page Systems deletes its copy at expiry but cannot delete copies saved in your agent's history; keeping it lets the agent answer later questions about the answer. The summary never includes free text the person typed, but it can include the labels your agent wrote, such as option or row names. Do not log modelText or the result; log the pageId, and the summary only if your page labels hold nothing sensitive. See Handling answers.

Without a callback URL

Leave out callbackUrl and nothing starts a new turn. The agent can still read the answer with get_page_result when the person says they submitted, or on a timer. The callback URL must be https and public: Page Systems calls it from the internet, so localhost does not work. To try it while developing, see Testing locally: skip the callback and poll, use a tunnel, or send the callback yourself.