Skip to content

JavaScript SDK reference

The JavaScript SDK calls the HTTP service and keeps a local representation of each session. ExecKernelClient performs service operations; Session holds the latest validated state and payload. Your application reads that payload to display choices or terminal output, then submits an edge selection through the session.

This is the lookup reference for the CommonJS package @execkernel/sdk. Its root runtime entry is index.js and its TypeScript entry is index.d.ts. For a complete application sequence, use JavaScript and TypeScript SDK. The server’s accepted fields are specified separately in HTTP API endpoints.

Runtime export Responsibility
ExecKernelClient Start, restore, inspect, query status and delete sessions; inherits EventEmitter.
Session Local session data, start/select operations and snapshot import/export.
HttpTransport JSON requests through native or injected fetch.
EventEmitter Best-effort application observers.
ExecKernelError Normalized SDK and remote errors.
ContextBuilder, EdgeChoiceBuilder Immutable input builders.
PayloadTypeGuards Object with isNodePayload and isTerminalPayload.
isNodePayload, isTerminalPayload The same predicates exported directly.

Root type exports are NodePayload, TerminalPayload, Payload, SessionState, SessionHistory, SessionTimestamps, Context, ContextValue, BuilderContext, BuilderContextValue, GraphInspectResponse, SessionStatusResponse, JsonObject, JsonValue and DeepReadonly<T>. The entry also declares the options, transport, snapshot and request/response interfaces described below.

JsonValue is a JSON scalar, array or object; JsonObject is Record<string, JsonValue>. DeepReadonly<T> recursively exposes readonly properties and arrays in TypeScript. Runtime checks additionally reject non-finite numbers, unsafe integer numbers, circular data, sparse arrays, accessors and unsupported object types. A TypeScript annotation does not bypass those checks.

new ExecKernelClient(options: ExecKernelClientOptions) takes:

Option Type Default and behavior
baseUrl Required string HTTP(S) service root; trailing slashes are removed. User information, query, fragment, spaces and control characters are rejected.
flowId Required string Default graph identifier for start and inspect; must be non-empty when used.
apiKey Optional string If present, sent as Authorization: Bearer ….
fetchImpl Optional typeof fetch Global fetch when available. A fetch implementation is required.
lang Optional string Included in start/resume requests and retained in local Session data.
correlationId Optional string | null Defaults to null; included as X-Correlation-Id when present.

Invalid URL/fetch configuration can throw TypeError during construction. These are configuration errors, before an asynchronous SDK operation.

The package declares no minimum Node version in an engines field. Its declarations refer to fetch types; the package’s typecheck uses TypeScript 5.9.3 with ES2022,DOM libraries. These are the declared development settings, not an additional runtime installation procedure.

These are TypeScript signatures for lookup:

Method Result and operation
startSession(context?: Context): Promise<Session> Defaults context to {}. Starts a server session and returns a Session with its validated response.
inspect(flowId?: string): Promise<GraphInspectResponse> Uses the supplied identifier or the client’s flowId. Posts {flow} to /execkernel/graph/inspect.
status(sessionId: string): Promise<SessionStatusResponse> Gets /execkernel/sessions/{encoded-id}/status and validates any echoed identity.
destroy(sessionId: string): Promise<boolean> Deletes /execkernel/session/{encoded-id}; resolves to whether deleted === true.
restoreSession(session: string | SessionSnapshotPayload): Promise<Session> Uses remote resume for an ID-only reference; imports locally when the object contains state or payload.

For a string or an object containing only identity metadata, restoration posts session_id and the client’s configured language to /execkernel/session/resume. A snapshot containing state or payload takes the local import branch and makes no request. In either case the returned Session has the client’s transport and emitter.

Remote start/select/resume replies must include an outer session ID, a state object and a non-null payload. The SDK rejects conflicting identities, inconsistent node/terminal data and persisted: false. A failed operation does not replace the Session’s previously confirmed local data.

new Session(args?) accepts sessionId?: string, state?: SessionState (default {}), payload?: Payload | null (default null), transport?: SessionTransport | null, emitter?: EventEmitter | null, flowId?: string, lang?: string | null and correlationId?: string | null (default null).

A Session can therefore exist as local data without a transport. Calling remote operations requires a compatible transport and the relevant flow/session identifier.

Property or getter Declared type and meaning
sessionId Readonly optional string identifying the remote session.
state Readonly DeepReadonly<SessionState>.
currentPayload Readonly DeepReadonly<Payload> | null.
flowId, lang, correlationId Readonly configuration metadata; correlation defaults to null.
currentNode DeepReadonly<NodePayload> | null; null for a terminal payload or missing payload.
context DeepReadonly<Context> | null; null when the state has no context.
history DeepReadonly<SessionHistory | number[]> | null. Falls back to top-level edges/nodes when present.
timestamps SessionTimestamps | null; a fresh projection of any supplied timestamps.
transport, emitter Optional mutable references to the transport and observer object.

State and payload are copied, validated and deeply frozen at runtime. Exported snapshots and the timestamp projection are detached data. The optional shape permits legacy reduced snapshots; missing timestamps or context are not fabricated.

Signature Behavior
start(context?: Context): Promise<DeepReadonly<Payload>> Defaults context to {}. Posts flow, context and optional lang to start; replaces local data after a valid reply. Starting again creates another server session; it does not delete the old one.
selectEdge(edgeId: number, context?: Context): Promise<DeepReadonly<Payload>> Posts session_id, edge_id, context (default {}) and local lang when supplied. Updates the Session after validation and returns its current payload.
import(snapshot: SessionSnapshotPayload): this Validates and merges supplied local fields synchronously. Performs no HTTP request.
export(): SessionSnapshotPayload & {state: SessionState; payload: Payload | null; correlationId: string | null} Returns a detached, mutable copy.

An edge ID must be a JavaScript safe integer. The independent API ignores lang on next even though Session includes it; that endpoint uses the server snapshot’s language.

A Session rejects overlapping start/select/import operations. Sessions created by one client also share an in-flight guard for the same session ID, covering remote restoration and deletion. This guard rejects overlap with EK-SESSION-002; it does not queue operations, lock another client or implement server-side concurrency control.

Type Fields
Context Record<string, JsonValue>. This is the SDK data type; the independent API has a narrower scalar-only request contract.
BuilderContext Record<string, BuilderContextValue>; values are JSON scalars or flat arrays of JSON scalars.
NodePayload Required type: 'node', nodeId: number, edges; optional nullable title, subtitle, description and extras.
TerminalPayload Required type: 'terminal', nodeId: number, outputs; the same optional presentation fields.
SessionHistory Optional edges: number[], nodes: number[], overflow_policy: string.
SessionTimestamps Optional number fields created_at, updated_at, last_transition_at.
GraphInspectResponse Required nodes, edges and labels arrays. Nodes contain id/isTerminal; edges contain id/fromNode/toNode; labels contain edgeId/lang/text and optional description/extras.
SessionStatusResponse currentNode: number, optional nullable nodeStatus: string and logsTail: unknown[]. The current status normalizer returns null for missing status/log fields.

SessionState makes its fields optional for reduced snapshots: session_id/sessionId, graph_code, flow_id (number/string/null), current-node aliases current_node/currentNode/node_id/nodeId, is_terminal/isTerminal, context, history (object or number list), top-level edges/nodes, the three timestamps, and nullable graph_version/dsl_version.

Node edges contain id and optional label, from, to, labels, enabled, availability and disabledReason. Availability is available | blocked | pending. Edge labels contain text and optional nullable description/extras. Terminal outputs contain a required string type and optional nullable url, label, lang, content and openBehavior.

The runtime normalizes payload IDs to nodeId and edge IDs to id, converts disabled_reason/open_behavior to camelCase, and derives an edge’s simple label from its first label record when needed. It retains the declared payload fields and extras rather than arbitrary extra output properties. State retains its validated wire field names; it is not globally converted to camelCase. Conflicting aliases fail instead of choosing one silently. Node and terminal payloads explains the engine-facing fields.

Both predicates accept unknown and return a TypeScript guard for DeepReadonly<NodePayload> or DeepReadonly<TerminalPayload>. They check the supplied normalized shape, including type and nodeId. They do not repair a raw snake-case payload or freeze an arbitrary input object. Session’s own payload data is already normalized and frozen.

The root types also include:

Interface Declared fields
SessionStartPayload flow: string, optional context: Context, lang: string.
SessionNavigatePayload session_id: string, edge_id: number, optional context: Context and lang: string | null.
SessionResumePayload session_id: string, optional lang: string | null.
EdgeChoicePayload edge_id: number, optional context: BuilderContext and lang: string.
SessionResponsePayload Required state: SessionState, payload: JsonObject; optional session_id/sessionId, persisted: boolean and trace_id: string.
RequestScope Optional nullable sessionId and correlationId.
SessionTransport post(path: string, body: JsonObject, scope?: RequestScope): Promise<unknown>.

These declarations describe representable data. Remote response validation still requires an identity and consistent state/payload, and the server still decides which request fields it consumes.

Builder Constructor and methods
ContextBuilder constructor(values?: BuilderContext) with {} default; static from(values?: BuilderContext): ContextBuilder; with(key: string, value: BuilderContextValue), remove(key: string) and merge(values: BuilderContext) return a new builder; toObject() and toJSON() return BuilderContext.
EdgeChoiceBuilder constructor(args?: {edgeId?: number | null; context?: BuilderContext | ContextBuilder; lang?: string | null}). Defaults are null, empty context and null. withEdgeId(number), withContext(BuilderContext | ContextBuilder) and withLang(string | null) return a new builder. toObject()/toJSON() return EdgeChoicePayload; toJson(): string returns JSON text.

Builder instances are frozen. Context values may include null and flat scalar arrays; nested objects/lists are rejected by the convenience builder. Direct Context accepts broader JSON data, while the independent API rejects null, array and object values in incoming context. A successful builder call is therefore not a server validation result.

An edge ID is required when exporting a choice. Empty context and null language are omitted. Pass the exported edge ID and context to selectEdge; that method does not accept a builder object.

SessionSnapshotPayload has optional sessionId/session_id, state, payload, flowId/flow_id, nullable lang and nullable correlationId/correlation_id. SessionSnapshot is an alias of this type. Exports use camelCase outer identifiers and always include state, payload and correlation ID. Import validates aliases, node/payload relationships and timestamp ordering. Changing session identity requires both state and payload, avoiding a mixture of two sessions.

This example constructs a local representation of a review screen at node 4 with confirmation edge 7. It demonstrates data handling without a running graph or backend:

const { Session } = require('@execkernel/sdk');
const session = new Session({
sessionId: 'reference-session',
state: { current_node: 4, context: { reviewed: false } },
payload: {
type: 'node', nodeId: 4, title: 'Review the record',
edges: [{ id: 7, label: 'Confirm' }],
},
});
const snapshot = session.export();
snapshot.state.context.reviewed = true;
const restored = new Session().import(snapshot);

The original session still has reviewed: false; the imported representation has reviewed: true and the same title. Neither operation creates, resumes or rewinds a backend session. Use client.restoreSession(sessionId) to fetch the backend’s current state.

Download the JavaScript example or its TypeScript equivalent. They also demonstrate immutable builders and the payload guard. Exporting the original session again produces:

{
"sessionId": "reference-session",
"state": {"current_node": 4, "context": {"reviewed": false}},
"payload": {
"type": "node",
"nodeId": 4,
"title": "Review the record",
"edges": [{"id": 7, "label": "Confirm"}]
},
"correlationId": null
}

Its constructor takes {baseUrl, apiKey?, fetchImpl?, emitter?, correlationId?, sessionId?}. Correlation and session IDs default to null. Methods are post<T = JsonObject>(path: string, body?: JsonObject, scope?: RequestScope): Promise<T>, get<T = JsonObject>(path: string, scope?: RequestScope): Promise<T> and delete<T = JsonObject>(path: string, scope?: RequestScope): Promise<T>. The post body defaults to {}. setSessionId(id: string | null): void and setCorrelationId(id: string | null): void change defaults for direct transport calls.

An explicit scope field overrides the transport default, including null to omit that header. Client-created Session operations supply their own scope. Requests set JSON content type, optional bearer/correlation/session headers and redirect: 'manual'. The SDK has no retry policy, timeout option or AbortSignal parameter; any added deadline must come from the fetch implementation you supply. It sends no SDK/API version declaration automatically.

The transport reads and validates a JSON object and rejects duplicate keys when raw response text is available. The injected legacy response fallback can provide only json(), which cannot reveal duplicate original keys. The generic result type T is not an additional runtime schema check.

ExecKernelError extends Error with ekCode: string, type: string, context: JsonObject, optional severity: string and optional hint: string | null. Its constructor accepts a payload whose fields are optional: ek_code, type, message, context, severity and hint. TypeScript requires that payload argument; runtime JavaScript also accepts no argument. isCode(prefix: string): boolean checks a prefix, and static fromUnknown(error: unknown): ExecKernelError normalizes an existing error or envelope.

Failure Result
Invalid local data or inconsistent snapshot/response Usually EK-SESSION-002 with type InvalidState and context.field. Invalid session IDs/flow inputs can use EK-INPUT-400.
Fetch rejects EK-EXTERNAL-000, type NetworkError.
Invalid JSON response EK-SYS-003 for 2xx; EK-EXTERNAL-000 otherwise, type InvalidResponse.
HTTP 3xx–5xx or non-false/non-null error Normalized remote error; status and valid trace header are attached to context.
Explicit persisted: false EK-SYS-002, type PersistenceError.

Remote code aliases ek_code/ekCode/code must agree; absent or conflicting codes fall back to EK-EXTERNAL-000. The independent API’s missing-session response is HTTP 400 / EK-INPUT-400, rather than a synthesized domain session code. See Error codes and exceptions.

EventEmitter.on(event: string, handler): () => void returns an unsubscribe function; off(event, handler): void removes a handler; emit(event, payload?): void invokes observers. Handlers may return promises, but operation completion does not await them; thrown/rejected listener errors are contained.

SDK event Payload
session:start The Session after successful start.
session:node / session:terminal The normalized payload after start, selection or restoration.
session:error A reduced ExecKernelError with structural code and safe HTTP/trace metadata.
http:request / http:response Structural method, endpoint pattern and, for responses, status and error code when available.

These event payloads differ from PHP’s event arrays. The structural HTTP/error projection omits raw credentials and business bodies; successful session events expose application data. Your application decides how those observers use it.