TypeScript / JavaScript SDK handbook
Use @orbitspace/sdk in your backend to submit work, follow progress and handle input. The resource helpers below require SDK 0.3.0+. Verify the version in the SDK center and browse the generated method reference.
Choose credentials and a runtime
| Application | Credential and SDK setup |
|---|---|
| Backend with an API Token | Read the token from your secret manager and pass token: () => accessToken. |
| Confidential OAuth application | Use createClientCredentialsTokenProvider() with its registered token endpoint, client ID, authentication method and approved scopes. |
| Browser or mobile product | Use your established OAuth/OIDC client for authorization code + PKCE. Supply its short-lived access token through TokenProvider. Never bundle a client secret. |
| Worker / Runtime Host | Use the Runtime deployment contract. Application API credentials do not enroll an executor. |
Prepare the tenant, project-authorized workspace and Agent binding, or an authorized Agent service deployment. Scopes do not replace project grants or service policy. Native Task reads/writes use tasks:read / tasks:write; request artifacts:read or approval scopes only for operations your product actually exposes. See authentication. Model-provider keys are configured on the platform, not in this SDK.
Node.js 22.18+ is the qualified backend runtime. Browser qualification covers client transport and event observation; OAuth secrets, Node file examples and server-side Inbox persistence belong on the backend. Cloudflare Workers and other Edge runtimes must qualify their Fetch, Web Crypto, streams and cancellation behavior before deployment; they are not claimed as tested targets here.
Create one client per identity
import { OrbitSpaceClient, createClientCredentialsTokenProvider } from "@orbitspace/sdk";
const token = createClientCredentialsTokenProvider({
tokenEndpoint: process.env.ORBITSPACE_TOKEN_ENDPOINT!,
clientId: process.env.ORBITSPACE_CLIENT_ID!,
clientSecret: () => process.env.ORBITSPACE_CLIENT_SECRET!,
scopes: ["tasks:read", "tasks:write"],
});
const client = new OrbitSpaceClient({
baseUrl: "https://api.orbitspace.dev",
tenantId: process.env.ORBITSPACE_TENANT_ID!,
token,
timeoutMs: 15_000,
retry: { maxRetries: 2 },
});The provider caches Bearer tokens in memory, shares concurrent issuance and renews before expiry. It does not persist credentials or share a cache across tenants/processes. A response without an expiry is not cached indefinitely. Default client authentication is client_secret_basic; explicitly select client_secret_post only for a matching registration, or private_key_jwt with your existing signer's clientAssertion callback. Optional resource must match the authorization server's resource policy.
Do not infer the token endpoint from the API hostname. Copy the endpoint from the configured OAuth issuer. When rotating a credential, update the backing secret and call token.invalidate(); it affects subsequent requests and does not revoke an already issued server token. A failed write is not automatically replayed after a 401.
Submit and observe work
Persist the business job, exact request body and one idempotency key before admission, in the same transaction as your own job mapping. Reuse that key/body after an uncertain network outcome. Do not generate a new key for each attempt.
// These values were loaded from your durable business-job record.
const task = await client.tasks.create({
workspace_id: job.workspaceId,
workspace_agent_binding_id: job.agentBindingId,
input: job.input,
idempotency_key: job.submissionKey,
});
await saveExecutionId(job.id, task.id!);
const view = new AbortController();
for await (const progress of client.tasks.observe(task.id!, { signal: view.signal })) {
await showProgress(job.id, progress.state, progress.resource);
}observe() reads an initial REST snapshot and refreshes it in response to SSE events. It stops for completion, failure, cancellation, pause, required input or required approval. wait() returns the same actionable or terminal observation. Neither method interprets a closed connection or unknown status as success. Aborting the signal releases local observation; the remote execution continues. Use explicit cancel() to stop remote work.
For a published Agent service, use client.invocations.create(deploymentId, { input, idempotency_key }), then client.invocations.observe(id, { signal }). Save the Invocation-to-business-job mapping. Its opaque execution_id is not an internal Task ID. Invocation interaction follows that service's published contract; do not call native Task endpoints with inferred IDs.
Native client.goals.observe() follows the Goal's status. A child Task can wait for input while its Goal remains active. Use client.goals.getExperience() and client.watchGoalExperience() for Experience phases, interaction and the supplied deep link. See Goals & Workflows.
Reply to existing questions and control state
const question = await client.tasks.getInput(questionId);
// Validate scope_task_id / task_id against the application's business job.
// Persist the answer, this question's version and replyKey before sending.
await client.tasks.replyInput(questionId, {
expected_state_version: question.state_version!,
idempotency_key: replyKey,
response: validatedUserAnswer,
});
const current = await client.tasks.get(taskId);
await client.tasks.cancel(taskId, { expected_state_version: current.state_version! });Keep decimal versions and event IDs as strings. A question's version is distinct from its Task version. On a conflict, reload the resource and ask the application to reconcile its intended change; do not silently replace a version and replay. Replying continues the existing Task/Run. Recreating a Task does not answer its question. Approval decisions are separate explicit client.approvals.approve() / deny() calls by an authorized reviewer; the SDK never decides on the user's behalf. See input and approval.
Run the complete backend example
Download sdk-backend.mjs into a directory where the verified SDK version is installed. Set ORBITSPACE_API_URL, ORBITSPACE_TENANT_ID, and either ORBITSPACE_API_TOKEN or the four OAuth variables ORBITSPACE_TOKEN_ENDPOINT, ORBITSPACE_CLIENT_ID, ORBITSPACE_CLIENT_SECRET, ORBITSPACE_SCOPES through your secret manager. For Invocation submission also set ORBITSPACE_DEPLOYMENT_ID.
Create request.json with workspace_id, workspace_agent_binding_id and input. Omit idempotency_key: the example creates and persists it before submission. For a service Invocation, use the deployment's published input shape instead.
node sdk-backend.mjs submit-task job.json request.json
node sdk-backend.mjs watch job.json
node sdk-backend.mjs inputs job.json
node sdk-backend.mjs reply job.json QUESTION_ID answer.json
node sdk-backend.mjs watch job.json
node sdk-backend.mjs results job.json
node sdk-backend.mjs download job.json ARTIFACT_ID result.binanswer.json contains the actual JSON response that satisfies the question's schema. Re-run the exact submit/reply command after an uncertain response; keep job.json. To deliberately stop remote work, run node sdk-backend.mjs cancel job.json. The example exits observation after two minutes without cancelling the execution. It exclusively locks a checkpoint, writes it with mode 0600 and refuses a changed tenant/API/request. After a crash, inspect the checkpoint and remove its .lock directory only after confirming no process is using it. Use a transactional database and durable Inbox for production concurrency, not this single-process file.
Recover events, errors and downloads
client.tasks.events() and the existing watch*() methods expose raw SSE. Save the last business-committed ID as a string and supply afterSequence on resume. observe().cursor is only the latest observed ID; it is not a durable-consumer acknowledgement. Task and Invocation replay semantics differ. Use the paginated event API when a complete ledger is required, and reconcile snapshots after reconnect. See events and recovery.
Resource helpers and client.request() throw OrbitSpaceError with status, code, reason, metadata and requestId. Transport aborts/deadlines retain their native errors. OAuth errors use OrbitSpaceOAuthError without echoing credentials or the server's response body. Raw generated functions retain their { data, error, response } / throwOnError contract. Keep request IDs for support, and keep sensitive request bodies out of logs.
HTTP retries are opt-in and bounded, for GET/HEAD only. They honor a bounded Retry-After; a server delay beyond your configured cap returns the error rather than retrying early. POST controls and submissions are never automatically retried. timeoutMs covers HTTP credential resolution, headers and body; SSE uses its separate observation signal and finite reconnect budget.
Before downloading, confirm that an artifact belongs to the selected Task or Invocation output. client.artifacts.download(id, { signal, maxBytes }) obtains a short-lived receipt, transfers without forwarding the API token, and checks declared size and SHA-256 before returning bytes. Its default destination is the API's /api/v1/artifact-downloads/ path. Only operators should approve alternative origins/path prefixes. Capability URLs are credentials: do not log them. This helper buffers bounded files; use the streaming download example for larger transfers.
Use verifyWebhook() from the package for the platform's exact RFC 9421/9530 signature profile. Verify raw bytes and the configured public URL, atomically admit (source,id) into your Inbox, then acknowledge. See the receiver guide; an in-memory queue is not durable acceptance.
Upgrade from 0.2.x
The admitted generated functions remain available, including taskServiceCreateTask({ client: client.transport, ... }). The new resource helpers are optional. Version 0.3.0 rejects authenticated cross-origin/outside-base-path requests and redirects before forwarding credentials. Audit custom transports and redirecting API proxies before upgrading. Use a separate unauthenticated transport for artifact capability URLs. SDK, API image, OpenAPI and Buf versions are independent; pin the npm version in your lockfile.