Writing an agent
The class: config, state, stages, tools, hooks, the call, the panel, and what is refused when it loads.
An agent is one TypeScript class, the default export of agents/<slug>/agent.tsx. Everything the
model can see about it comes from four places: the docstring above the class, what the class
declares, the docstrings of its tools, and render().
import { Agent } from "@pinecall/agents";
/**
* You are the front desk of Clínica Norte. Formal, short sentences.
* Everything you say is read aloud: no lists, no markdown.
*/
export default class ClinicaNorte extends Agent {}
That docstring is the identity block of the prompt — the first of the static blocks, which never
change during a call and are what a provider caches. Write it as instructions to a person, not as
documentation. It must be a /** … */ comment directly above the class: the CLI hands the class
its own source, so the comment survives compilation. @agent({ doc: "…" }) says it instead, for a
build that strips comments.
@agent: what the agent is#
Declared once, above the class, because it is not something the agent remembers: it never changes
during a call and no view renders it. The class under it holds what the agent does: its state, its
hooks, its tools and its render().
import { Agent, agent, tool } from "@pinecall/agents";
/** You are the front desk of Brightside Dental. Keep it short. */
@agent({
stt: "deepgram/flux-general-en",
llm: "google/gemini-3.5-flash-lite",
voice: "cartesia/f786b574-daa5-4673-aa0c-cbe3e8534c02",
timezone: "America/Los_Angeles",
judges: ["consent", "grounded"],
})
export default class FrontDesk extends Agent {}
There is one way to say it. A class that writes one of these as a static field, or as an instance
field, is refused when it loads, by a sentence that names the field and @agent. A class that
extends another keeps what its parent declared, and its own @agent declares over it field by field.
channelRules, on the instance, is the one setting written in the class: how the agent writes on a
channel. channelRules = { whatsapp: "…", sms: "…" } says its own words for those in place of the
framework's, and a channel it leaves out keeps the framework's (voice, a spoken call; chat, a
website's written chat; whatsapp; sms). channelRules = false leaves the <channel> part out of
the prompt on every channel.
The environment: the settings', or the class's#
Everything the agent runs on — the voice, the models, the language, the greeting, what it knows
by heart, what it remembers — is the class's. An app written as code is set by its code and nothing
else: the console's Setup shows what it runs on, read-only, and pinecall agent set and every other
verb that writes one agent's settings refuses an app, naming it. Change the class and deploy. A stage
the class leaves out runs on the org's default vendor for it and that vendor's default model; a field
left out reads as the runtime's default. The settings those verbs write belong to an agent built in
Studio, which has no code.
A model is "vendor/model" or a vendor alone, and a voice is "vendor/voice", the vendor and its own
id for the voice. A stage that takes options is an object with them:
@agent({
voice: { voice: "cartesia/a0e99841-438c-4a64-b679-ae501e7d6091", model: "sonic-2" },
llm: { model: "openai/gpt-5.4-mini", temperature: 0.3, builds: "responses.LLM", options: { use_websocket: true } },
stt: { model: "soniox/stt-rt-v3", endOfTurn: "smart-turn" },
language: "es",
greeting: "Clínica Norte, buenas, ¿en qué le ayudo?",
hangup: "the caller says goodbye or needs nothing else",
})
export default class ClinicaNorte extends Agent {}
timezone is the IANA zone the agent's day and clock are read in: the model is told the date, the
weekday and the hour there as the call opens, and this.call.today is that day. Left out, the day is
the gateway's own and the model is told no hour.
greeting is the words, said as written — instant, and no model runs — or the model's own:
improvise opens on the prompt alone, improvise("Greet them by name if you know it") with an
instruction for the opening. The caller cannot cut it short unless it says so:
improvise("…", { interruptible: true }), or { text: "…", interruptible: true } for words.
hangup is when the model may end the call, in your words, or true whenever it judges the call
done. stt also takes endOfTurn, who says the caller's turn is over: "stt" the ears
themselves (Deepgram Flux; refused for ears that cannot), "livekit" or "smart-turn" (Smart Turn
v3), a model on the worker that runs on any key. Left out, the ears end the turn where they can and Smart Turn v3 does everywhere else.
judge names the model the agent's calls are judged on, over the org's choice and the platform's:
on a key of your org's own its evals are never billed, a local model included —
judge: { model: "openai/qwen3-32b", options: { base_url: "http://gpu:8000/v1" } } — and it must call
tools, since every judge answers through one.
llm, stt and judge take vendor/model or a vendor alone; voice the vendor and its own id for the
voice. Each takes builds, a class of the vendor's livekit plugin other than its default (dotted
names reach a module of it: responses.LLM is OpenAI's Responses API, and use_websocket its
WebSocket), and options, that class's keyword arguments as the plugin names them, passed as given
and over the operator's. Both run only on your org's own key for that vendor: on a key Pinecall
lends they are refused at registration, naming pinecall providers add <vendor>, since an option
can point the plugin at another server. llm also takes temperature, which runs on any key. A
model that hears and speaks itself is not an llm: realtime: { model: "xai/grok-voice-3.0", options: { voice: "eve" } } runs the agent's voice calls — phone and web — on it alone, with no ears and its
own voice, while the llm keeps answering the written ones; pinecall providers lists the
vendors' realtime models, its options run on your org's own key alone, and an llm that names
such a model is refused at registration. A realtime model that says given words itself (xAI's Grok does) is the call's only voice: the recording notice, a greeting given as words and a confirmation's read-back are said by it, in its own voice; one that cannot leaves them to the agent's voice, and the call then has two. A vendor that is not installed, or does not do the stage, is refused at registration. A stage
the class declares is fixed whole: with llm in the class, --temperature, --llm-builds and --llm-option
are refused too. A class that leaves the stage out runs it on the org's default vendor and that vendor's default model.
| field | what it is | in @agent({ … }) |
|---|---|---|
slug |
the name the agent registers as; left out, the folder's name under pinecall start, or the class's name in kebab-case (ClinicaNorte → clinica-norte) under mount. A class served under another slug is refused |
slug: "front-desk" |
voice |
the voice: its vendor and the vendor's id | voice: "<vendor>/<id>" · { voice, model } |
llm |
the model that answers, and its temperature | llm: "<vendor>/<model>" · { model, temperature } |
realtime |
the model a voice call runs on alone, hearing and speaking itself | realtime: "<vendor>/<model>" · { model, options } |
stt |
the ears, and who ends the caller's turn | stt: "<vendor>/<model>" · { model, endOfTurn } |
judge |
the model its calls are judged on | judge: "<vendor>/<model>" · { model, options } |
language |
the language the call is in | language: "es" |
timezone |
the zone its day and its clock are read in | timezone: "America/Los_Angeles" |
greeting |
how the call opens: the words, or the model's own | greeting: "…" · improvise · improvise("…") |
hangup |
whether the model may end the call itself, and when, in your words | hangup: "…" · true |
turn |
when the caller has finished, and may interrupt | turn: { endpointingMs: 300 } |
says |
how a word the voice would misread is said | says: [{ word, spoken }] |
hears |
the words the ears must know: names, brands, the doctor's surname | hears: ["…"] |
memory |
what to remember about a caller across calls, and what never to | memory: { remember: […], forget: […] } |
record |
whether the call is recorded | record: false |
maxDuration |
the longest a voice call runs, in minutes, or "off" |
maxDuration: 20 |
llmTimeout |
how long a turn waits for the model's first word, in seconds | llmTimeout: 8 |
silenceTimeout |
seconds of the caller saying nothing before a voice call ends, 5 to 3600 | silenceTimeout: 30 |
idle |
what it says when the caller goes quiet | idle: { says: ["Are you there?"], afterS: 7.5, times: 3 } |
voicemail |
on a call it placed, the words left on a machine, or true to leave nothing |
voicemail: "Please call us back." |
sttFallbacks · ttsFallbacks |
who takes over when the vendor fails, in order | ttsFallbacks: ["cartesia"] |
knowledge |
what the agent knows by heart: a page of Markdown, read whole on every call | knowledge: { path, text } |
docs |
the base the agent searches per turn; declared, the folder agents/<slug>/docs/ is pushed into it when the agent registers |
docs: { base: "…", k: 4 } |
bases |
several bases, in place of docs; each pushed on its own (pinecall docs push --base) |
bases: [{ base: "faq" }, { base: "prices", k: 2 }] |
monitors |
numbers of its calls it watches: each fires, once a day, on the agent's log and your webhook when it crosses its line | monitors: [{ name: "slow", metric: "e2e_median_s", above: true, threshold: 2 }] |
hold |
the hold melody: a file beside the class and the wait before it, or silence | hold: { file: "hold.mp3", afterS: 1.5 } · "off" |
widget |
how the widget presents the agent | widget: { title, tagline, greeting, accent, autostart, theme } |
judges |
which of Pinecall's judges its calls meet, and its own | judges: ["consent", …, offersNextSlot] |
takes |
what it takes when a teammate passes it a call, in words the model reads | takes: "a question about a charge" |
tasks |
what a tool may stop to ask the caller for | tasks: [GetEmail] |
scenes |
the scenes of the caller's screen, each with what it shows | scenes: { agenda: "the open times you last read" } |
events |
the outside events the agent takes, and from whom: app is your backend, participant a browser in the call |
events: { "slot.released": { from: ["app"] } } |
The judges are the class's the same way, and they are code. judges is a list: a name is one
of Pinecall's judges the agent's calls meet (every other off), an object is one of the agent's own,
an ownJudge({ name, asks, answer, choices, when, trigger, reads }): the question the judge model
answers about a finished call, and how and when. pinecall new writes the agent's own in
agents/<slug>/harness.ts, imported by the class:
// agents/front-desk/harness.ts
import { ownJudge } from "@pinecall/agents";
export const offersNextSlot = ownJudge({ name: "offers-next-slot", asks: "Did the agent offer the next free slot before the caller asked twice?", reads: ["facts"] });
The callers the agent is tested with are code too, and they live with its tests, in
agents/<slug>/test/personas.ts, beside the goldens. The class does not name them and does not
import the file: the serve entry reads it when it loads the class. Every ownPersona({ name, goal, style, about, facts, expects, behavior, … }) the file exports is one of the agent's own, what
PUT …/personas/{name} takes, and its on names the ones of Pinecall's that pinecall simulate
plays (every other off):
// agents/front-desk/test/personas.ts
import { ownPersona } from "@pinecall/agents";
export const on = ["in-a-hurry", "wrong-number"];
export const hurried = ownPersona({ name: "hurried", goal: "leave a message: the delivery has to come after 4 pm", style: "short sentences, interrupts", expects: ["The agent should write the message down."], behavior: { interrupts: 0.3, pauseS: 1 } });
A wrong one is refused when the class loads, by a sentence that names it (offers-next-slot: a judge that answers one of several needs at least two choices), and so are two of one name.
Declared, the code is the agent's list: the console shows both locked, and pinecall judges add
or personas add is refused saying where they are written; pinecall judges pull writes code into
harness.ts, and personas pull and personas generate --save into test/personas.ts, where a
caller plays from the moment it is written. A class that declares no judges, and an agent with no
test/personas.ts, leave each to the console and the CLI, as before. The org's own judges
(pinecall judges add --org) meet every agent's calls either way.
personas: [...] in @agent({ … }) was the callers' place before, and it still plays for an agent
with no test/personas.ts: pinecall start says once where they moved. The two together are
refused (FrontDesk declares personas in @agent({ … }) and …/test/personas.ts holds them too).
Neither a fact the agent remembers nor a chunk of a base ever reaches the prompt. Both arrive
as a tool result, in the history, where a model reads them as information rather than as an
instruction. A tool that searches calls this.knowledge.search(…); the class says nothing else
about it, and a class that reads this.knowledge is refused at registration when no base is
attached, rather than at the first turn.
State: what it remembers#
Every own field of the instance is state, and so is every getter. Each call gets its own instance, so field initializers run once per call and two callers never share a list.
import { Agent, state, type Stages } from "@pinecall/agents";
export default class ClinicaNorte extends Agent {
@state stage: Stages<"identify" | "choose" | "book" | "done"> = "identify";
@state({ pii: true }) patient?: Patient | undefined;
@state slots: Slot[] = [];
@state proposed?: Slot | undefined;
get identified() { // derived: in every snapshot, assigned by nobody
return this.patient !== undefined;
}
private agenda() { // a method is a collaborator, never state
return new Agenda();
}
}
stageis typed withStages<…>, which names its values once: a tool'sstageuses the same words, and a misspelled stage is a compile error.@statesays who may see a field:@state({ pii: true })masks it in the log,@state({ visibility: "public" })lets a participant's browser read it, and bare@stateis the default,tenant. Decorating one field decides them all: a class with no@statehas every field as state, and a class with any has those and nothing else. An undecorated field is then scratch space, out of the prompt, the log and goldens —stageincluded, so the tools it gates would never show. Decorate every field, or none.- A getter is state, read every time the state is copied. A collaborator belongs in a method.
Tools and hooks are the only writers. Once the agent is sealed — every call seals its instance —
a write anywhere else throws UnauthoredWrite:
state field patient was assigned outside a tool and outside a lifecycle hook; tools are the only writers of state
Every write is recorded with its author — the tool's name, hook:onCall, event:<name> — carried
by AsyncLocalStorage, so two calls served at the same moment never read each other's.
this.collapse("…") replaces the record with one sentence; this.log(name, data) writes a line of
your own into the call's log.
Tools: what the model may do#
/** Finds the patient's file by their full name and phone. Call it only once you have both. */
@tool({ stage: "identify", pii: ["name", "phone"] })
async findPatient(name: string, phone: string): Promise<Patient | null> {
this.patient = await this.agenda().find(name, phone);
if (this.patient) this.stage = "choose";
return this.patient ?? null;
}
The docstring is what the model reads to choose the tool, joined into one line. The signature is
the schema it fills: string, number, boolean and arrays of them are typed; an interface or a
type declared in the same file is read field by field; an optional parameter is not required. What
the model sends is checked against it before the method runs.
| option | what it does |
|---|---|
stage |
visible while the state is in this stage, or one of these: stage: ["choose", "book"] |
when |
a question asked of the state on every change: when: (s) => s.slots.length > 0 |
confirm |
the sentence said after the tool runs. This is what makes a tool irreversible on the wire; {{result.x}} names a field of what it returns |
announce |
Deprecated: it still works, but it is no longer recommended. What the agent says as the tool starts ("Let me check the agenda."), when the model's turn said nothing itself and wrote no line of its own in the argument say every tool carries; a turn that spoke first is not announced twice. No tool declares an argument named say |
delayed |
what the agent says when the wait has grown long, 5 seconds in unless delayedAfter says otherwise; failed, what it says when the tool failed, before the model reads why |
quiet |
a move on the caller's screen, such as a pointer: it runs as the model calls it, while the words of that answer still play, and the model is asked for no answer of its own. Without it, every tool's result is a turn the model answers |
preview |
how many items of a list the model sees. The state keeps every one |
pii |
the parameters that carry personal data: the log masks their values wherever the agent wrote them down (state.changed, tool.result and a line you log too), and pinecall start prints the log's version. A callback's number is what the callback is for, so callback.requested keeps it in the clear |
timeout |
how many seconds the platform waits for this method: 30 unless set, 300 at most |
params |
an explicit zod schema, when the signature is not enough: import { z } from "@pinecall/agents" |
A tool that throws does not crash the call: its message becomes the tool's result, marked as an
error, and the model reads it. Throw a sentence a model can use — "Tuesday has no free slots" —
never a stack trace. And ask the model for a word, not a record: book(slot: string), looked up
among the slots it was offered, is safer than book(slot: Slot).
A tool that asks: tasks#
import { Agent, GetEmail, agent, tool } from "@pinecall/agents";
@agent({ tasks: [GetEmail] })
export default class FrontDesk extends Agent {
/** Book a time, once the caller said yes to it. */
@tool()
async book(slot: string) {
const email = await this.ask(GetEmail);
return clinic.book(slot, email);
}
}
A task is one thing a tool needs from the caller before it can finish. await this.ask(GetEmail)
stops the tool there: the model is told what is missing and how to ask for it, asks the caller,
and gives the answer with a tool of the task's own (give_email), the only tool open meanwhile.
The task checks what it was given, and one that does not pass is asked for again. Then your tool
goes on from the await with the value, and what it returns is what the model reads, as
{ finished: "book", result }. A tool may
ask more than once, one question at a time.
Three come with the package: GetEmail (an address, lowercased), GetPhone (the digits, with the
+ of a country code) and GetName ({ first, last }). One of your own is task:
import { task } from "@pinecall/agents";
export const GetPlate = task({
name: "plate",
asks: "the plate of the car",
how: "Read it back letter by letter.",
fields: { plate: "The plate, letters and digits, no spaces." },
check: ({ plate }) => {
if (!/^[A-Z0-9]{5,8}$/i.test(plate)) throw new Error(`"${plate}" is not a plate. Ask for it again.`);
return plate.toUpperCase();
},
});
fields is what the model gives, each a string with what it is; check returns what your tool is
handed, and what it throws is told to the model. A class names the tasks its tools ask for in
@agent({ tasks }): each one's tool is declared with the agent, and this.ask of one that is not named
is refused. A call that ends with a question open rejects the await, so the tool does not go on.
The hooks#
override async onCall(call: Call) { // a call started; writes here are authored by the hook
this.patient = await this.agenda().byPhone(call.from ?? "");
if (this.patient) this.stage = "choose";
}
override onEnd(call: Call) { // a line logged here still lands, though the call is over
this.log("outcome", { stage: this.stage });
}
override onEvent(name: string, data: Record<string, unknown>, meta: EventMeta) {} // an accepted outside fact
override onMemory(ops: MemoryOp[], call: Call) {} // memory read or written: each op's `op` and `facts`
After onEnd the SDK sends call.done, and the gateway waits for it, up to three seconds, before it seals
the call: a log is closed to lines once sealed, so a line onEnd logs later than that is refused, and the
gateway's journal names it.
A hook that throws fails its call and no other: the call's log gets a hook.failed line naming the
hook (and the event, for onEvent) and the error, stderr one line, and the call goes on with what the
hook had written.
onCall runs before the first prompt goes out, so the model never reads a state the call was not
in; the state a golden or a persona opens the call in is applied after it, so the hook never
overwrites it. An outside fact reaches onEvent only if the class declared the pair in
@agent({ events }): an event declared from: ["app"] that arrives from a browser is somebody else's
event with your name on it, and the hook never sees it.
Before the first call: static onServe#
A class can publish something for the pages that show it, once its agent is registered and before any call: lines recorded in its own voice, which a page plays with no call, and a JSON document any page reads with no key.
static override async onServe(serve: Serve) {
const lines = await serve.record(["Welcome to Brightside.", "Pricing is simple."]);
await serve.publish("welcome", { lines: lines.map(({ url, words }) => ({ url, words })) });
serve.say(`welcome recorded · ${lines.length} lines`);
}
record answers each line's MP3 URL, its length and when each written word is said; a line the
agent recorded before, in the same voice, costs nothing, so onServe runs again on every reconnect
as it is. publish replaces the document under its name; a page reads it at
GET /v1/agents/{slug}/public/{name} with no key (?env=sandbox for the sandbox's), so put there only
what the page would show anyway. say writes one line in the terminal of whoever started the agent.
A throw is reported, and the agent serves its calls all the same.
The voice app: the project's lines#
A project may have an app.ts beside agents/: its voice app. It says which agent answers each of
the project's numbers, the words a call on that line opens with, and what every agent of the app
says to a caller who went quiet. It is optional: an agent alone answers its number as before.
// app.ts
import { voiceApp } from "@pinecall/agents";
import FrontDesk from "./agents/front-desk/agent";
const app = voiceApp("brightside", { timezone: "America/Los_Angeles" });
app.line("+1 415 555 0134", { answers: FrontDesk, greeting: "Brightside Dental. How can I help?" });
app.silence({ after: "8s", say: "Are you still there?", times: 2 });
export default app;
timezone is the zone every agent of the app reads its day and its clock in, the same setting as a
class's timezone. pinecall start finds the file at the project's root and serves the agents with it; a save of it
reloads them. app.line(number, FrontDesk) is the short form, with no greeting. The greeting is said
as written, by the agent, before any model runs: it is that agent's greeting, declared by the app,
and silence is its idle. A class that declares greeting or idle itself and gets
one from the app too is refused when the app loads, naming both, since a call runs on one of them.
The app's page#
app.page("ui/dist");
An app may have a page of its own: the folder its build writes, inside the project. pinecall deploy
sends the folder with the release, and Pinecall serves it at the app's own name,
https://<app>--<org>.app.pinecall.io (--sandbox after the org in the sandbox). A visitor of it
reaches the agent of the app's first line, or the one app.page(dir, { answers: Billing }) names.
app.page(dir, { only: "sandbox" }) keeps the page to one environment ("sandbox" or
"production"): a deploy to the other sends the app alone, with no page.
The page needs no server and holds no key. It asks its own name for its ticket
(POST /pinecall/token), for the code a visitor keys from a phone (POST /pinecall/code) and for a
dictation into one of its fields (POST /pinecall/dictation), and Pinecall answers each, so many
a minute from one address. With @pinecall/room that is room({ ...hosted() }), and hosted().dictation. While
you write it, pinecall start serves the same folder and the same routes on
http://localhost:4747 (PINECALL_PAGE_PORT names another port), with your own key, so
a dev server of yours only has to pass /pinecall on to it.
A page has no caller id: call.contact is empty for its visitors. What the page knows of them it
says with an event the class declares, as any page does.
What the app hears#
app.on("visit.booked", async (call, visit) => {
await reminders.schedule(visit);
});
app.on("call.ended", async (call, ended) => {
await db.calls.insert({ call: call.id, agent: call.agent, reason: ended["reason"] });
});
app.on(name, handler) runs the handler on every entry of that name on a call of the app's agents.
The name is an entry of the call's log by its type (call.started, call.ended, call.score, handoff
for a pass and routed for a line's choice), or a line an agent logs by its own name:
this.log("visit.booked", visit) in a tool is what the first handler above hears. The handler is
told the call (id, agent) and what the entry carries. One that throws is said in the terminal,
and the others run. The handlers run in the process that serves the agents: an entry of a call logged
while it is down is not heard later. What has to outlive the process is a flow.
A flow: what outlives a call#
An agent only a flow uses (one it calls, texts or reads with, and that answers no line) is held with
app.agent(Reader): it is served by the app like a line's agent, and step.extract(text, Schema, { agent: Reader })
runs on its account.
import { flow } from "@pinecall/agents";
const remindVisit = flow("remind-visit", async (visit, step) => {
await step.sleepUntil(String(visit.at), { before: "24h" });
let called = await step.call(String(visit.phone), Reminder, {
instruction: `Remind ${visit.patient} of the visit tomorrow at ${visit.time}.`,
});
if (!called.answered) {
await step.sleep("2h");
called = await step.call(String(visit.phone), Reminder);
}
await step.run(() => db.visits.update(visit.id, { reminded: called.answered }));
}).cancelOn("visit.cancelled", (gone, visit) => gone.id === visit.id);
app.on("visit.booked", remindVisit);
A flow is a name and a function of what started it and its steps. app.on(name, flow) starts a run
of it on every entry of that name, with what the entry carries as its input, once per entry however
many processes hear it. The function runs in the process that serves the agents; the gateway keeps
the run: a journal of its steps, and the time, the event or the call that wakes it. So a run
outlives a deploy, a crash and a night with nothing running: when a process of the app is up, the
gateway hands it the runs that are ready.
| step | what it does |
|---|---|
step.sleep("2h") |
the run sleeps: a number and s, m, h or d |
step.sleepUntil(at, { before }) |
until a time, a Date or an ISO string, or that long before it |
step.call(to, Agent, { state, metadata, greeting, instruction, from }) |
the agent calls the number, as pinecall dial does, and the step answers how the call ended: { answered, reason, call }. A dial the org's guards refused answers at once with { answered: false, refused, message } |
step.text(to, Agent, words, { from, subject, metadata, instruction }) |
the agent sends the contact one SMS first, as pinecall text does, or, to an address, the first email of a thread under subject (step.text(to, Agent, { subject, instruction }) leaves its words to the agent), and the step answers at once: { sent, call, from }, or { sent: false, refused, message } |
step.template(to, Agent, name, { language, variables, from, text, metadata }) |
the agent sends the contact one WhatsApp template, as pinecall template does: approved at Meta in language, its body filled by variables in order; text, what it says once filled, opens the contact's conversation as its first turn, with metadata; answers { sent, simulated, messageId, from, call }, or { sent: false, refused, message }. In the sandbox it is answered simulated and never sent |
step.extract(text, Schema, { agent, instructions, model }) |
a model reads text into the zod object Schema (or a JSON Schema of an object) and the step answers with it, parsed: no call is opened and nothing is listed among the calls; the request is one written turn, on agent's org's keys or the ones the platform lends. Throws ExtractRefused (refused, message) when no key runs the model, the messages ran out, or it would not answer by the schema |
step.waitFor(event, { match, within }) |
the run waits for an event sent to the app whose data has what match names; it answers the event's data, or null once within passed |
step.run(() => …) |
runs your own code once and keeps what it returned |
step.emit(name, data) |
sends an event to the app |
Each time a run is woken its function is called again from the top, and every step already in the
journal answers what it came to without doing it again. Two rules follow. What must happen once
goes inside step.run: a write to your database, a text message, anything outside the steps runs
again on every wake. And the function reaches its steps in the same order every time: a run whose
function asks for another step than its journal holds is failed, saying which.
cancelOn(event, when) cancels the runs still waiting when an entry or an event of that name comes
and when(event, input) is true for the run's input. A call a run placed is not ended by it.
An event is sent to the app with step.emit, or by your own backend with
POST /v1/apps/{app}/events and the project's key: { "name": "lab.ready", "data": { … } }. The
gateway keeps it until a process of the app heard it, so one sent while nothing runs is heard when
something does. It reaches app.on(name, handler), starts the flows of that name and wakes a
waitFor. A line an agent logs starts a flow and cancels one, and wakes no waitFor.
A step is written within a minute of the run being handed out: a step.run that takes longer may
be run by another process of the app too. A function that throws fails its run, with what it
threw; the terminal says so. A run sleeps or waits 90 days at most, an org has 10000 runs waiting at
most, and what starts a run or rides an event is 16 KB of JSON at most: an id and a few facts.
A rule every agent keeps#
app.rule("Never quote a price that is not in the price list.");
A rule is read into the prompt of every agent of the app, and a judge asks of each call whether it
was kept: the call's score says so, as it does for the judges a class declares. The judges are named
app-rule-1, app-rule-2, in the order the rules are written. A rule's judge reads the call and its
evidence (the documents searched, the tools' answers, the state), so a rule about what the agent may say
is held to what the call gave it. An agent's declared judges are its
whole list, so an app with rules owns the list of each of its agents: name the ones of Pinecall's you
want beside them in the class, @agent({ judges: ["grounded"] }).
A team: the call passed from one agent to another#
A line may name a team, the agents its call can pass to. Each says what it takes, in the words a model reads to choose it:
// agents/billing/agent.tsx
/** You handle charges, invoices and refunds for Brightside Dental. */
@agent({ takes: "a question about a charge, an invoice or a refund" })
export default class Billing extends Agent {}
app.line("+1 415 555 0134", { answers: FrontDesk, greeting: "Brightside Dental. How can I help?", team: [Billing] });
The agent on the call is offered one tool per teammate, named by its class (transfer_to_billing for
Billing), and the model calls it
when the caller asks for that; a caller who only says hello is passed to nobody. A tool can pass the
call itself, with what the next agent should know:
/** The caller disputes a charge and names the invoice. */
@tool()
disputeCharge(invoice: string) {
return this.call.handoff(Billing, { invoice });
}
From the pass on, the call is the teammate's: its instructions, its tools, its state, and its onCall,
where this.call.handed is what it was handed. this.call.shared is an object the agents of one call
share: what the first one wrote there, the next one reads. The conversation so far stays with the call,
and the pass is a handoff line on its log. A call is passed three times at most; the fourth is
refused and the agent answers itself.
Two things to know. The agents of a team give each tool a name of its own, or the app is refused when it loads. And the gateway still knows the call by the agent that answered it, which is where it is listed and judged.
A spoken call takes the model and the voice of the agent it was passed to: the llm and
the voice that class declares, or what its settings say. The sentence being said ends in the voice it
began in, and the next one is the teammate's; each stage that changed is a stage.changed on the
call's log. The ears stay the first agent's for the whole call. A written call has one stage, its model, and takes
the teammate's the same way.
A line that chooses who answers#
answers may be a function. It runs as the call comes in, while the caller hears the greeting, and
returns the agent of the team that serves this call:
app.line("+1 415 555 0134", {
greeting: "Brightside Dental. How can I help?",
answers: async (call) => {
if (clinic.isClosed(call.today)) {
return AfterHours;
}
return FrontDesk;
},
fallback: FrontDesk,
team: [AfterHours, Billing],
});
fallback is the agent the number is pointed at. It answers when the function returns nothing,
throws, takes more than a second, or names an agent that is not of the line's team; then the call's
log has a routed line saying why. The function is handed the call as a hook is: id, contact,
from, to, channel, today, and what the call was opened with.
The number stays your org's: pinecall numbers points it at the agent. A line whose number the
gateway does not route to its agent is said once in the terminal, and the agent serves its other
calls all the same. An agent that answers two lines opens both with the same greeting, or with none.
The call#
Inside a tool, a hook or render(), this.call is the live call; outside one it throws.
await this.say("One moment, let me check."); // true once the turn lands, false after 30 s
await this.reply("Tell them it is booked."); // the model speaks, guided by words nobody hears
this.call.send("cart", { total: 42 }); // a payload to the browsers in the room
this.call.participant(identity).mute(); // and .remove()
this.call.invite("+34910000001", { kind: "sip" }); // a phone leg into the call
await this.call.transfer("+34910000002"); // { ok, to, mode, error? }: ok false if they are still here
await this.call.attention("wants to talk to a person", { waitS: 60 }); // { ok, by, error? }
this.call.hold(); // and unhold()
this.call.dtmf("1#");
this.call.claim("4821"); // the page showing 4821 follows this call
this.call.callback("+34600000001", { when: "tomorrow afternoon", note: "a quote" });
this.call.optOut("does not want more calls"); // their number joins the do-not-call list
this.call.hangup("done");
await this.knowledge.search("summer opening hours", { k: 3 }); // the chunks, searched for this call
this.call.instruction is what this call is for, when whoever placed it said so: a dial's instruction
(pinecall dial reminder +1415… --instruction "Remind Ana of her cleaning tomorrow."). The prompt carries
it for the whole call, so the class does nothing with it unless it wants to.
this.call also carries id, contact, from, channel, medium, today — the day the call
runs in, which is what "next Tuesday" is counted from: the day a golden pinned when one did, else
the day the call opened — history, room and claimed.
There is no LiveKit here and no escape hatch to it: a need the room cannot express is a new command with a name.
The caller's page: screen()#
A caller on a page of yours sees more than a transcript: the agent draws their screen. screen() is
render() for the page: it reads the same state and returns parts, and it is drawn again whenever the
state moves, a tool ends or a task is asked for.
import { Agent, part, tool } from "@pinecall/agents";
const Agenda = part<{ slots: Slot[]; picked: string }>("agenda");
const Form = part<Asked>("form");
const Ticket = part<{ visit: Visit }>("ticket");
@agent({ events: { "slot.picked": { from: ["participant"] } } })
export default class FrontDesk extends Agent {
slots: Slot[] = [];
picked = "";
visit: Visit | null = null;
override onEvent(_name: string, tapped: Record<string, unknown>) {
this.picked = `${tapped["day"]} ${tapped["time"]}`;
void this.reply(`The caller tapped ${this.picked} on their screen. Read it back and ask for their yes.`);
}
override screen() {
const asked = this.call.asking;
if (asked !== undefined) return <Form {...asked} />;
if (this.visit !== null) return <Ticket visit={this.visit} />;
return <Agenda slots={this.slots} picked={this.picked} />;
}
}
part<Props>(name) |
a part: a tag of your own, also callable as a function (Agenda({ slots })) in a .ts file. The name is lowercase letters, digits and dashes; the page maps it to a component of its own. What it is given must be plain data: it crosses to a browser as JSON |
screen() |
what the page shows now. Parts nest, a component that is no part is called, and nothing is sent while the screen is the one already sent |
this.call.asking |
what a tool stopped to ask for ({ task, asks, fields, refused? }), so the screen can draw the question as a form; undefined when nothing is asked |
this.call.show(<Map />) |
puts a part over the screen now, from a tool or a hook; this.call.show(null) takes it away |
A screen that only reads the state stays on what the state holds: the agenda read three turns ago is still there while the caller asks who they are talking to. Scenes make it follow the conversation:
@agent({ scenes: { agenda: "the open times you last read", ticket: "the visit booked on this call" } })
export default class FrontDesk extends Agent {
@tool({ shows: "agenda" })
freeSlots(day: string) { … }
override screen() {
if (this.call.scene === "agenda") return <Agenda slots={this.slots} />;
return <Welcome />;
}
}
A tool with shows puts its scene up once it ran, and this.call.scene is the one up now. A turn the
caller opened in which nothing showed or kept the scene takes it away: the screen goes back to what
screen() draws with no scene. The model is told which scene is up, and is given show_screen, a quiet
tool it calls in the same turn as its words (no wait, no second answer) to keep the scene, put another
up, or take it away with none. A turn the agent opened on its own, such as its answer to a tap, leaves
the scene where it is.
The agent says what is on the screen and the page says how it looks: a part carries no markup and no
style. The screen travels in the call's state as the field screen, public to that call's own page and
to nobody else's, so a page that follows a phone call draws it too. @pinecall/room reads it with
screenOf(state.log) and draws it with <Screen>.
What the caller does on the page reaches the class as an event it declares from participant
(@agent({ events })), in onEvent. One event is the package's own: a page that shows a task's form gives the
answer with task.give ({ task: "phone", given: { number: "+14155550142" } }), in the model's place.
The task's check reads it as it reads the model's; the tool that asked goes on, and the model is told how
it ended so it can say so. A value the check refuses comes back on this.call.asking.refused.
The panel beside a conversation: @view#
The console draws a pane beside every thread in Calls. A class that declares a view has its own panel drawn there — the customer's file, their orders, the balance — from your own systems:
import { Agent, view, type Who } from "@pinecall/agents";
import { Badge, Panel, Row, Rows, Stat, Table } from "@pinecall/agents/panels";
async function CustomerCard(who: Who) {
const client = await crm.find(who.contact);
if (client === undefined) return <Panel title="Not on file">Not in the CRM.</Panel>;
return (
<Panel title={client.name}>
<Rows>
<Row label="Since">{client.since}</Row>
<Row label="Area">{client.area}</Row>
</Rows>
<Stat label="Jobs" value={client.jobs.length} />
<Table columns={["date", "job", "amount"]} rows={client.jobs} />
<Badge tone={client.debt > 0 ? "warn" : "good"}>{client.debt > 0 ? "owes" : "paid up"}</Badge>
</Panel>
);
}
@view(CustomerCard, "Customer")
export default class ClinicaNorte extends Agent {}
What reaches the console is a tree of the closed catalogue — Panel, Rows, Row, Stat,
Table, Badge, Text — drawn by the console's own parts; nothing a tenant writes reaches the
page's styling or its scripts. who is the conversation — agent, contact, call — and nothing
else: the panel is read beside threads that ended weeks ago, so it fetches what it shows. One per
class.
What is refused when the class loads#
Every one of these is refused before any call, with a message that says what to write:
| refused | the sentence |
|---|---|
| a tool with no docstring | tool book: without a docstring no model can choose it; write a /** one line */ above the method |
| a tool name a model cannot call | a tool name is one word a model can call, not … |
pii: ["dni"] on a tool with no dni |
tool book: pii names parameters the tool has; unknown: dni |
stage on a class with no stage field |
tool book: stage names a value of this agent's own stage field, and ClinicaNorte declares none; add \stage: Stages<"…"> = "…"` to the class, or ask when(state) instead` |
@tool on something that is not a method |
@tool goes on a method; … is not one |
a tool with an argument named say, which every tool carries for the model's own line |
bad_shape: tool echo: 'say' is the platform's argument, never a tool's own, said by the gateway when pinecall start registers the agent |
@state({ pii: true, visibility: "public" }) |
two different answers to one question; write one |
two @view decorators |
ClinicaNorte declares two views (…); a class draws one panel |
language, greeting, says, … as an instance field |
`language` is the class's, not a call's state: declare it in @agent({ language: … }) above the class |
static llm, or any other field of @agent, written as a static |
ClinicaNorte declares `static llm`: what an agent is goes in @agent({ llm: … }) above the class |
two @agent({ … }) on one class |
ClinicaNorte has two @agent({ … }): one says what it is |
an ownJudge with no asks, a bad answer, a choice with one choice, a trigger with no question |
offers: a judge asks a question of a call: write it as asks, offers: a judge that answers one of several needs at least two choices, … |
an ownPersona with no goal or style, or a key the wire does not know |
in-a-rush: a persona wants something: write its goal, in the first person |
two judges or two personas of one name in own |
two judges called offers-next-slot: a name is declared once |