Agents APIReference
TypeScript SDK
@latentcode/sandbox-agents 0.1.4: a typed client for hosted agent sessions. It has no runtime dependencies and runs anywhere fetch does.
Install
The package is distributed by LatentStack rather than npm. Installing from the URL records it in package.json:
npm install https://latentstack.dev/dl/latentcode-sandbox-agents-0.1.4.tgzbun add, pnpm add and yarn add take the same URL. To pin a copy, download the tarball and install the file (npm install ./latentcode-sandbox-agents-0.1.4.tgz).
| Runtime | Supported |
|---|---|
| Node.js | 22 or newer |
| Bun · Deno | Yes |
| Browsers | Technically yes, but never ship an ls- key to a browser. Call from your server. |
Create a client
import { LatentStack } from "@latentcode/sandbox-agents"
const client = new LatentStack({ apiKey: process.env.LS_API_KEY! })
const sessions = client.agents.sessionsnew LatentStack(options: LatentStackOptions)| Option | Type | |
|---|---|---|
| apiKey | string | Required. Your ls-… key. |
| baseUrl | string | Your LatentStack URL, if it isn't https://latentstack.dev. |
| fetch | typeof fetch | Your own fetch, for proxies, tracing or tests. |
client.agents.sessions
Lifecycle
create(params: CreateSessionParams): Promise<Session>params holds the session settings (agent, environment, limits, input, metadata) and an optional idempotencyKey that makes the call safe to retry. environment.network sets what the sandbox can reach; limits caps what the session may spend. files, outputs and end_after_run are on Outputs, and webhook on Webhooks.Sessionget(sessionId: string): Promise<Session>limits, stop_reason and usage.Sessionlist(params?: { limit?: number; after?: string }): Promise<SessionList>next_after as after for the next page.{ data, has_more, next_after }delete(sessionId: string): Promise<Session>Session (stopping or stopped)pause(sessionId: string): Promise<Session>Session (pausing)resume(sessionId: string): Promise<Session>message() does this on its own. Also brings back a stopped session while its disk is kept (volume_kept_until).Session (provisioning)fork(sessionId: string, params?): Promise<Session>input, metadata, limits, outputs, end_after_run, webhook and idempotencyKey. See Fork a session.Session (provisioning)update(sessionId: string, { limits }): Promise<Session>nullremoves one.SessionInput
message(sessionId: string, text: string,
options?: { delivery?: "steer" | "queue"; files?: string[] }): Promise<InputAccepted>steer (default) folds into the current run; queue runs after it. files names workspace images (png, jpeg, gif or webp) to put in front of the model with the text.{ accepted, queued?, resumed? }approve(sessionId: string, requestId: string,
reply: "once" | "always" | "reject", message?: string): Promise<InputAccepted>approval.requested frame.cancel(sessionId: string): Promise<InputAccepted>send(sessionId: string, input: SessionInput): Promise<InputAccepted>{ type: "message", text, delivery }.Following
events(sessionId: string, options?: EventsOptions): AsyncGenerator<StreamFrame>after=<last seq> when the connection drops and ends when the session is stopped or failed. It throws a LatentStackError if the session can't be read (e.g. not_found) or the stream keeps closing (5 attempts in a row).| Option | Type | |
|---|---|---|
| after | number | Start after this seq, e.g. a stored session.last_seq. Default: from the beginning. |
| signal | AbortSignal | Ends the loop when aborted. |
| retryDelayMs | number | Fixed wait between reconnects. Default: 1 s, 2 s, 3 s … per failed attempt. |
wait(sessionId: string, options?: { until?: SessionStatusName[];
timeoutMs?: number; pollMs?: number }): Promise<Session>until (default SETTLED: idle, waiting, paused, stopped, failed). timeoutMs defaults to 10 minutes and pollMs to 2 seconds. On timeout it throws LatentStackError with type timeout. Right after create() a session is briefly idle before its first message starts, so follow events() to know a task is done.SessionArtifacts
artifacts(sessionId: string): Promise<ArtifactList>{ data: Artifact[] }artifact(sessionId: string, name = "patch", options?: { repo?: string }): Promise<string>repo when the session has several repositories.string (unified diff)Files
Paths are relative to the workspace, like uploads/photo.png. A path with a . or .. segment, or a leading or trailing slash, throws invalid_request before anything is sent. See Files.
uploadFile(sessionId: string, path: string, data: Blob | ArrayBuffer | ArrayBufferView | string,
options?: { contentType?: string }): Promise<FileInfo>data at path. Missing folders are created, and an existing file is replaced. A string is the file's content, as UTF-8. contentType defaults to the Blob's own type, else application/octet-stream.{ object, path, size, sha256 }downloadFile(sessionId: string, path: string): Promise<Blob>type comes from the file's extension.BloblistFiles(sessionId: string, params?: { prefix?: string; limit?: number }): Promise<FileList>prefix, in path order, up to limit (1,000 at most). .git is left out. truncated is true when there were more.{ object, data: [{ path, size, modified_at }], truncated }deleteFile(sessionId: string, path: string): Promise<void>Working with frames
StreamFrame is a union of SessionStatus, ApprovalRequested and Event. A durable event's type is an open string, so narrow on "seq" in frame first. data may be missing; read it with ?..
for await (const frame of sessions.events(id)) {
if ("seq" in frame) {
// Event: { seq, type, data: Record<string, unknown>, time }
if (frame.type === "text.ended") console.log(frame.data?.text)
if (frame.type === "run.completed") break
} else if (frame.type === "session.status") {
// SessionStatus: status, error, instance_number, pending_approvals
} else if (frame.type === "approval.requested") {
// ApprovalRequested: request_id, action, resources, metadata
await sessions.approve(id, frame.request_id, "once")
}
}Errors
Every failed call throws LatentStackError, with status (0 if no response arrived), type and message. See Errors for the list of types.
import { LatentStackError } from "@latentcode/sandbox-agents"
try {
await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5" }, input: "hi" })
} catch (e) {
if (e instanceof LatentStackError && e.type === "model_not_allowed") { /* pick another model */ }
else throw e
}Exports
| Export | What |
|---|---|
| LatentStack | The client. |
| Sessions | The class behind client.agents.sessions. |
| Webhooks · Events · Schedules | The classes behind client.agents.webhooks, client.agents.events and client.agents.schedules. |
| LatentStackError | The error class. |
| verifyWebhook · WebhookVerificationError | Checks a webhook delivery and returns its event, or throws. See Verify the signature. |
| SETTLED | ["idle", "waiting", "paused", "stopped", "failed"] |
| DEFAULT_BASE_URL | https://latentstack.dev |
| types | Session, SessionList, SessionStatusName, Agent, Rule, Event, StreamFrame, SessionStatus, ApprovalRequested, PendingApproval, InputAccepted, SessionInput, Artifact, ArtifactList, FileChange, FileInfo, FileList, FileData, ApiError, CreateSessionParams, ListSessionsParams, MessageOptions, ListFilesParams, UploadFileOptions, WaitOptions, EventsOptions, LatentStackOptions, Output, OutputList, WebhookEndpoint, WebhookEndpointList, WebhookDelivery, WebhookDeliveryList, WebhookAttempt, WebhookEvent, EventList, EventSession, Schedule, ScheduleList, ScheduleRun, ScheduleRunList, StagedFile, PageParams, CreateWebhookParams, UpdateWebhookParams, ListWebhookDeliveriesParams, ListEventsParams, ScheduleSession, CreateScheduleParams, UpdateScheduleParams, WebhookHeaders, VerifyWebhookOptions |
Upgrading
- Each new version has its own install URL; see Install above. Update the URL in
package.jsonand reinstall. 0.1.1added several repositories per session and therepooption onartifact().0.1.2addedlimitsandenvironment.networkoncreate(), andlimits,usageandstop_reasonon the session.0.1.3addeduploadFile(),downloadFile(),listFiles(),deleteFile()and thefilesoption onmessage().0.1.4addedclient.agents.webhooks,client.agents.eventsandclient.agents.schedules;outputs(),deleteOutput()andwebhookDeliveries()on sessions;files,outputs,end_after_runandwebhookoncreate(); andverifyWebhook()withWebhookVerificationError; andupdate()to raise a session's limits. A spend limit now pauses a session instead of stopping it, andresume()brings back a stopped one for 7 days. See Webhooks, Outputs and Schedules.