Build your first feature
A feature that is not a conversation. A page takes a text, a background job summarises it for a price per page, and the result is there on return.
Most products built on a model are not a chat. Someone hands over a file, a URL or a form, the work takes a while, and they come back for the result. This page walks through one such feature as it ships in the registry, so every block below is the installed code and not a sketch of it.
pnpm exec intelligo sync summariesThat installs the page at /summaries with its action, its job and its messages. It needs the chat item for the model seam (lib/chat-model.ts) and pricing for money formatting. Without a model key it runs on the stub, so the whole path works on a fresh install.
The feature has four parts, and yours will have the same four:
- a price the person sees before they start
- an action that queues the work and returns at once
- a job that does the work inside an execution, so it is admitted, charged and recorded
- a list the page reads back, finished or not
A price known before the work
A summary is priced by the pages of the text, not by the model’s tokens. The form and the job read the same file, so the price shown is the price charged:
export function summaryPrice(pages: number): MoneyLike {
const price = multiply(SUMMARY_PRICE_PER_PAGE, pages);
return { amount: price.amount, currency: price.currency };
}lib/summary-config.ts is yours once installed: change the page size, the limit and the price there. Work whose size is only known afterwards (minutes transcribed, images made) begins with the most it can cost as price and settles the measured amount with complete({ charge }); the billing package page has that under “A fixed price per unit of work”.
Queue the work, return at once
The action checks its input, stores the text as a document, and enqueues a job that names the person who asked. It does not call the model:
export async function startSummary(input: {
title: string;
text: string;
}): Promise<ActionResult<{ id: string }>> {
const parsed = startSummarySchema.safeParse(input);
const t = await getTranslations("summaries");
if (!parsed.success) {
const issue = parsed.error.issues[0];
const key =
issue?.path[0] !== "text"
? "actions.invalidTitle"
: issue.code === "too_big"
? "actions.textTooLong"
: "actions.emptyText";
return { success: false, error: t(key) };
}
const { title, text } = parsed.data;
try {
const { workspace, user } = await requireWorkspace();
composeIntelligo();
const sourceId = `summary-source-${crypto.randomUUID()}`;
await saveDocument(
{ workspaceId: workspace.id, userId: user.id },
{ id: sourceId, kind: "text", title, content: text }
);
const payload: SummaryPayload = {
sourceId,
title,
summaryTitle: t("summaryTitle", { title }),
};
const id = await enqueue({
kind: SUMMARY_KIND,
workspaceId: workspace.id,
userId: user.id,
payload,
maxAttempts: 2,
});
// The first attempt now, after the response, not at the next
// scheduled drain. One that fails waits for the drain route.
runInBackground(
drain(summaryHandlers, { kinds: [SUMMARY_KIND], limit: 1 }).catch(
(error: unknown) => {
log.error("Running a queued summary failed", { error });
}
)
);
return { success: true, data: { id } };
} catch (error) {
if (!isAuthGuardError(error)) {
log.error("Starting a summary failed", { error });
}
return { success: false, error: t("actions.genericError") };
}
}Three things to copy:
- The input is parsed. A server action is a public endpoint; its arguments are whatever was sent.
- The job carries
userId. That is what lets the page list this person’s work and nobody else’s. - The first attempt starts now.
runInBackground(drain(...))runs it after the response instead of waiting for the next scheduled drain. An attempt that fails is run again by the drain route, below.
Do the work inside an execution
The handler reports where it is, runs the model call through runWithExecution, saves the result, and returns the id of what it made:
export const summaryHandlers: Record<string, JobHandler> = {
[SUMMARY_KIND]: async (job, signal) => {
composeIntelligo();
if (!job.workspaceId || !job.userId) {
throw new Error(
"A summary job carries its workspace and the person who asked."
);
}
const { sourceId, summaryTitle } = payloadOf(job.payload);
const actor = { workspaceId: job.workspaceId, userId: job.userId };
await reportProgress(job, { stage: "reading" satisfies SummaryStage });
const source = await getDocument(actor, sourceId);
const text = source.content ?? "";
const pages = summaryPages(text);
const price = summaryPrice(pages);
const documentId = summaryDocumentId(job.id);
// An attempt that saved the summary and then lost its job: the
// work is done and paid for, so it is not done again.
if (await findDocument(actor, documentId)) {
return { documentId, pages, charged: price };
}
await reportProgress(job, { stage: "writing" satisfies SummaryStage });
let summary: string;
try {
const written = await runWithExecution(
{
executions,
workspaceId: actor.workspaceId,
userId: actor.userId,
capability: SUMMARY_CAPABILITY,
model: CHAT_MODEL_ID,
// Held when the run begins, charged when it completes,
// released if the model call throws.
price: money(price.amount, price.currency),
},
async () => {
const stream = streamText({
model: getChatModel(CHAT_MODEL_ID),
system: SUMMARY_SYSTEM,
prompt: text,
abortSignal: signal,
});
const [answer, usage] = await Promise.all([
stream.text,
stream.totalUsage,
]);
if (!answer.trim()) throw new Error("The model wrote nothing.");
return { text: answer, usage };
}
);
summary = written.text;
} catch (error) {
// Not enough credit, or a limit reached. Running it again changes
// nothing, so the job ends and says why.
if (error instanceof ExecutionRefusedError) {
return { refused: error.reasonCode ?? "refused" };
}
throw error;
}
await reportProgress(job, { stage: "saving" satisfies SummaryStage });
await saveDocument(actor, {
id: documentId,
kind: "text",
title: summaryTitle,
content: summary,
});
return { documentId, pages, charged: price };
},
};What each part buys you:
priceis held when the run begins and charged when it completes. If the model call throws, the hold is released and nothing is charged.- A refusal is an answer, not a failure. A workspace without credit is refused at
begin. Running the job again would be refused again, so the handler returns{ refused }and the page says why. - The result is saved under the job’s id. A handler runs once per attempt. If an attempt saved the summary and then lost its job, the next one finds the document and neither runs nor charges again.
reportProgresswrites the stage onto the job, where the page reads it.- What it returns is the job’s
result: the document’s id, the page count and the charge. The summary itself lives in a document, because finished jobs are pruned.
For attempts after the first, the drain route has to know the handler. Install the route once and add the item’s handlers to its map:
pnpm exec intelligo add jobsimport type { JobHandler } from "@intelligo-dev/jobs";
import { summaryHandlers } from "@/lib/summaries";
export const handlers: Record<string, JobHandler> = {
...summaryHandlers,
};Background jobs covers scheduling the route.
Read it back
The page lists the caller’s own jobs of this kind and turns each into what it shows:
export async function listSummaries(): Promise<ActionResult<SummaryItem[]>> {
try {
const { workspace, user } = await requireWorkspace();
const jobs = await listJobs({
workspaceId: workspace.id,
userId: user.id,
kinds: [SUMMARY_KIND],
limit: LIST_LIMIT,
});
return { success: true, data: jobs.map(toItem) };
} catch (error) {
if (!isAuthGuardError(error)) {
log.error("Listing summaries failed", { error });
}
const t = await getTranslations("summaries");
return { success: false, error: t("actions.genericError") };
}
}listJobs requires the workspace and narrows to the person, so the list cannot hold another tenant’s work. The job’s lastError never reaches the page: it is the handler’s own message, written for an operator.
The client reads the list again after a summary is started and every two seconds while one is unfinished, and stops once all have ended:
export function SummariesPanel({ initial }: { initial: SummaryItem[] }) {
const [items, setItems] = useState(initial);
const refresh = useCallback(async () => {
const result = await listSummaries();
if (result.success) setItems(result.data);
}, []);
const waiting = unfinished(items);
useEffect(() => {
if (!waiting) return;
const timer = setInterval(() => void refresh(), POLL_MS);
return () => clearInterval(timer);
}, [waiting, refresh]);
return (
<div className="space-y-8">
<SummaryForm onStarted={() => void refresh()} />
<SummaryList items={items} />
</div>
);
}Leaving the page stops the reading and nothing else. The work runs in the background, and coming back shows where it got to.
What you get without writing it
Because the model call went through an execution, the run is on the usage page with its charge, in the admin console with its provider cost, counted against the workspace’s credit and against a deployment-wide spend cap if you set one. Because the job went through the queue, a failed attempt is retried and one out of attempts is on the admin console’s operations page with a retry button.
Make it yours
Rename the kind and the capability, replace the prompt and the model call in lib/summaries.ts with your own work, and keep the shape: price, action, job, list. To gate the feature to a plan, call requireFeature in the action before you enqueue; see Plans, features and quotas.