DEV Community

Sandscale
Sandscale

Posted on Originally published at sandscale.dev

Streaming command output from a sandbox: live logs for long agent runs

A command that takes a few seconds can return its output in one piece, and that is what most sandbox examples show. Real agent work is not always like that. A dependency install, a full test suite or a build can run for minutes. If the only signal is a single answer at the end, your user stares at a spinner, your agent cannot react to an obvious failure early, and a dropped connection near the end throws away everything.

Streaming fixes all three. This post shows how to stream output from a Sandscale sandbox with the TypeScript SDK and with plain HTTP, how resuming works, and how to decide what part of a long log the model should actually read. The calls come from the TypeScript SDK reference and the Sandboxes API reference, and the behavior described is that of @sandscale/sdk 1.0.0 on npm.

Two ways to run a command

The exec endpoint has a wait flag. Per the API reference, with wait omitted or true the call answers 200 with the result when the command ends: exit code, stdout, stderr, duration, and timed_out and oom_killed flags. With wait: false it answers 202 with the run's ID as soon as the run is recorded, before the command ends. You then read the output from the sandbox's log stream, which is Server-Sent Events.

The SDK picks between the two for you.

Streaming with the SDK

Pass onStdout or onStderr to sandboxes.run, and the SDK starts the command without waiting, follows the log stream and calls your functions with each piece of output in order:

import { Sandscale, type Region } from '@sandscale/sdk';

const sandscale = new Sandscale(); // reads SANDSCALE_API_KEY

const box = await sandscale.sandboxes.create({ template: 'builtin:node', timeoutSeconds: 1800 });

try {
  const result = await sandscale.sandboxes.run(box.id, 'npm ci && npm test', {
    region: box.region,
    timeoutSeconds: 900,
    onStdout: (chunk) => process.stdout.write(chunk),
    onStderr: (chunk) => process.stderr.write(chunk),
  });

  console.log('exit code', result.exitCode, 'streamed', result.streamed);
} finally {
  await sandscale.sandboxes.stop(box.id, { region: box.region });
}
Enter fullscreen mode Exit fullscreen mode

The call still resolves to a full RunResult at the end, with the complete stdout and stderr accumulated for you, plus exitCode, timedOut and oomKilled. So you get live output and a final answer from the same call.

Check result.streamed. It is true when your callbacks received live output, and false when they received the whole output once at the end. Per the SDK reference, that second case happens when the server answers with the finished result instead, for example a sandbox without live output. Code that shows progress should handle both: treat the callbacks as "output arrived", not "output arrived in real time".

Reading the stream yourself

If you started a command elsewhere, or want more control, sandboxes.logs is an async generator over a run's output:

async function follow(sandboxId: string, runId: string, region?: Region) {
  let lastChunk = -1;
  for await (const chunk of sandscale.sandboxes.logs(sandboxId, runId, {
    region,
    onDone: (end) => console.log('ended', end.exitCode, end.timedOut, end.oomKilled),
  })) {
    lastChunk = chunk.chunkIndex;
    (chunk.stream === 'stderr' ? process.stderr : process.stdout).write(chunk.data);
  }
  return lastChunk;
}
Enter fullscreen mode Exit fullscreen mode

Each chunk carries its stream (stdout or stderr), its data and a chunkIndex. The onDone callback receives how the run ended once the stream finishes.

Resuming after a dropped connection

Long streams drop. Laptops sleep, proxies time out idle connections, deploys restart workers. The log endpoint takes a from_chunk parameter, and the SDK uses it: when the connection breaks, it reconnects and asks for the chunks after the last one it delivered, so you do not see output twice or miss any. In 1.0.0 it retries a few times before giving up.

If your own process restarts, you can do the same by hand. Store the run ID and the last chunkIndex you processed, then pass fromChunk: lastChunk + 1 to logs when you come back. The run kept going in the sandbox while you were away; the log stream lets you catch up.

Streaming over plain HTTP

Without the SDK, it is two requests. Start the command with wait set to false:

API=https://api.sandscale.dev/api/v1/sandbox
AUTH="Authorization: Bearer $SANDSCALE_API_KEY"

curl -X POST "$API/instances/$ID/exec" -H "$AUTH" -H "Content-Type: application/json" \
  -d '{"command": ["sh", "-c", "npm ci && npm test"], "timeout_sec": 900, "wait": false}'
Enter fullscreen mode Exit fullscreen mode

The answer is a 202 with the run's ID. Then follow the stream, with -N so curl prints events as they arrive:

curl -N "$API/instances/$ID/logs?run_id=$RUN_ID" -H "$AUTH" -H "Accept: text/event-stream"
Enter fullscreen mode Exit fullscreen mode

Add &from_chunk=N to resume. When the stream ends, GET $API/runs/$RUN_ID returns the run's details, including its exit code.

What the model should see

Streaming solves the human side: people can watch. It does not mean the model should read every line. A failing test suite can print thousands of lines, and pasting all of it into the next prompt costs tokens and buries the useful part.

Some patterns that work:

  • Stream to people, summarize to the model. Show the live log in your UI. When the command ends, give the model the exit code, the last part of stderr and stdout, and any lines matching obvious failure markers.
  • Keep both ends. The first lines often say what was run; the last lines say why it failed. Truncate the middle, and tell the model you did, with a count of the lines you dropped.
  • React early when it is safe. If your agent loop watches the stream, it can spot a fatal error in an install step before the test step starts. Stopping the sandbox early saves the rest of the run.
  • Report flags in words. If timedOut or oomKilled is set, say so plainly in the tool result. Models handle "your command was stopped after 900 seconds" much better than an abruptly cut log.

Timeouts still apply

Streaming does not change the time limits. The command's timeoutSeconds (or timeout_sec) still ends it, and the sandbox's own lifetime still ends the sandbox. Our post on timeouts for agent sandboxes explains how the three clocks fit together.

Every run is recorded

Whether you stream or wait, each command is recorded as a run. GET /api/v1/sandbox/runs/{id} with the run ID returns its details, and the run code guide notes that the record includes its cost. That makes the run ID the thing to log next to each tool call in your agent: from it you can get back to the output, the exit status and what the command cost.

Originally published on the Sandscale blog.

Top comments (0)