Skip to main content

Step 4 of 7: Add a primitive

By the end you will be able to:

  • Choose one platform primitive and wire it into your agent
  • Point at it in your code and say what it does in one sentence
  • Show the agent doing something a plain chat cannot

Use the Cloudflare account on your card (also on the Workspace page). No account yet? Ask a host: you can read on, but you can't deploy until it is ready.

The curl and PowerShell examples use $DEMO_URL (macOS / Linux) or $env:DEMO_URL (PowerShell): your demo URL from your card, set once per terminal in Step 1. Open a new terminal later? Set it again.

Why it matters​

  • A chat answers; an agent does something. One primitive is what lets your agent act when nobody is typing, wait for hours, read a live page, answer from your own documents or keep a file. That is the part of a demo people remember.
  • Each primitive replaces something you would otherwise build. A scheduler, a job runner with retries, a search index, a headless browser, a file store. Here each one is a single binding, with nothing to run and no API key to look after.
  • It is the same loop every time. Declare a binding, call it from a tool, check it with one command. Learn it once and the next primitive takes minutes.

A primitive plugs into the starter in two places: a binding in wrangler.jsonc (the bar along the bottom) and a call from tools() in the Durable Object. The Cloudflare platform lane on the right already holds Workers AI and the AI Gateway, which you reach the same way. The primitive you choose is one more product in that lane, reached from tools() through its binding. Click any box to see what it does.

Click a box or an arrow to see what it does.

The concepts​

A primitive is a Cloudflare product your agent uses through a binding. Adding one is always the same four moves: declare the binding in wrangler.jsonc (the starter has commented blocks ready), run npm run types, call it from a tool, then npm run deploy and test on your demo URL. Here is why each part is the way it is:

  • A binding is how your Worker is allowed to use a product. It is a name in wrangler.jsonc that appears as env.<NAME> in your code. There is no API key to store or leak, because the platform connects the two. A product you have not bound cannot be reached from your code at all.
  • npm run types catches typos early. It regenerates env.d.ts from wrangler.jsonc, so a wrong binding name becomes a type error at your desk instead of undefined in the middle of the demo.
  • Some bindings have no local emulator. AI Search and Browser Run always talk to the real service, so their blocks say "remote": true and npm run dev needs your wrangler login. That is also why every test below runs against your deployed demo URL, the same path your demo will use.
  • Use the shared names. You build in your own account, so there is nothing to collide with, and every account uses the same names: agent-workflow, agent-files, agent-docs, agent-db. The commented blocks in the starter already say so: uncomment them as they are. What you create here lives in your account and counts against its limits only.
  • Choose by the job, not by the product. Each primitive takes one specific chore off your hands. Pick the chore your demo needs and make that one work end to end: two half-working primitives make a worse demo than one that works.

Pick one​

Not sure which? Start with Option A: there is nothing to create, and the starter already has the schedule tools. Picked another option and it is not working? Switch to Option A rather than stay stuck.

Click a name to open its steps. Each one starts with why it exists, so you can check it is the right pick before you build.

OptionThe problem it solvesPick it when you want to showWhat you set up
A. ScheduleAn agent only acts when someone writes to itThe agent working on its own: a morning check, a reminderNothing new
B. WorkflowsA job of several steps falls over if one step fails or the request endsA job that retries, waits or pauses for a personA class and a binding. Your first deploy creates the Workflow
C. AI SearchThe model has never read your documents, so it guessesAnswers that cite your own runbookAn instance, a file and a binding
D. Browser Runfetch returns the HTML the server sent, not what a visitor seesReading or capturing a real pageA binding
E. R2Reports and screenshots are files, not table rowsThe agent leaving a file behindA bucket and a binding
Go deeper: background work, approvals and what else the SDK offers

You do not need any of this to finish the step. It helps you choose well, and shows what to reach for when your agent grows.

Queue, Schedule or Workflow?

  • A queue runs work as soon as it can, in order. Use it for work that should not block the reply but does not need to wait for a time.
  • A schedule runs at a time or on repeat. Cron schedules have a one-minute resolution; this.scheduleEvery(seconds, ...) repeats at a fixed interval and skips a run if the last one is still going. Retries are built in, and the schedule is stored in the agent's own database.
  • A Workflow is for several dependent steps. Each step is retried on its own, the whole job can run for minutes to hours, and it can wait for a person.
  • Cron Triggers run a Worker, not an agent. Prefer a schedule when the work belongs to one agent and its data.

Docs: Schedule tasks · Queue tasks · Cron Triggers

Wait for a person inside a Workflow

  • step.waitForEvent pauses until someone sends an event. The event is sent with instance.sendEvent({ type, payload }), and the type may only use letters, digits, - and _ (a . is rejected). The wait can be from one second up to 365 days, and defaults to 24 hours.
  • A timeout fails the whole instance, unless you catch it. Wrap the wait in try...catch when "no answer" should not end the job.
try {
const ok = await step.waitForEvent<{ approved: boolean }>(
"await approval", { type: "purge-approval", timeout: "1 hour" });
if (ok.payload.approved) await step.do("purge", () => purge(plan));
} catch {
// nobody answered in an hour: stop here, or carry on without the risky step
}
  • Step 5 is the in-chat version of this. Moving the gate into a Workflow lets a colleague approve later, even after the chat is closed.

Docs: Events and parameters · Workers API

Make a Workflow part of the agent

  • AgentWorkflow ties a Workflow to the agent that started it. You start it with this.runWorkflow(...). Inside, this.agent calls back into the agent, reportProgress and broadcastToClients update connected browsers, and waitForApproval pauses until the agent calls approveWorkflow().
  • Why you might want that. The Workflow's progress and result then appear in your chat page, and approval becomes a normal agent method. The plain Workflow in Option B is the simpler start.

Docs: Run Workflows from an agent

Ready-made tools for the browser and for search

  • The Agents SDK can hand your model browser tools. createBrowserTools (from agents/browser/ai) adds tools for Markdown, extraction, links, scraping and running code against a live browser. It needs the Browser Run binding and a Worker Loader binding.
  • AI Search can be bound to one instance. An ai_search block with instance_name binds a single instance and calls env.NAME.search(...) directly, with no get(). It cannot list, create or delete instances, and the instance must exist when you deploy.
  • The namespace binding you used reaches every instance in default. In your own account that is only your own instances. It still reaches all of them, so keep synthetic data in it.

Docs: Browser tools for agents · AI Search as an agent tool · AI Search Workers binding

Build it​

Do one option and only that one: pick its tab below (or click its name in Pick one). Every command can be copied as it is. Each command shows the system you picked on the Workspace page; where a command is the same on both, it is shown once. Each option has the same shape: why it exists, set it up, add a tool, deploy, test.

Why this one

  • The problem it solves. A chat agent only acts when someone writes to it. Real jobs ("check this every morning", "tell me when it is done") need the agent to start by itself.
  • Why it is built into the agent. The timer is saved in the agent's own database and wakes it with a Durable Object alarm, so it survives restarts and redeploys. When it fires, the agent runs with its own memory and tools, so there is nothing extra to connect.
  • Pick it when you want the demo to show the agent working on its own: a daily check, a reminder, a follow-up.
  • Watch out. A schedule runs one method with a small payload. For a job of several dependent steps, or one that runs for a long time, use Workflows (Option B).

What you will build. The Agents SDK can wake your agent later with this.schedule(when, callback, payload): when is a delay in seconds, a Date or a cron string. The starter already has the scheduleTask, getScheduledTasks and cancelScheduledTask tools. What it does not do is any real work: its executeTask only logs and sends a message. You will make it check a web page, save the result and tell the chat page.

Prefer to let your coding agent do the typing? Copy this prompt into your agent, in your starter folder.

Prompt for your coding agent

What your agent will do

  1. Adds a checks table in onStart().
  2. Rewrites executeTask so a scheduled task checks a page, saves the result and tells the open chat page.
  3. Adds a listChecks tool to read the results.
  4. Deploys, schedules a check in 60 seconds, waits, and reads the row your agent wrote by itself.

Key ideas to understand

  • this.schedule(): the starter's scheduleTask tool calls it. The timer is saved in the agent's own database, so it survives restarts and redeploys.
  • A callback by name: when the time comes, the agent wakes and runs the method named in the schedule, here executeTask, with its own memory and tools.
  • this.broadcast(): sends a message to every open chat page: the toast you see when the check runs.

The prompt ends by asking your agent to explain these in your own code. More in The concepts.

Paste it into your coding agent: the terminal, the IDE panel or the desktop app all work.

1. Add a table. Find the existing onStart() { line and paste these lines right after it, next to the notes table from Step 3 if you added it. Do not add a second onStart():

this.sql`CREATE TABLE IF NOT EXISTS checks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task TEXT NOT NULL,
result TEXT NOT NULL,
at TEXT NOT NULL
)`;

2. Replace executeTask, the last method of the ChatAgent class, with this. The schedule calls it by name when the time comes:

async executeTask(description: string, _task: Schedule<string>) {
// 1. Do the work: check the first web address in the task text.
const url = description.split(" ").find((w) => w.startsWith("https://"));
let result = "no web address in the task";
if (url) {
try {
const res = await fetch(url, { method: "HEAD", redirect: "follow" });
result = `HTTP ${res.status}, cache: ${res.headers.get("cf-cache-status") ?? "n/a"}`;
} catch (err) {
result = `failed: ${err}`;
}
}
// 2. Keep the result in the table from onStart().
this.sql`INSERT INTO checks (task, result, at)
VALUES (${description}, ${result}, ${new Date().toISOString()})`;
console.log(`Scheduled task: ${description} -> ${result}`);
// 3. Tell the open chat page (it shows as a toast).
this.broadcast(
JSON.stringify({
type: "scheduled-task",
description: `${description}: ${result}`,
timestamp: new Date().toISOString(),
}),
);
}

3. Add a tool to read the results, inside tools():

listChecks: tool({
description: "Show the results of the scheduled checks, newest first.",
inputSchema: z.object({}),
execute: async () =>
this.sql<{ task: string; result: string; at: string }>`
SELECT task, result, at FROM checks ORDER BY id DESC LIMIT 10`,
}),

4. Deploy, ask for a check in a minute, then read the result:

npm run deploy
macOS / Linux
curl -s -X POST "$DEMO_URL/api/chat" \
-H 'content-type: application/json' \
-d '{"message":"Use scheduleTask to check https://www.cloudflare.com/ in 60 seconds."}'
Or type it in your agent's chat page
Use scheduleTask to check https://www.cloudflare.com/ in 60 seconds.

Open your demo URL in a browser and paste this into the message box instead of running the command above. It is the same agent either way.

Wait about 70 seconds, then:

macOS / Linux
curl -s -X POST "$DEMO_URL/api/chat" \
-H 'content-type: application/json' \
-d '{"message":"Use listChecks to show the latest checks."}'
Or type it in your agent's chat page
Use listChecks to show the latest checks.

Open your demo URL in a browser and paste this into the message box instead of running the command above. It is the same agent either way.

What this does: the first call stores a timer inside your agent. A minute later the agent wakes by itself, runs executeTask and saves a row. You should see: a reply saying the task is scheduled, then a row such as HTTP 200, cache: n/a. Any HTTP status means it ran.

To see the toast, keep the chat page open on your demo URL while the check runs: it appears there even when you scheduled it with curl. npx wrangler tail shows the console.log line either way.

Docs: Schedule tasks · Cron and queues: Queues · Cron Triggers

Check it worked​

For the option you chose:

  • A, Schedule: listChecks shows a row that your agent wrote by itself, a minute after you asked, while nobody was typing.
  • B, Workflows: describe shows the run with all three steps, and the dashboard shows the same steps as a diagram. The job ran outside the chat and would have survived a crash.
  • C, AI Search: the answer comes from your document and names cache-runbook.md. Ask something the document does not cover and compare the two answers.
  • D, Browser Run: the reply describes text that is on the page right now, not a guess from the model's memory.
  • E, R2: the last command prints your report straight from the bucket. It is still there after a redeploy.

And for everyone: you can point at the binding in wrangler.jsonc and the tool in src/server.ts and say in one sentence what the primitive does.

Stuck?
  • env.X is undefined, or a type error says it does not exist on Env. The binding name in wrangler.jsonc must match the name in code. Run npm run types and redeploy.
  • A create command or the first deploy is refused (code 10000). Your role in your own account should be Super Administrator; if it is not, or the product is not enabled on the account, you cannot create that resource. Tell a host, who checks your role and the product in your account. Meanwhile switch to Option A, which needs no new resource.
  • Wrangler asks you to register a workers.dev subdomain when you deploy the Workflow (B). The hosts gave every account one, so check account_id first. If it is right, open Workers & Pages in the dashboard once (that creates it) and deploy again (it is only the account's subdomain; your Worker stays off workers.dev).
  • wrangler ai-search create says there is no AI Search API token (C). AI Search needs one account-level token and a new account has none. Create it once: dashboard > AI Search > API Tokens > Create Token (the error message prints the link), then run the command again. If Create Token is missing or refused, tell a host.
  • "Already exists". You already created it in your own account: reuse it with the same name (agent-files, agent-docs, agent-workflow) instead of creating it again. If you ran the commands in another account by mistake, check account_id in wrangler.jsonc.
  • A remote binding errors in npm run dev. AI Search, Browser Run and the AI binding talk to the real service; make sure npx wrangler login is done and account_id is your own account, or test on your demo URL.
  • The model never calls your tool. Same fix as Step 2: name the tool in your prompt ("Use searchDocs: ...") and make its description say when to use it.
  • no such table: checks (A). The CREATE TABLE must be inside onStart(). Check it and redeploy.
  • The schedule never fires, or errors (A). Ask for getScheduledTasks, and check that the callback name is exactly executeTask. A name that does not match a method throws. If you ask for a time of day, say the time zone in your prompt.
  • Workflow not found or class error (B). class_name in wrangler.jsonc must match the exported class exactly, and the class must be exported from src/server.ts. Run npm run types and redeploy.
  • AI Search returns nothing (C). Check indexing with the stats command, and that the instance name in the code is the one you created (agent-docs).
  • Browser Run fails on a page (D). Use a public page and try again. It cannot sign in to anything.
  • Stuck on another option? Switch to Option A: it needs no setup, and you can come back later.
Go further
  • Combine two. A schedule that starts a Workflow, or Browser Run screenshots saved to R2. For the second, remember that quickAction returns a Response, so read it before storing: await this.env.BUCKET.put(key, await res.arrayBuffer(), { httpMetadata: { contentType: "image/png" } }).
  • D1 (a shared SQL database) and KV (fast config) are in the Platform Guide if step 3 was not enough.
  • Sandbox SDK and Containers run code the model wrote; heavy for a three-hour build, fun for a demo. See the Platform Guide.
  • Every primitive in one map: Platform Guide. Optional reading, nothing here depends on it.

Finished step 4?

Checking your team…


Back: Step 3: State and memory. Next: Step 5: Human approval.

Need help? Raise a hand for a host, or ask the Mentor dock (it escalates to a host when unsure).