The v2 SDK migration (#5273, #6564) shipped five breaking changes in both
SDKs but got the release mechanics wrong in three separate ways, and left
one of the two rewrites unable to complete a single successful call.
Versions. packages/ts-sdk/package.json read 0.1.3 -- a patch digit added
inside an unrelated compatibility commit, never deliberated. npm expands
^0.1.2 to >=0.1.2 <0.2.0, so every existing consumer would have picked the
break up on a lockfile refresh: AsyncExecutionResult.jobId renamed to
runId, executionId dropped from that interface, a failed sync run now
throwing instead of resolving {success:false}, the request body reshaped,
and the endpoint moved to /api/v2 with no fallback. 0.2.0 excludes every
existing range, so the upgrade becomes opt-in. packages/python-sdk carries
the identical break and was never bumped at all, so its publish job would
have skipped green at the "version already exists" gate and left the repo
and PyPI silently divergent; it moves 0.1.2 -> 0.2.0 in lockstep, along
with the __version__ string in simstudio/__init__.py, which tracks
pyproject and would otherwise have started lying. setup.py is left at
0.1.1: it is unchanged from main and demonstrably unread (0.1.2 published
from pyproject while setup.py already said 0.1.1). It wants deleting, in
its own commit.
A 404 fallback was considered and rejected. The legacy 202 body's statusUrl
points at /api/jobs/{jobId}, so mapping jobId onto runId would hand the
caller an id that getWorkflowRun cannot resolve against that same old
server -- a successful execute followed by an inexplicable failure on the
next call is a worse contract than a clean 404. Both READMEs instead state
the minimum server version and name the endpoint to check for.
Cancelled runs. packages/python-sdk computed success as status != 'failed',
so a run cancelled out of band reported success=True. The TypeScript SDK
uses a closed whitelist and reports False, and before the migration both
SDKs read the server's own value, which was False -- so this was a Python
regression, not merely an inconsistency. Fixed by mirroring the whitelist.
The v2 contract enumerates exactly completed|failed|paused|cancelled, so
narrowing the blacklist to a whitelist cannot drop a live value, and a
status added later now defaults to "not successful" rather than silently
reporting True. WorkflowExecutionResult gains a status field because
Python, unlike TypeScript, does not throw on 'failed' -- so success=False
alone is ambiguous there in a way it is not in the TypeScript SDK, which
is why status is not added to both.
Rate-limit header. Found while auditing the two SDKs for further
divergence, and the reason the Python bump could not have shipped as it
stood: every authenticated v2 response now carries X-RateLimit-Reset as an
ISO 8601 timestamp (recorded by v2RateLimits.publicApi, stamped by
withRouteHandler). The Python SDK parsed it with int(), raising a bare
ValueError that no handler in execute_workflow catches -- so every
successful v2 execution raised instead of returning. None of the legacy
endpoints the SDK previously called record a rate-limit snapshot, which is
why the latent int() survived until the v2 move. The TypeScript SDK
already branches on the format; _parse_reset_header mirrors it, including
degrading an unrecognised value to 0, because a quota hint must not take
down the call it rode in on.
Timing metadata. The v2 rewrite stopped forwarding startedAt/endedAt, which
main passed through and the TypeScript SDK still reports; restored under
the same startTime/endTime keys the TypeScript SDK uses.
Tests: cancelled/failed/paused status coverage, the ISO reset header, and
the restored metadata keys, each verified red against the unfixed line
first. The TypeScript suite gains matching cancelled/paused and ISO-reset
pins -- they pass against today's source by design, and were confirmed to
fail against a deliberately degraded copy so they are not toothless.
Deliberately not included: a CI guard failing a PR that changes SDK source
without a version bump. It would have caught this twice over, but it is a
new script and workflow rather than a fix to the defect at hand.
Review revision. bun.lock recorded packages/ts-sdk at 0.1.3 and was left
stale by the first pass, so the repo asserted two versions for the same
workspace package -- in a change whose whole thesis is that the version
strings had diverged. It does not break CI (bun 1.3.14 accepts the
mismatch under --frozen-lockfile, confirmed here), but 092311ea68 bumped
the lock in lockstep with package.json, and the next unfrozen install
would otherwise drop the line into an unrelated PR.
_parse_reset_header gated the numeric branch on str.isdigit(), which
accepts characters int() rejects ('²'.isdigit() is True, int('²')
raises) -- and that int() sits outside the try, so the one function added
to stop a quota hint raising could still raise, contradicting its own
docstring. str.isdecimal() is exactly the set int() accepts. The
tolerates-unparseable test is parametrized over both forms and was
confirmed red on '²' against isdigit.
Docs and docstrings: apps/docs api-reference/python.mdx mirrors the
README's dataclass block and was the only copy left without the new
status field. RateLimitInfo now names its units, because reset is epoch
seconds for the legacy integer and milliseconds for the ISO form that v2
sends. execute_workflow's Args entry still described the pre-v2 body
shape ("spread at root level"); every input is nested under input now,
and this is the commit that ships that help() text to PyPI. The
"declared last so positional construction keeps working" sentence was a
maintainer's note that belongs in this message, not in every user's
help(WorkflowExecutionResult).
Sim TypeScript SDK
The official TypeScript/JavaScript SDK for Sim, allowing you to execute workflows programmatically from your applications.
Server compatibility
0.2.x talks to the v2 API and has no fallback to the older endpoints, so it requires a Sim deployment that serves POST /api/v2/workflows/{id}/execute. That surface is newer than the endpoints 0.1.x used, and a deployment can also have it switched off — a self-hosted build serves /api/v2 only when the operator enables V2_API. Where it is unavailable every v2 route answers 404, so executeWorkflow fails with HTTP 404: Not Found — enable or upgrade the v2 API on the server, or stay on simstudio-ts-sdk@0.1.x, which keeps using /api/workflows/{id}/execute and /api/jobs/{id}.
Upgrading from 0.1.x to 0.2.0
0.2.0 is a breaking release. It is a minor bump rather than a patch precisely so that ^0.1.2 does not pick it up — you upgrade when you choose to.
- Requests move to
/api/v2.executeWorkflowposts to/api/v2/workflows/{id}/execute, sends the workflow input nested underinput, and carriesasync/executionTimeoutSecondsin the body instead of theX-Execution-ModeandX-Execution-Timeout-Secondsheaders. AsyncExecutionResult.jobIdis nowrunId, andexecutionIdhas been removed from that interface. Replaceresult.jobIdwithresult.runId.getJobStatus(taskId)is legacy. It still calls/api/jobs/{taskId}and only resolves IDs from a0.1.xasync execution. For runs started by0.2.x, usegetWorkflowRun(workflowId, runId), which reads/api/v2/workflows/{id}/runs/{runId}and returns a typedWorkflowRunStatus.- A failed synchronous run now throws. Previously it resolved with
{ success: false }; it now rejects with aSimStudioErrorcarrying the server'serror.codeanderror.message. Anyif (!result.success)branch that handled failures must move into acatch. successis derived from the run status. It istrueforcompletedandpausedruns only, so a run cancelled while it was in flight resolves withsuccess: falserather than throwing. Combined with the point above: a rejection means the run failed, and a resolvedsuccess: falsemeans it was cancelled.
Installation
npm install simstudio-ts-sdk
# or
yarn add simstudio-ts-sdk
# or
bun add simstudio-ts-sdk
Quick Start
import { SimStudioClient } from 'simstudio-ts-sdk';
// Initialize the client
const client = new SimStudioClient({
apiKey: 'your-api-key-here',
baseUrl: 'https://sim.ai' // optional, defaults to https://sim.ai
});
// Execute a workflow
try {
const result = await client.executeWorkflow('workflow-id');
console.log('Workflow executed successfully:', result);
} catch (error) {
console.error('Workflow execution failed:', error);
}
API Reference
SimStudioClient
Constructor
new SimStudioClient(config: SimStudioConfig)
config.apiKey(string): Your Sim API keyconfig.baseUrl(string, optional): Base URL for the Sim API (defaults tohttps://sim.ai)
Methods
executeWorkflow(workflowId, input?, options?)
Execute a workflow with optional input data.
// With object input (sent as the v2 input object)
const result = await client.executeWorkflow('workflow-id', {
message: 'Hello, world!'
});
// With primitive input (sent as { input: { input: value } })
const result = await client.executeWorkflow('workflow-id', 'NVDA');
// With options
const result = await client.executeWorkflow('workflow-id', { message: 'Hello' }, {
timeout: 60000,
async: true,
executionTimeoutSeconds: 3600
});
Parameters:
workflowId(string): The ID of the workflow to executeinput(any, optional): Input data to pass to the workflow. Objects become the v2inputobject; primitives and arrays become{ input: value }inside it. File objects are automatically converted to base64.options(ExecutionOptions, optional):timeout(number): Timeout in milliseconds (default: 30000)stream(boolean): Enable streaming responsesselectedOutputs(string[]): Block outputs to stream (e.g.,["agent1.content"])async(boolean): Execute asynchronously and return a run IDexecutionTimeoutSeconds(number): Server-side async execution cap from 1 to 604800 seconds. Requiresasync: trueand cannot extend the account policy.
Returns: Promise<WorkflowExecutionResult | AsyncExecutionResult>
Synchronous executions that finish with status: 'failed' reject with SimStudioError.
getWorkflowStatus(workflowId)
Get the status of a workflow (deployment status, etc.).
const status = await client.getWorkflowStatus('workflow-id');
console.log('Is deployed:', status.isDeployed);
Parameters:
workflowId(string): The ID of the workflow
Returns: Promise<WorkflowStatus>
validateWorkflow(workflowId)
Validate that a workflow is ready for execution.
const isReady = await client.validateWorkflow('workflow-id');
if (isReady) {
// Workflow is deployed and ready
}
Parameters:
workflowId(string): The ID of the workflow
Returns: Promise<boolean>
executeWorkflowSync(workflowId, input?, options?)
Execute a workflow and poll for completion (useful for long-running workflows).
const result = await client.executeWorkflowSync('workflow-id', { data: 'some input' }, {
timeout: 60000
});
Parameters:
workflowId(string): The ID of the workflow to executeinput(any, optional): Input data to pass to the workflowoptions(ExecutionOptions, optional):timeout(number): Timeout for the initial request in milliseconds
Returns: Promise<WorkflowExecutionResult>
getWorkflowRun(workflowId, runId, options?)
Get the status and optional outputs of a workflow run. Use the runId returned by async execution.
const status = await client.getWorkflowRun('workflow-id', 'run-id', {
includeOutput: true,
selectedOutputs: ['agent.content']
});
console.log('Run status:', status.status);
Parameters:
workflowId(string): The workflow IDrunId(string): The run ID returned from async executionoptions.includeOutput(boolean, optional): Include the final output for completed executionsoptions.selectedOutputs(string[], optional): Block output selectors to include
Returns: Promise<WorkflowRunStatus>
getJobStatus(jobId)
Get the status of a job created through the legacy async execution endpoint. New integrations should use getWorkflowRun() with a run ID.
const status = await client.getJobStatus('legacy-job-id');
Returns: Promise<JobStatusResult>
executeWithRetry(workflowId, input?, options?, retryOptions?)
Execute a workflow with automatic retry on rate limit errors.
const result = await client.executeWithRetry('workflow-id', { message: 'Hello' }, {
timeout: 30000
}, {
maxRetries: 3,
initialDelay: 1000,
maxDelay: 30000,
backoffMultiplier: 2
});
Parameters:
workflowId(string): The ID of the workflow to executeinput(any, optional): Input data to pass to the workflowoptions(ExecutionOptions, optional): Execution optionsretryOptions(RetryOptions, optional):maxRetries(number): Maximum retry attempts (default: 3)initialDelay(number): Initial delay in ms (default: 1000)maxDelay(number): Maximum delay in ms (default: 30000)backoffMultiplier(number): Backoff multiplier (default: 2)
Returns: Promise<WorkflowExecutionResult | AsyncExecutionResult>
getRateLimitInfo()
Get current rate limit information from the last API response.
const rateInfo = client.getRateLimitInfo();
if (rateInfo) {
console.log('Remaining requests:', rateInfo.remaining);
}
Returns: RateLimitInfo | null
getUsageLimits()
Get current usage limits and quota information.
const limits = await client.getUsageLimits();
console.log('Current usage:', limits.usage);
Returns: Promise<UsageLimits>
setApiKey(apiKey)
Update the API key.
client.setApiKey('new-api-key');
setBaseUrl(baseUrl)
Update the base URL.
client.setBaseUrl('https://my-custom-domain.com');
Types
WorkflowExecutionResult
interface WorkflowExecutionResult {
success: boolean;
executionId?: string;
output?: any;
error?: string;
logs?: any[];
metadata?: {
duration?: number;
executionId?: string;
runId?: string;
startTime?: string;
endTime?: string;
[key: string]: any;
};
traceSpans?: any[];
totalDuration?: number;
}
LargeValueRef
Oversized execution values may be returned as a versioned reference inside output, logs, streaming events, or execution status responses.
The key field is an opaque execution-scoped server storage pointer, not a client-readable download URL.
interface LargeValueRef {
__simLargeValueRef: true;
version: 1;
id: string;
kind: 'array' | 'object' | 'string' | 'json';
size: number;
key?: string;
executionId?: string;
preview?: unknown;
}
WorkflowStatus
interface WorkflowStatus {
isDeployed: boolean;
deployedAt?: string;
needsRedeployment: boolean;
}
SimStudioError
class SimStudioError extends Error {
code?: string;
status?: number;
}
AsyncExecutionResult
interface AsyncExecutionResult {
success: boolean;
runId: string;
statusUrl: string;
message: string;
async: true;
}
RateLimitInfo
interface RateLimitInfo {
limit: number;
remaining: number;
reset: number;
retryAfter?: number;
}
UsageLimits
interface UsageLimits {
success: boolean;
rateLimit: {
sync: {
isLimited: boolean;
limit: number;
remaining: number;
resetAt: string;
};
async: {
isLimited: boolean;
limit: number;
remaining: number;
resetAt: string;
};
authType: string;
};
usage: {
currentPeriodCost: number;
limit: number;
plan: string;
};
}
ExecutionOptions
interface ExecutionOptions {
timeout?: number;
stream?: boolean;
selectedOutputs?: string[];
async?: boolean;
executionTimeoutSeconds?: number;
}
RetryOptions
interface RetryOptions {
maxRetries?: number;
initialDelay?: number;
maxDelay?: number;
backoffMultiplier?: number;
}
Examples
Basic Workflow Execution
import { SimStudioClient } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
apiKey: process.env.SIM_API_KEY!
});
async function runWorkflow() {
try {
// Check if workflow is ready
const isReady = await client.validateWorkflow('my-workflow-id');
if (!isReady) {
throw new Error('Workflow is not deployed or ready');
}
// Execute the workflow
const result = await client.executeWorkflow('my-workflow-id', {
message: 'Process this data',
userId: '12345'
});
if (result.success) {
console.log('Output:', result.output);
console.log('Duration:', result.metadata?.duration);
} else {
console.error('Workflow failed:', result.error);
}
} catch (error) {
console.error('Error:', error);
}
}
runWorkflow();
Error Handling
import { SimStudioClient, SimStudioError } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
apiKey: process.env.SIM_API_KEY!
});
async function executeWithErrorHandling() {
try {
const result = await client.executeWorkflow('workflow-id');
return result;
} catch (error) {
if (error instanceof SimStudioError) {
switch (error.code) {
case 'UNAUTHORIZED':
console.error('Invalid API key');
break;
case 'TIMEOUT':
console.error('Workflow execution timed out');
break;
case 'USAGE_LIMIT_EXCEEDED':
console.error('Usage limit exceeded');
break;
case 'INVALID_JSON':
console.error('Invalid JSON in request body');
break;
default:
console.error('Workflow error:', error.message);
}
} else {
console.error('Unexpected error:', error);
}
throw error;
}
}
Environment Configuration
// Using environment variables
const client = new SimStudioClient({
apiKey: process.env.SIM_API_KEY!,
baseUrl: process.env.SIM_BASE_URL // optional
});
File Upload
File objects are automatically detected and converted to base64 format. Include them in your input under the field name matching your workflow's API trigger input format:
The SDK converts File objects to this format:
{
type: 'file',
data: 'data:mime/type;base64,base64data',
name: 'filename',
mime: 'mime/type'
}
Alternatively, you can manually provide files using the URL format:
{
type: 'url',
data: 'https://example.com/file.pdf',
name: 'file.pdf',
mime: 'application/pdf'
}
import { SimStudioClient } from 'simstudio-ts-sdk';
import fs from 'fs';
const client = new SimStudioClient({
apiKey: process.env.SIM_API_KEY!
});
// Node.js: Read file and create File object
const fileBuffer = fs.readFileSync('./document.pdf');
const file = new File([fileBuffer], 'document.pdf', { type: 'application/pdf' });
// Include files under the field name from your API trigger's input format
const result = await client.executeWorkflow('workflow-id', {
documents: [file], // Field name must match your API trigger's file input field
instructions: 'Process this document'
});
// Browser: From file input
const handleFileUpload = async (event: Event) => {
const inputEl = event.target as HTMLInputElement;
const files = Array.from(inputEl.files || []);
const result = await client.executeWorkflow('workflow-id', {
attachments: files, // Field name must match your API trigger's file input field
query: 'Analyze these files'
});
};
Getting Your API Key
- Log in to your Sim account
- Navigate to your workflow
- Click on "Deploy" to deploy your workflow
- Select or create an API key during the deployment process
- Copy the API key to use in your application
Development
Running Tests
To run the tests locally:
-
Clone the repository and navigate to the TypeScript SDK directory:
cd packages/ts-sdk -
Install dependencies:
bun install -
Run the tests:
bun run test
Building
Build the TypeScript SDK:
bun run build
This will compile TypeScript files to JavaScript and generate type declarations in the dist/ directory.
Development Mode
For development with auto-rebuild:
bun run dev
Requirements
- Node.js 18+
- TypeScript 5.0+ (for TypeScript projects)
License
Apache-2.0