One HTTP request that returns a finished agentic answer, executed on someone's own Claude Code or Codex, with tools your app defines and executes.
JavaScript
import { Soba } from "@soba-so/sdk";
import { sobaUserId } from "@soba-so/sdk/identity";
const soba = new Soba({ apiKey: process.env.SOBA_KEY });
const run = await soba.run({
// Stable across database resets — see [Identifying users](/docs/identity).
user: sobaUserId(session.user.username),
model: "auto",
prompt: "Summarise everything I saved this week",
tools: [listNotes, readNote], // your code, executed in your app
});
for await (const event of run) {
if (event.type === "delta") process.stdout.write(event.text);
if (event.type === "done") console.log(event.usage);
}
A run is one request that comes back finished. It reaches everything the endpoint
reaches and, unlike the endpoint, the user's own Claude Code or Codex on their
subscription, and it streams back the
normalised event stream.
Streaming it from a serverless function#
Most apps forward a run to the browser from a route handler. Three lines keep that
route from outliving the person who asked:
JavaScript
export const maxDuration = 300; // a run lasts as long as its answer, not the platform default
const run = await soba.run({ user, model: "auto", prompt, tools, signal: request.signal });
return new Response(new ReadableStream({
async start(controller) { /* forward each event */ },
cancel() { void run.cancel(); }, // the tab closed: stop the run on their machine too
}));
signal stops the run when the request is aborted. cancel() stops it when the
reader goes away mid-stream. Without them, a closed tab leaves your function, and
the user's machine, working on an answer nobody will read. npx create-soba
scaffolds exactly this.
The SDK starts a run at most once. It retries POST /runs only when the request
provably never arrived: a refused connection, an unresolvable host, or a 429. A
timeout or a 5xx can come after the run has already started, and retrying either
would start a second one, billed as one.
Runs that outlive the request#
A run is tied to the request reading it: when that request goes away, the run is
cancelled. On a serverless host that is a run cut off at the function's time limit.
Pass resumable: true and it is not. The run keeps going, Soba keeps its events,
and any later request can read on from where the last one stopped:
JavaScript
const run = await soba.run({ user, prompt, tools, resumable: true });
for await (const event of run) {
if (almostOutOfTime()) break; // stop reading; the run carries on
/* … */
}
await saveForLater({ runId: run.runId, cursor: run.cursor, key: run.key });
// The next request, a queue worker, a cron: same tools, same user.
const again = await soba.runs.attach(runId, { user, tools, after: cursor, key });
for await (const event of again) { /* what was missed, then live */ }
run.key opens an encrypted run from another process. Keep it anywhere, even in
a browser: it only works with your API key, and Soba never receives it. A server that
stays up can leave it out.
Your app only ever calls out to Soba, so this works the same on localhost as in
production: no public URL and no tunnel. Tool calls run wherever the run is being
read. One the run is still waiting on, because the last reader left mid-tool, is
executed by the next one; one that was already answered is not executed again.
- One reader at a time. Attaching takes the run over and the previous reader's
stream ends.
- Fifteen minutes. A run nobody is reading for fifteen minutes is stopped. A
finished run can still be read to its end for ten minutes after it finished.
- 5 MB of history. Soba keeps the newest 5 MB of a run's events. Attaching
from further back starts with a
status event saying which events were
dropped, then reads on from the oldest kept one. A tool call the run is still
waiting on is always kept. A run whose waiting tool call holds back more than
10 MB is stopped.
soba.runs.start without a webhook starts a run nobody is reading yet and
returns its id; read it with runs.attach. With a webhook, events are pushed
there instead: see Webhooks.
- Encrypted detached runs return a
key beside their id. Pass it to
runs.attach, or to handleRunWebhook and openRunWebhook if you read the run
by webhook: deliveries arrive sealed, and answers leave sealed. See
What Soba sees.
A run that survives the page#
In a browser, useRun does all of the above for you. Leaving a page, reloading or
losing the connection only stops the reading, and it reads on by itself when it can.
JavaScript
// app/api/run/route.js
export async function POST(request) {
const { prompt } = await request.json();
return runResponse(await soba.run({ user, prompt, resumable: true }));
}
// app/api/run/attach/route.js
export async function POST(request) {
const { runId, after, key } = await request.json();
return runResponse(await soba.runs.attach(runId, { user, after, key }));
}
JavaScript
const { start, text, busy, reconnecting, stop } = useRun({ endpoint: "/api/run" });
user is the signed-in person, from your session, on both routes.
Every run survives Soba restarting, without resumable. When Soba deploys,
a run in flight carries on, and soba.run() reads on from where it was on its
own: your loop sees a pause, not an error. Hanging up still stops a run that did
not ask for resumable: true. This needs the person's machine to be on a current
Soba app, and is not offered over the OpenAI-compatible endpoint.
Let the page read the run#
A streamed run passes every event through your server: a function stays open for
the whole run, and your host cuts it off at its time limit. Instead, start the run
and hand the page where to read it. Your server answers in milliseconds, and the
page reads the run straight from Soba.
TypeScript
// app/api/ask/route.ts: your server starts the run and is done
const run = await soba.runs.start({
user,
prompt,
tools,
...(process.env.SOBA_TOOLS_URL
? { webhook: { url: process.env.SOBA_TOOLS_URL, secret: process.env.SOBA_WEBHOOK_SECRET!, events: "tools" } }
: { answerTools: "here" }),
})
return Response.json({ id: run.id, stream: run.stream })
TypeScript
// the page
import { watchRun } from "@soba-so/react"
const { stream } = await (await fetch("/api/ask", { method: "POST", body })).json()
for await (const event of watchRun(stream)) {
if (event.type === "delta") setAnswer((a) => a + event.text)
}
Your tools still run on your server, against your data. Two ways:
- In production, a webhook with
events: "tools": Soba calls it once per tool
call and once when the run ends, each a short request. Nothing waits in between.
- On localhost,
answerTools: "here": the SDK answers the tool calls from the
same process, so nothing has to reach your laptop. Use it on any long-lived
server too, but not in a serverless function, which would be stopped mid-run.
Every webhook delivery carries the user the run was started for, inside the
signed body. handleRunWebhook hands it to your tools as ctx.user, so a tool
answering a webhook knows whom it acts for without your handler looking it up.
If you pass user as well, the two must match or the tool is not run.
run.stream is a URL and a token for that one run, valid for an hour. It can only
read: tool calls show as their names, never their inputs, and nothing can be
started, answered or cancelled with it. If the connection drops, watchRun
reconnects and reads on from where it was.
Small jobs, small models#
Every run counts against the person's own Claude or ChatGPT plan. A summary or a
quick lookup does not need the largest model:
TypeScript
await soba.runs.start({ user, prompt, model: "small" }) // or "large"
"small" is the machine's quick, cheap model (Haiku, for Claude Code) and "large"
its most capable one. A runtime with no size to offer runs its default, and so does
a machine on an older version of Soba. "auto" (the default) leaves it to the machine.
When their machine is busy#
A machine runs a few runs at once (its owner sets how many). A run that arrives
while all its slots are taken waits for one, up to a minute, instead of failing or
going to a bought model, when your route puts their machine first. If your route
ranks bought supply first, it goes there at once: that is what you asked for when
the machine is not free.
How long a run may last#
Every run has a time limit, and a run that reaches it is stopped on the machine.
It ends with an error event whose reason is run_too_long and whose
message says which limit it reached.
The limit is the lowest of these:
| Layer |
Who sets it |
Where |
| Soba's default |
Soba |
30 minutes |
| Your organisation's limit |
Soba, on request |
Replaces the default, higher or lower |
| Your app's limit |
Your app's admins |
Settings → Advanced → Run limit. Can only be lower than your organisation's |
| This run's limit |
Your code |
maxDurationMs on soba.run or soba.runs.start |
TypeScript
const run = await soba.run({ user, prompt, maxDurationMs: 2 * 60_000 })
for await (const event of run) {
if (event.type === "error" && event.reason === "run_too_long") {
// Starting it again reaches the same limit: narrow the task instead.
}
}
Runs opened as a terminal window are not limited this way: they are someone
working in their own session. The user's machine also has its own limit, set by
its owner (10 minutes unless they change it), so a run can end sooner than your
limit, never later.
Your own server's limits still apply too. A streamed run ends when the function
serving it does (300 seconds on Vercel by default); use a resumable run for
anything longer.
Why this exists alongside the endpoint#
chat/completions is stateless, and the caller owns the loop:
you send messages, you get a tool call back, you execute it, you send everything
again. That works for a model. An agent cannot be driven that way.
Claude Code and Codex run their own loop, and they never hand a tool call back to wait
on an HTTP round trip. So running them with your tools means Soba owns the loop, and your tools
have to be registered out of band rather than returned mid-conversation.
That is the whole difference between the two entry points:
|
chat/completions |
soba.run() |
| Who owns the loop |
You |
Soba |
| Tools |
Returned to you, per turn |
Registered up front, called back |
| Reaches model runtimes |
yes |
yes |
| Claude Code and Codex |
Conversation as text, no loop of yours |
With your tools |
| Shape |
The request you already send |
One request, one finished answer |
The model calls them wherever the run is executing, the call comes back to your app, and
your code executes it. Nothing about your tools moves to Soba: they run where they
already run, against the data they already touch. See
App-defined tools.
Over HTTP that is a frame on the run's stream and a request back the other way:
JSON
{"type":"tool_call","runId":"r_01","callId":"c_1","name":"lookup_invoices","input":{"customer":"Acme"}}
Terminal
curl https://api.soba.so/v1/runs/r_01/tool_result \
-H "Authorization: Bearer $SOBA_KEY" \
-H "Content-Type: application/json" \
-d '{ "callId": "c_1", "result": { "open": 3, "total": "$14,200" } }'
The SDK does that for you: your execute returns, and the result is on its way.
isError: true marks a failure the model should see and can react to, rather than
one that kills the run.
Tools can also be registered from an MCP server you already operate, which is what
lets a run reach a toolset you did not write inline.
Over raw HTTP#
Terminal
curl https://api.soba.so/v1/runs \
-H "Authorization: Bearer $SOBA_KEY" \
-H "Content-Type: application/json" \
-d '{
"user": "usr_123",
"model": "auto",
"prompt": "Summarise everything I saved this week",
"route": { "prefer": ["user-hardware", "user-subscription"] }
}'
POST /v1/runs takes the same shape the SDK sends and streams the same events back.
The SDK is a convenience over it, not a different product. The run's id arrives in a
Soba-Run-Id header, and three routes
(tool_result, approval, cancel) answer a run that is
still in flight.
The events#
JSON
{"type":"status","message":"Starting","tier":"user-subscription"}
{"type":"delta","text":"You saved eleven things this week. "}
{"type":"done","usage":{"model":"sonnet","costClass":"user-subscription","inputTokens":1840,"outputTokens":210,"cacheReadTokens":0,"cacheWriteTokens":0,"webSearches":0}}
Five event types. delta appends, thinking replaces, status carries the
tier that served the run before any output, done carries what it consumed, and
error is the other way a run ends.
Full shapes on The event stream.
Declaring what a run may use#
JavaScript
const run = await soba.run({
user: sobaUserId(session.user.username),
prompt: "…",
route: {
prefer: ["user-hardware", "user-subscription"],
allow: ["user-hardware", "user-subscription", "user-api-key"],
maxCostMicros: 250000,
},
});
You declare the cost classes you accept, not a runtime. allow is a hard ceiling and is
enforced on the machine as well as by Soba. See Routing a run.
Most apps never write route by hand: a plan compiles to one on every
run, so pricing and routing stay the same decision.
Serving the run yourself#
A user with nothing reachable can be answered by your app, on your own key, the way you
serve them today. soba.run() throws before any output, so catch that one code:
JavaScript
try {
const run = await soba.run({ user, prompt, tools });
// …stream the run
} catch (err) {
if (!(err instanceof SobaError) || err.code !== "no_compute") throw err;
// call your provider here, as you did before Soba
}
To have Soba call your provider instead, add it under Models and make the client with
encrypt: false: Soba can't serve a run it can't read. For when Soba itself can't be
reached, see Routing a run.