TypeScript SDK
Use Algenta from TypeScript or JavaScript — install the SDK, authenticate, and call the engine with a typed client. Includes runnable examples.
The TypeScript and JavaScript client is published to npm as algenta-sdk. It gives you a single AlgentaClient for the hosted control plane and self-hosted engines, a Runtime class for local and self-hosted execution, and exported contract constants so your code can stay in lockstep with the API. It runs on Node.js 18+ and modern browsers, uses fetch with no required dependencies, and ships full type definitions.
Install
Install the public npm package:
npm install algenta-sdkRepository contributors can still build the package from source with pnpm install and pnpm --filter algenta-sdk build.
Quick start
The client reads your API key from config.apiKey first, then ALGENTA_API_KEY, then the legacy DE_API_KEY. Set it once in the environment and the example below runs end to end.
import { AlgentaClient } from "algenta-sdk";
const apiKey = process.env.ALGENTA_API_KEY ?? process.env.DE_API_KEY;
if (!apiKey) {
throw new Error("Set ALGENTA_API_KEY or DE_API_KEY before running this example.");
}
const client = new AlgentaClient({ apiKey, baseUrl: "https://api.algenta.ai" });
const datasets = await client.listDatasets({ search: "nps_scores", compact: true });
const datasetId = datasets.datasets[0].dataset_id;
const summary = await client.getDatasetSummary(datasetId);
console.log(summary.dataset_id, summary.name);Configuration
new AlgentaClient(config) accepts an AlgentaClientConfig:
apiKey
string
process.env.ALGENTA_API_KEY ?? process.env.DE_API_KEY
Required. Read from the environment if not passed.
baseUrl
string
DEFAULT_BASE_URL (https://api.algenta.ai)
Override for self-hosted engines.
timeout
number
SDK default
Per-request timeout in milliseconds (AbortController).
maxRetries
number
SDK default
Retries with exponential backoff; honors Retry-After on 429.
defaultHeaders
Record<string, string>
{}
Merged into every request.
The API key resolves from config.apiKey first, then ALGENTA_API_KEY, then the legacy DE_API_KEY. If none is set, the constructor throws with guidance instead of failing silently.
Exports
The barrel exports the client and runtime classes, their error types, and the generated contract constants:
AlgentaClient
The HTTP client class.
Runtime, RuntimeError, RuntimeConfigurationError, RuntimeValidationError
Runtime class for local / self-hosted use.
MojoRuntime, libraries
Runtime-library entrypoint and catalog.
DecisionEngineError, AuthenticationError, RateLimitError, ValidationError, NotFoundError, ServerError
Client error hierarchy.
MojoExecutionError, MojoFunctionNotRegisteredError, MojoModuleNotRegisteredError, MojoRuntimeConfigurationError, MojoRuntimeError
Runtime-library error types.
DEFAULT_BASE_URL, MCP_ENDPOINT, MCP_TOOLS_ENDPOINT, CONTRACT_VERSION, BRAND
Endpoint and version constants.
API_KEY_PREFIX_LIVE, API_KEY_PREFIX_TEST, AUTH_SCHEME, PLAN_LIMITS, INTEGRATIONS
Contract metadata.
PRIMARY_DATA_QUERY_CONTRACT, CAPABILITY_PLANE_CONTRACT
Machine-readable maps of endpoints, methods, CLI commands, and MCP tools.
type QueryFilterSpec and all other types
Full request/response type surface.
PRIMARY_DATA_QUERY_CONTRACT is generated alongside the engine, so it always names the current method per surface. For example:
Data: datasets and contract
listDatasets({ search, compact, status, sourceName, page, limit })
GET /v1/data
sourceName maps to source_name; compact sends compact=1.
getDataset(datasetId)
GET /v1/data/{id}
Full dataset detail.
getDatasetSummary(datasetId)
GET /v1/data/{id}/summary
Schema, fields, row counts.
getContract()
GET /v1/meta/contract
Falls back to /openapi.json if the contract endpoint is absent.
Querying
The query family is the governed data path. Bodies stay snake_case.
Single query with metadata
queryWithMetadata returns { data, metadata, headers } so you get the response alongside its execution metadata and raw headers.
Batch query
queryBatch runs several keyed queries in one round trip, with optional shared defaults.
The optional defaults.filter accepts a QueryFilterSpec:
Supported filter operators
The governed filter contract supports eq, gt, gte, lt, lte, in, is_null, and is_not_null. Filters apply to normalized rows before aggregation and are valid across SQL and non-SQL backends.
SQL report
querySqlReport runs a read-only SQL report over one or more governed datasets, each given an alias.
queryWithMetadata(request)
POST /v1/query (returns { data, metadata, headers })
queryBatch({ defaults, queries })
POST /v1/query/batch
querySqlReport({ sources, sql, max_rows })
POST /v1/query/sql-report
Capability plane
The capability plane is how the engine discovers, routes, and executes tools, skills, and MCP capabilities.
routeCapabilities(request)
POST /v1/capabilities/route
Returns a CapabilityRoutePlan.
getCapability(id, { includeInstruction })
GET /v1/capabilities/{id}
includeInstruction sends include_instruction=1.
executeCapability(request)
POST /v1/capabilities/execute
Runs the selected capability.
listCapabilities({ kinds, providerIds, bindingIds })
GET /v1/capabilities
Filter by kind, provider, or binding.
recordCapabilityOutcome(request)
POST /v1/capabilities/outcomes
Feed results back for learning.
Providers, skills, and MCP
listMcpProviders() is a convenience filter over listCapabilityProviders(), and listSkills() is listCapabilities({ kinds: ["skill"] }).
Binding lifecycle and skill toggle helpers
There are also full binding lifecycle methods (createCapabilityBinding, testCapabilityBinding, discoverCapabilityBinding, startCapabilityAuthorization, completeCapabilityAuthorization) plus enableSkill / disableSkill helpers.
The Runtime class
Runtime is the entrypoint for self-hosted and local execution. It wraps the same HTTP client but adds mode-awareness, contract validation, and signed runtime-proof checks. It is exported directly:
local
In-process execution; the default.
No network for the local query path.
api
Hosted control plane over HTTP.
apiKey (env or config).
self_hosted
Your own engine over HTTP.
apiKey and an explicit baseUrl.
Runtime introspection
These methods read the engine's signed runtime manifest and validation artifacts. They require API transport (api or self_hosted); calling them in local mode throws local_mode_not_supported.
getRuntimeManifest()
GET /v1/runtime/manifest
Signed manifest of the active runtime build.
getRuntimeModules()
GET /v1/admin/runtime/modules
Registered runtime-library modules.
getRuntimeBenchmarks()
GET /v1/admin/runtime/benchmarks
Published runtime benchmarks.
getRuntimeReleaseValidation()
GET /v1/admin/runtime/validation
Release-validation proof.
The Runtime also re-exposes the data and capability surface (getContract, listDatasets, getDatasetSummary, queryWithMetadata, queryBatch, querySqlReport, routeCapabilities, executeCapability, and more), delegating to the underlying client when in api or self_hosted mode.
Device-binding headers
Every request carries automatic device-binding headers, computed by resolveClientDeviceHeaders (client_device_headers.ts). These let the control plane recognize and bind a stable device without you wiring anything up.
X-Algenta-SDK-Version
The SDK user agent / version.
X-Algenta-Device-Id
A stable, derived device id (16-64 chars).
X-Algenta-Platform
OS platform (Node) or navigator.platform (browser).
X-Algenta-Platform-Version
Node version, when available.
X-Algenta-Hostname-Hash
FNV-1a hash of the hostname seed (never the raw hostname).
How the device id is derived and how to override it
On Node, the device id is derived from the machine id (/etc/machine-id on Linux), the hostname, or a persisted install id under ~/.algenta/runtime/install_id. In the browser it is generated once and stored in localStorage. You can override it with the ALGENTA_DEVICE_ID (or legacy DE_DEVICE_ID) environment variable, or by passing X-Algenta-Device-Id in defaultHeaders:
Errors
All client errors extend DecisionEngineError and carry a normalized errorCode, statusCode, and details.
AuthenticationError
401
No
NotFoundError
404
No
ValidationError
422
No
RateLimitError
429
Yes, honoring Retry-After
ServerError
5xx
Yes, with exponential backoff
DecisionEngineError
other
Base class
Environment variables
ALGENTA_API_KEY
Primary API key.
DE_API_KEY
Legacy fallback for the API key.
ALGENTA_DEVICE_ID / DE_DEVICE_ID
Override the derived device id.
ALGENTA_RUNTIME_DIR
Directory for the persisted install id (defaults to ~/.algenta/runtime).
Agent runs
Agent runs drive a task through the engine's tool loop with deterministic, replayable checkpoints. You create a run, watch its events stream in, approve or resume it when it pauses for a gated action, and fork or replay it from any checkpoint. Every run carries a request_hash so the same task against the same snapshots is reproducible. See the agent runs guide for the full lifecycle.
When a run pauses for a gated action, advance it with approveAgentRun (or override with resumeAgentRun); stop it early with cancelAgentRun. Branch a new run from a checkpoint with forkAgentRun, or re-execute deterministically from one with replayAgentRun.
createAgentRun(request)
POST /v1/agent/runs
request is an AgentRunCreateRequest (task, max_steps, approval_mode, tools, start_paused).
getAgentRun(runId)
GET /v1/agent/runs/{id}
Current run state, including request_hash.
streamAgentRunEvents(runId, { limit })
GET /v1/agent/runs/{id}/events?stream=true
Async generator of agent.run.event / agent.run.completed messages.
approveAgentRun(runId)
POST /v1/agent/runs/{id}/approve
Approve a pending gated action.
resumeAgentRun(runId)
POST /v1/agent/runs/{id}/resume
Continue a paused run.
cancelAgentRun(runId)
POST /v1/agent/runs/{id}/cancel
Stop the run.
forkAgentRun(runId, { checkpoint_id })
POST /v1/agent/runs/{id}/fork
New run branched from a checkpoint.
replayAgentRun(runId, { checkpoint_id })
POST /v1/agent/runs/{id}/replay
Deterministic re-execution from a checkpoint.
Async jobs
Long-running simulations run as async jobs: you submit a SimulateRequest, get back a job_id and poll_url, then poll until the result is ready. pollJob is the convenience wrapper that polls getJob for you and returns the result once the job completes. An optional callbackUrl lets the engine deliver a webhook instead of (or alongside) polling. See the async jobs guide.
Expected result: submitJob returns a JobSubmitResponse with job_id, status: "queued", and a poll_url.
To poll by hand, read the status with getJob, fetch the payload with getJobResult once status === "completed", browse history with listJobs, and stop in-flight work with cancelJob.
submitJob(request, callbackUrl?)
POST /v1/jobs
request is a SimulateRequest; callbackUrl maps to callback_url.
getJob(jobId)
GET /v1/jobs/{id}
Job status (job_id, run_id, status).
getJobResult(jobId)
GET /v1/jobs/{id}/result
The completed result payload.
pollJob(jobId, { timeoutMs, pollIntervalMs })
polls GET /v1/jobs/{id}
Resolves to the result once the job completes.
listJobs({ page, limit, status })
GET /v1/jobs/list
Paginated job history, filterable by status.
cancelJob(jobId)
POST /v1/jobs/{id}/cancel
Cancels a queued or running job.
Repository intelligence
Repository intelligence turns a code repository into governed, queryable evidence. You snapshot the repo, triage an issue against it to get ranked evidence, query the symbol graph, simulate a candidate decision plan, and apply the result as a patch, branch, or pull request. Start by checking which languages the engine supports with getRepositoryIntelligenceCapabilities. See the repository intelligence guide.
getRepositoryIntelligenceCapabilities()
GET /v1/repositories/capabilities
Supported languages and support progress.
createRepositorySnapshot(repositoryId, request)
POST /v1/repositories/{id}/snapshots
request is a RepositorySnapshotCreateRequest.
triageRepository(repositoryId, request)
POST /v1/repositories/{id}/triage
Ranked evidence from signals (issue_text, failing_tests, changed_files).
queryRepositoryGraph(repositoryId, request)
POST /v1/repositories/{id}/graph-query
Symbol/file graph; direction is inbound, outbound, or both.
simulateRepository(repositoryId, request)
POST /v1/repositories/{id}/simulate
Returns a DecisionEnvelope for a decision_plan_id.
applyRepository(repositoryId, request)
POST /v1/repositories/{id}/apply
mode is patch_only, local_branch, or remote_pr.
Related pages
Authentication & API keysPython SDKAPI endpoint referenceSelf-hostingLast updated
Was this helpful?