Streaming: a run's result as it is written
A run has a result stream of its own, beside stdout and stderr. A script writes to it with result.write(chunk); the caller gets each write as soon as it is made, and the finished run carries all of it as run.result. Use it for the answer a script produces piece by piece, for example tokens a model hands the script through a tool, and keep console.log for progress and diagnostics.
Write from the script
import { result } from "shotcup:result";
result.write("<h1>Report</h1>");
result.write(new Uint8Array([0x0a]));chunk is a string (written as UTF-8; a lone surrogate becomes U+FFFD) or bytes: a typed array or an ArrayBuffer. Anything else is a TypeError. Nothing is added between writes: no newline, no separator. shotcup:result needs no engine switch; a run that does not import it pays nothing. It exists only in the run's own engine: a runScript child cannot import it.
Limits
A run's writes together may hold at most:
| Plan | Result stream |
|---|---|
| Free | 256 KiB |
| Pro | 1 MiB |
| Scale | 1 MiB |
| Platform | 1 MiB |
The bytes count as written (UTF-8 for text). A write that would pass the limit throws a RangeError and writes nothing, so a run either has its whole result or knows it does not; uncaught, the run fails as script-error and keeps what it wrote before.
Read it over HTTP
POST /api/v1/runs answers when the run has ended; its run carries result (null when the script never wrote), resultEncoding (utf8 while every write was text, base64 once one was bytes: then result is all of them as base64), resultBytes and resultTruncated. Text whose JSON would pass 2 MiB and be larger than its base64 (mostly control characters, six bytes each when escaped) is answered as base64 too, so decode by resultEncoding.
POST /api/v1/runs/stream sends each write as it happens, as a result event, apart from the chunk events of stdout and stderr:
event: result
data: {"chunk":"<h1>Report</h1>"}
event: result
data: {"chunk":"Cg==","encoding":"base64"}A write of bytes arrives as base64 with "encoding": "base64". The closing run event carries the whole result too, so a client that skips result events loses nothing.
The answer that ran the run carries the whole result. The run record keeps its first 64 KiB as stored (48 KiB of bytes as base64), as it keeps stdout, for as long as your plan keeps runs: GET /api/v1/runs/:id then answers that start with resultTruncated: true and the whole size in resultBytes. A run that paused for an approval carries no result; the resumed run writes it again from the start.
Read it with the SDK
import { createClient } from "shotcup";
const shotcup = createClient({ apiKey: process.env.SHOTCUP_API_KEY, baseUrl: "https://shotcup.dev" });
// each write as it arrives: a string for text, a Uint8Array for bytes
const run = await shotcup.runs.create({ code }, { onResult: (chunk) => process.stdout.write(chunk) });
// or iterate the writes, then take the finished run
const stream = shotcup.runs.stream({ code });
for await (const chunk of stream) process.stdout.write(chunk);
const finished = await stream.run;Leaving the loop early cancels the run.
Tokens through a tool
The streamed-answer template shows the pattern: the script asks a tool for the next batch of tokens and writes each one to the result stream, so the caller's user sees the answer grow while the script is still working.
import { result } from "shotcup:result";
const pump = async (cursor) => {
const batch = await tools.model.next({ cursor });
for (const token of batch.tokens) result.write(token);
return batch.cursor === null ? null : pump(batch.cursor);
};
await pump(0);The caller declares model.next and answers it live (the SDK's tools handlers, or the call events of the stream endpoint), for example from its own model's stream.
Web streams in the script
shotcup:streams has the WHATWG Streams classes: ReadableStream (with async iteration, tee, pipeTo, pipeThrough and ReadableStream.from), WritableStream, TransformStream, the two queuing strategies, and TextEncoderStream and TextDecoderStream (UTF-8, with a character split across chunks decoded whole). Once it is imported, result.writable is a WritableStream into the result stream:
import { ReadableStream, TransformStream } from "shotcup:streams";
import { result } from "shotcup:result";
const upper = new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk.toUpperCase());
},
});
await ReadableStream.from(["one ", "two"]).pipeThrough(upper).pipeTo(result.writable);import "shotcup:streams/global" installs the classes as globals, for libraries that look for ReadableStream there. Byte streams (type: "bytes", BYOB readers) are not available. The module is plain JavaScript in the sandbox, so it counts against your plan's instructions: importing it takes about 3,400, and a chunk about 1,100 through a pipe and about 2,400 through a TransformStream. The stream-pipeline template turns a tool's tokens into HTML a line at a time this way.
Watching a run
Any client with a key in the run's scope can watch a run, also one another client started: a dashboard following an agent, or a second agent waiting for the first one's answer. GET /api/v1/runs/:id/events streams the run's events as server-sent events. Every event has a number, its id, from 1, and the run's own stream (POST /api/v1/runs/stream) carries the same numbers:
id: 1
event: started
data: {"runId":"run_…"}
id: 2
event: chunk
data: {"stream":"stdout","chunk":"working\n"}
id: 3
event: call
data: {"runId":"run_…","callId":"c1","name":"approve","args":[…]}
id: 4
event: answered
data: {"callId":"c1","answeredBy":{"scope":"account"},"answeredAt":"…"}The last event is run, the run as stored (a paused run comes without its continuation token: anyone in its scope resumes it by its id), or error, and then the stream closes.
A new watcher first gets every event the machine holding the run still keeps, then each one as it happens. That machine keeps the most recent events up to a size per plan; a watcher whose next event is gone first gets dropped with {"before": N}, the first number still kept. To pick up after a dropped connection, send the last number you have as Last-Event-ID (what EventSource does on its own) or as ?after=. A run that has ended answers with its stored run event, and with 204 when you already have it. Closing the stream stops watching, never the run.
| Plan | Recent events kept | Watchers per run |
|---|---|---|
| Free | 256 KiB | 4 |
| Pro | 1 MiB | 16 |
| Scale | 4 MiB | 64 |
| Platform | 4 MiB | 64 |
A watcher past the last column gets 429 too-many-watchers.
Answering a call
A watcher may answer a call it sees with POST /api/v1/runs/:id/calls. The first answer to a call wins, and an answered event tells every watcher. A later answer delivers nothing and gets 409 call-already-answered, naming who answered first (the account, or a Platform tenant by its externalId, never a key) and when. Several clients of one account tell each other apart by their keys' labels: a key with a label (set when it is created, or later with PATCH /api/v1/api-keys/:id and the dashboard) adds it as answeredBy.label, in the 409 and in the answered event, for example {"scope": "account", "label": "reviewer"}. A label is 1 to 64 letters, digits, ., _, : and -; everyone who can watch the run reads it, so it is a name, never a secret. A change applies to answers given after it. A request that answers several calls is delivered whole or not at all, so send it again without the calls it lost. A run makes at most 10,000 live tool calls; one past it fails in the script.
With the SDK
for await (const event of shotcup.runs.watch(runId)) {
if (event.event === "chunk") process.stdout.write(event.data.chunk);
if (event.event === "run") console.log(event.data.run.status);
}runs.watch reconnects on its own after a dropped connection and resumes after the last event it gave. runs.answer(runId, results) answers a call it saw, and throws a ConflictError with code call-already-answered when another client answered first:
for await (const event of shotcup.runs.watch(runId)) {
if (event.event === "call") {
await shotcup.runs.answer(runId, [{ callId: event.data.callId, value: await decide(event.data) }]);
}
}A paused run resumed with handlers (runs.resume(runId, results, { tools })) streams, so the process that resumes it answers its later calls live. The MCP server's watch_run returns a run's events after a number, for up to 30 seconds at a time.
This page as Markdown: /docs/streaming.md