Builders, payloads and session snapshots
SDK helpers support the work around a session operation. A builder prepares an input object from values supplied by your application. A payload describes the current choices or terminal result. A session snapshot saves the client’s representation of a session so your application can read it again later.
These objects have different jobs. Building a choice does not select it, and importing a snapshot does not recreate or rewind the session kept by the backend. The actual change happens through a client operation. This guide shows how to connect the helpers to the PHP SDK and JavaScript SDK already configured in your application.
Prepare a choice from application facts
Section titled “Prepare a choice from application facts”Context builders let you assemble the facts used by a graph without changing an existing input object. Edge choice builders combine the selected edge ID with optional context and language fields. Both PHP and JavaScript return new builder objects from their with…() methods, so retain the returned value.
We reuse the learning-path graph introduced in Anatomy of a graph. It offers a guide through edge 101 and practice through edge 102; practice requires the boolean practiceEnabled. Here, your application first has a base configuration with practice disabled, then enables it after checking that the exercise is available:
const { ContextBuilder, EdgeChoiceBuilder } = require('@execkernel/sdk');
const base = ContextBuilder.from({ practiceEnabled: false });const context = base.with('practiceEnabled', true);const choice = new EdgeChoiceBuilder() .withEdgeId(101) .withContext(context) .toObject();base still represents { practiceEnabled: false }. context is a new builder; choice is a plain request fragment:
{ "edge_id": 101, "context": { "practiceEnabled": true }}The PHP equivalent uses toArray() to obtain the same fields:
use ExecKernel\Builders\ContextBuilder;use ExecKernel\Builders\EdgeChoiceBuilder;
$base = ContextBuilder::from(['practiceEnabled' => false]);$context = $base->with('practiceEnabled', true);$choice = (new EdgeChoiceBuilder()) ->withEdgeId(101) ->withContext($context) ->toArray();with() replaces one context value, remove() removes a key, and merge() combines the existing values with a new set whose matching keys take precedence. These operations produce another builder. The returned array or object is a data copy; editing it does not modify the builder that produced it.
Pass the fields to the operation
Section titled “Pass the fields to the operation”A choice builder prepares data; it does not know which session owns the choice or whether that edge is available. Given an existing JavaScript session, pass its fields to selectEdge():
const payload = await session.selectEdge(choice.edge_id, choice.context ?? {});For PHP, $state is the SessionStateDTO returned by a configured local or remote client:
$next = $client->navigate($state, $choice['edge_id'], $choice['context'] ?? []);The JavaScript operation updates that Session and returns its payload. The PHP operation returns a new DTO in $next; use it for the next application view. Both clients add the session identity required for the operation.
The builders can add lang with withLang(), but the methods above accept an edge ID and context, not a complete choice envelope. A lang field in a separate builder does not change the language used by those calls. With the standalone API, the stored language is chosen when the session starts. Requesting another lang on resume changes that response only; later choices still use the stored language. When constructing HTTP requests yourself, also supply the required session ID as explained in HTTP API integration.
Match the destination’s context contract
Section titled “Match the destination’s context contract”The builders perform local data checks. They do not prove that the API or engine will accept every representable value:
| Context value | PHP and JavaScript context builders | Standalone HTTP API |
|---|---|---|
| String, boolean, supported finite number | Accepted | Accepted as a value |
null as a value |
Accepted | Rejected |
Flat list of scalar values and null |
Accepted | Rejected |
| Nested object or nested list | Rejected | Rejected |
JavaScript numbers must also respect its safe integer range when they represent integers. The API requires a context object with valid string keys; an individual value is a string, number or boolean. A builder can therefore successfully produce { tags: ['intro'] } even though sending it as API context is rejected with HTTP 400 and EK-INPUT-400.
The JavaScript SDK’s general Context type can represent more JSON structures than ContextBuilder. That broader type does not widen the standalone API’s accepted values. A local integration can also enforce its own engine context policy. Prepare inputs for the destination you actually use; keep presentation lists in your application when the graph only needs a fact such as practiceEnabled.
| Component | What it does for this choice |
|---|---|
| Builder | Creates a data value and checks its local shape. |
| SDK client | Sends the operation or calls the local adapter, validates the response and exposes session data. |
| API or local engine | Checks the actual session, graph, context policy and selected edge. |
| Your application | Supplies trusted facts, chooses when to submit and prepares the result for the person using it. |
Turn payloads into the data your screen needs
Section titled “Turn payloads into the data your screen needs”A payload brings together the graph’s presentation data for the current position. Node metadata supplies a heading or description, edge labels name the choices, and terminal outputs supply results for your application to present or act on. Payloads and presentation develops those concepts.
The SDKs expose the same distinction through different language constructs:
| Task | JavaScript | PHP |
|---|---|---|
| Get the payload | session.currentPayload |
$state->payload |
| Recognize choices | isNodePayload(payload) or payload.type === 'node' after a null check |
$payload instanceof NodePayloadDTO |
| Recognize a terminal | isTerminalPayload(payload) or payload.type === 'terminal' |
$payload instanceof TerminalPayloadDTO |
| Read node identity | payload.nodeId |
$payload->nodeId |
| Read choices or results | payload.edges / payload.outputs |
$payload->edges / $payload->outputs |
JavaScript normalizes presentation field names, including edge.label, edge.disabledReason and an output’s openBehavior. PHP payload DTOs retain arrays for individual edges, labels and outputs. A PHP view can therefore read the selected text from labels when no direct label is present:
use ExecKernel\DTO\NodePayloadDTO;
$payload = $state->payload;if ($payload instanceof NodePayloadDTO) { $choices = array_map(static fn (array $edge): array => [ 'edgeId' => $edge['id'], 'label' => $edge['label'] ?? $edge['labels'][0]['text'] ?? (string) $edge['id'], 'enabled' => ($edge['enabled'] ?? true) !== false, ], $payload->edges);}For the starting node, that projection produces “Read the guide” and “Practise in the browser”, associated with IDs 101 and 102. Retain the IDs when your interface renders the controls: the label is presentation text, while the ID identifies the submitted choice. If your interface explains disabled or pending choices, also project the edge’s availability and reason; PHP wire rows use disabled_reason, while JavaScript exposes disabledReason.
At a terminal, read outputs. A content output can supply a message, and url or redirect outputs can supply destinations. Your application decides how to present or follow them. The complete examples below produce message and link lists; they do not automatically navigate.
The high-level clients already hydrate responses into these SDK representations. Hydration means checking incoming fields and creating the corresponding DTO or normalized payload. Read-only DTO fields in PHP and frozen live session data in JavaScript help keep that received result stable. Create an application view model when you need different names, fallbacks or mutable UI data.
Save a JavaScript client snapshot
Section titled “Save a JavaScript client snapshot”A snapshot is useful when your application wants to preserve what it last displayed or keep a local representation between application steps. It captures the data available at that moment; the backend may advance or delete its session afterwards.
session.export() returns an independent data object. Serializing it gives your application a value it can store using its own storage mechanism:
const savedJson = JSON.stringify(session.export());The exported shape contains the following information when available:
| Field | Meaning in the snapshot |
|---|---|
sessionId |
Identity of the backend session. It does not contain that backend session. |
state |
Session data received by the client, such as position, context, history and timestamps. |
payload |
Choices or terminal outputs represented locally at export time. |
flowId and lang |
The client’s graph identifier and presentation language. |
correlationId |
The client’s correlation value, which can be null. |
For example, this reduced illustration keeps the fields needed to understand the starting screen. A real export() also retains the other state fields received from the API:
{ "sessionId": "saved-session-id", "flowId": "learning-path", "lang": "en", "state": { "current_node": 10, "context": { "practiceEnabled": true } }, "payload": { "type": "node", "nodeId": 10, "title": "How would you like to learn?", "edges": [ { "id": 101, "label": "Read the guide", "enabled": true }, { "id": 102, "label": "Practise in the browser", "enabled": true } ] }, "correlationId": null}state.current_node and payload.nodeId describe the same position. Their agreement lets the SDK reject inconsistent combinations during import. It does not prove that node 10 is still the backend’s current position.
The snapshot does not export the HTTP transport, API credential or event listeners. It can contain your application’s context and presentation data, so store it with the access rules appropriate to that data. Editing the exported object does not change the live Session.
Decide whether to hydrate locally or contact the API
Section titled “Decide whether to hydrate locally or contact the API”There are three useful operations, with different consequences:
| Operation | What changes |
|---|---|
new Session().import(snapshot) |
Creates a local representation with no transport configured. No HTTP request occurs. |
client.restoreSession(snapshot) with state or payload |
Creates a local representation attached to that client’s transport. No resume request occurs. |
client.restoreSession(sessionId) |
Requests the retained session from the API and builds the local representation from its response. |
An object containing only sessionId also follows the remote resume path. Passing the full snapshot follows the local hydration path even though the method is asynchronous.
The distinction becomes visible when a snapshot is saved before selecting the guide:
const sessionId = session.sessionId;if (!sessionId) throw new Error('Missing session identifier.');
const savedJson = JSON.stringify(session.export());await session.selectEdge(101);
const cached = await client.restoreSession(JSON.parse(savedJson));const current = await client.restoreSession(sessionId);cached.currentPayload still describes the choices at node 10. current.currentPayload describes terminal 20 and “Guide selected”. The first call read saved client data; the second asked the API what the session now contains.
Importing into an existing Session validates and replaces its local representation. An invalid import leaves the existing representation intact. It does not save to a backend store, recreate an expired session or change the graph position there. When continuing a process that may have changed elsewhere, retrieve its current backend state instead of treating cached options as authoritative.
Serialize PHP session data
Section titled “Serialize PHP session data”The PHP SDK offers StateSerializer for a SessionStateDTO. encode() creates JSON; decode() hydrates a new DTO from that JSON:
use ExecKernel\Serializer\StateSerializer;
$savedJson = StateSerializer::encode($state);$next = $client->navigate($state, 101);$cached = StateSerializer::decode($savedJson);$current = $client->resume($state->sessionId, 'en');As in the JavaScript example, $cached describes the starting choices and $current describes the guide terminal. Decoding the earlier JSON did not call the engine or overwrite its stored session. This works with the SDK’s DTO representation; backend store serialization and integrity are a separate subject covered in Serialization and session integrity.
The encoded DTO places session_id, node_id, context, history and is_terminal at the top level, with lang and payload when present. It is a projection of the SDK DTO, not a complete backup of every backend state field.
PHP’s SessionSnapshotBuilder builds a different envelope: an outer sessionId with optional state, payload, flowId, lang and correlationId. This is useful when your application wants those pieces together in an explicit client snapshot. To build one from the DTO JSON above, separate the payload from the state fields:
use ExecKernel\Builders\SessionSnapshotBuilder;
$stateFields = json_decode($savedJson, true, 512, JSON_THROW_ON_ERROR);$payloadFields = $stateFields['payload'] ?? null;unset($stateFields['payload']);
$snapshot = new SessionSnapshotBuilder( sessionId: $state->sessionId, state: $stateFields, payload: $payloadFields, flowId: 'learning-path', lang: 'en',);$savedEnvelope = $snapshot->toJson();The builder checks the supplied fields and consistency between state and payload. SessionSnapshotBuilder::fromArray() can read that envelope again, including its supported snake_case aliases. It constructs data; it does not call a session store.
Keep these two formats distinct. Use StateSerializer::decode() for JSON created by StateSerializer::encode(). Use SessionSnapshotBuilder::fromArray() for a decoded snapshot envelope. Neither operation restores the backend. To read the retained session through a PHP client, call resume() with its ID.
Complete examples: compare saved and current views
Section titled “Complete examples: compare saved and current views”The complete JavaScript example uses a configured API containing learning-path. The complete PHP example uses the local SDK and a graph directory containing the learning-path definition. Both use the installed SDK from your application.
Each example builds a choice, starts the session with practice enabled, saves its local representation, selects the guide and compares the saved view with the backend’s current view. They delete their own demonstration session at the end.
node helpers-session-snapshot.cjsphp helpers-payload-snapshot.php ./graphs ./var/helper-sessionsThe JavaScript program uses EXECKERNEL_BASE_URL and EXECKERNEL_API_TOKEN from your API configuration. The PHP program accepts the graph directory and a writable session directory; place it alongside your application’s vendor directory. These commands exercise existing integration setup rather than installing another environment.
| Output | What the application can display |
|---|---|
baseContext |
practiceEnabled remains false in the original builder. |
request |
Edge 101 with a separate context containing practiceEnabled: true. |
cachedView |
“How would you like to learn?” with both original choices. |
backendView |
“Guide selected”, its message and the guide link. |
JavaScript detachedView |
The same saved choices, reconstructed without a transport. |
PHP snapshotFields |
The envelope’s separate sessionId, state, payload, flowId and lang fields. |
Complete JavaScript snapshot example
'use strict';
const { ExecKernelClient, ExecKernelError, ContextBuilder, EdgeChoiceBuilder, Session, isNodePayload, isTerminalPayload,} = require('@execkernel/sdk');
function viewFor(session) { const payload = session.currentPayload; if (isNodePayload(payload)) { return { heading: payload.title ?? '', choices: payload.edges.map(edge => ({ edgeId: edge.id, label: edge.label ?? String(edge.id), enabled: edge.enabled !== false, })), }; } if (isTerminalPayload(payload)) { return { heading: payload.title ?? '', messages: payload.outputs.flatMap(output => output.type === 'content' && typeof output.content === 'string' ? [output.content] : []), links: payload.outputs.flatMap(output => (output.type === 'url' || output.type === 'redirect') && typeof output.url === 'string' ? [{ label: output.label ?? output.url, url: output.url }] : []), }; } throw new Error('No displayable payload.');}
async function main() { const baseUrl = process.env.EXECKERNEL_BASE_URL; const apiKey = process.env.EXECKERNEL_API_TOKEN; if (!baseUrl || !apiKey) { throw new Error('Set EXECKERNEL_BASE_URL and EXECKERNEL_API_TOKEN.'); } const client = new ExecKernelClient({ baseUrl, apiKey, flowId: process.env.EXECKERNEL_GRAPH_CODE || 'learning-path', lang: process.env.EXECKERNEL_LANG || 'en', }); const base = ContextBuilder.from({ practiceEnabled: false }); const context = base.with('practiceEnabled', true); const choice = new EdgeChoiceBuilder() .withEdgeId(101) .withContext(context) .toObject();
const live = await client.startSession(context.toObject()); const sessionId = live.sessionId; if (!sessionId) throw new Error('Missing session identifier.'); try { const savedJson = JSON.stringify(live.export()); await live.selectEdge(choice.edge_id, choice.context ?? {});
// Both operations below restore a local representation, without HTTP. const detached = new Session().import(JSON.parse(savedJson)); const cached = await client.restoreSession(JSON.parse(savedJson));
// Passing the identifier instead makes a request to the API. const backend = await client.restoreSession(sessionId); console.log(JSON.stringify({ baseContext: base.toObject(), request: choice, detachedView: viewFor(detached), cachedView: viewFor(cached), backendView: viewFor(backend), }, null, 2)); } finally { await client.destroy(sessionId); }}
if (require.main === module) { main().catch(error => { console.error(error instanceof ExecKernelError ? error.ekCode : error instanceof Error ? error.message : 'Unexpected failure.'); process.exitCode = 1; });}Complete PHP builder, payload and snapshot example
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use ExecKernel\Bootstrap\ExecKernelLocalBootstrap;use ExecKernel\Builders\ContextBuilder;use ExecKernel\Builders\EdgeChoiceBuilder;use ExecKernel\Builders\SessionSnapshotBuilder;use ExecKernel\Client\ExecKernelLocalClient;use ExecKernel\DTO\NodePayloadDTO;use ExecKernel\DTO\SessionStateDTO;use ExecKernel\DTO\TerminalPayloadDTO;use ExecKernel\Serializer\StateSerializer;
function viewFor(SessionStateDTO $state): array{ $payload = $state->payload; if ($payload instanceof NodePayloadDTO) { return [ 'heading' => $payload->title ?? '', 'choices' => array_map(static fn (array $edge): array => [ 'edgeId' => $edge['id'], 'label' => $edge['label'] ?? $edge['labels'][0]['text'] ?? (string) $edge['id'], 'enabled' => ($edge['enabled'] ?? true) !== false, ], $payload->edges), ]; } if ($payload instanceof TerminalPayloadDTO) { $messages = []; $links = []; foreach ($payload->outputs as $output) { if (($output['type'] ?? null) === 'content' && is_string($output['content'] ?? null)) { $messages[] = $output['content']; } if (in_array($output['type'] ?? null, ['url', 'redirect'], true) && is_string($output['url'] ?? null)) { $links[] = ['label' => $output['label'] ?? $output['url'], 'url' => $output['url']]; } } return ['heading' => $payload->title ?? '', 'messages' => $messages, 'links' => $links]; } throw new RuntimeException('No displayable payload.');}
$graphDirectory = $argv[1] ?? __DIR__ . '/graphs';$sessionDirectory = $argv[2] ?? __DIR__ . '/var/helper-sessions';$lang = getenv('EXECKERNEL_LANG') ?: 'en';
$client = new ExecKernelLocalClient( ExecKernelLocalBootstrap::fromFilesystem($graphDirectory, $sessionDirectory),);$base = ContextBuilder::from(['practiceEnabled' => false]);$context = $base->with('practiceEnabled', true);$choice = (new EdgeChoiceBuilder()) ->withEdgeId(101) ->withContext($context) ->toArray();
$started = $client->start('learning-path', $context->toArray(), $lang);try { // The serializer round-trips the SDK's SessionStateDTO. $savedJson = StateSerializer::encode($started);
// A snapshot envelope keeps state and payload as separate siblings. $stateFields = json_decode($savedJson, true, 512, JSON_THROW_ON_ERROR); $payloadFields = $stateFields['payload'] ?? null; unset($stateFields['payload']); $snapshot = new SessionSnapshotBuilder( sessionId: $started->sessionId, state: $stateFields, payload: $payloadFields, flowId: 'learning-path', lang: $lang, ); $savedEnvelope = $snapshot->toJson(); $envelope = SessionSnapshotBuilder::fromArray( json_decode($savedEnvelope, true, 512, JSON_THROW_ON_ERROR), )->toArray();
$finished = $client->navigate($started, $choice['edge_id'], $choice['context'] ?? []);
// This decode only recreates the old DTO; the backend remains at the terminal. $cached = StateSerializer::decode($savedJson); $backend = $client->resume($started->sessionId, $lang);
echo json_encode([ 'baseContext' => $base->toArray(), 'request' => $choice, 'cachedView' => viewFor($cached), 'backendView' => viewFor($backend), 'snapshotFields' => array_keys($envelope), 'snapshotNode' => $envelope['state']['node_id'], ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), PHP_EOL;} finally { $client->destroy($started->sessionId);}