PHP SDK reference
The PHP SDK presents session operations through typed objects. A local client calls a PHP adapter in the same process; an HTTP client sends requests to a server and hydrates its replies. Both implement ExecKernelClientInterface, but persistence, language and transport behavior come from different components.
Use this page to look up a call or returned object. Complete sequences are in Local PHP SDK and Remote PHP SDK. The machine-readable signature index includes public methods, parameter defaults and DTO properties. Public visibility alone does not make an implementation helper a supported extension point; internal methods are marked in that index.
Namespaces and construction
Section titled “Namespaces and construction”| Responsibility | Namespace and types |
|---|---|
| Clients | ExecKernel\Client\ExecKernelClient, ExecKernelLocalClient, ExecKernelHttpClient, ExecKernelLocalAdapter |
| Transports | ExecKernel\Client\HttpTransport, GuzzleTransport |
| Ports | ExecKernel\Client\Contracts\ExecKernelClientInterface, LocalEngineInterface, TransportInterface |
| Configuration | ExecKernel\Config\Config; ExecKernel\Utils\RetryPolicy |
| Filesystem assembly | ExecKernel\Bootstrap\ExecKernelLocalBootstrap |
| Data helpers | ExecKernel\Builders\ContextBuilder, EdgeChoiceBuilder, SessionSnapshotBuilder |
| Returned objects | ExecKernel\DTO\SessionStateDTO, NodePayloadDTO, TerminalPayloadDTO, GraphInspectionDTO, SessionStatusDTO, ErrorDTO |
| Conversion and observation | ExecKernel\Serializer\PayloadHydrator, StateSerializer; ExecKernel\Utils\SdkEventDispatcher, ExecKernelErrorMapper |
The shorter names below refer to these namespaces. The adapter’s engine, graph loader and session store are core types; the SDK’s LocalEngineInterface is a separate port.
| Constructor | Arguments, in order |
|---|---|
ExecKernelClient |
Config $config, ?LocalEngineInterface $engine = null, ?TransportInterface $transport = null, ?SdkEventDispatcher $dispatcher = null |
ExecKernelLocalClient |
LocalEngineInterface $engine, ?SdkEventDispatcher $dispatcher = null |
ExecKernelHttpClient |
Config $config, ?TransportInterface $transport = null, ?SdkEventDispatcher $dispatcher = null |
ExecKernelLocalAdapter |
Core ExecKernel $engine, GraphLoaderInterface $loader, SessionStoreInterface $sessionStore, ?callable $sessionIdFactory = null |
ExecKernelClient delegates according to $config->isLocal(). Local configuration requires an engine port and otherwise throws InvalidArgumentException. HTTP configuration selects HttpTransport when no transport is supplied. The local adapter generates an ID with bin2hex(random_bytes(10)) unless your factory supplies one.
ExecKernelLocalBootstrap::fromFilesystem(string $graphDirectory, string $sessionDirectory, array $graphRepository = [], ?callable $sessionIdFactory = null, ?ExecKernelFactory $engineFactory = null): ExecKernelLocalAdapter assembles an engine, LocalGraphLoader and FilesystemSessionStore. The optional repository maps string or integer graph identifiers to definition arrays. It returns an adapter to pass to a local client.
Config and defaults
Section titled “Config and defaults”| Constructor parameter | Type and default | Meaning |
|---|---|---|
baseUrl |
Required string |
HTTP service root; baseUrl() removes trailing slashes. |
authToken |
?string = null |
Sent as a bearer token. |
retryPolicy |
?RetryPolicy = null |
retryPolicy() returns a no-retry policy when omitted. |
timeoutSeconds |
int = 10 |
Positive timeout used by the native stream transport. |
local |
bool = false |
Selects the local delegate in ExecKernelClient. |
correlationId |
?string = null |
Optional X-Correlation-Id request header. |
Config::local(): Config supplies the local marker and skips URL validation. For HTTP use, the URL must have an http or https scheme and a host, with no user information, query, fragment, spaces or control characters. An invalid URL or non-positive timeout throws InvalidArgumentException.
Accessors are baseUrl(): string, authToken(): ?string, retryPolicy(): RetryPolicy, timeoutSeconds(): int, isLocal(): bool and correlationId(): ?string. Configuration serialization and unserialization throw LogicException: supply configuration explicitly when constructing another client.
Session operations
Section titled “Session operations”All three client classes expose these exact interface signatures. This block is a signature listing, not an executable program:
start(string $flowId, array $context = [], ?string $lang = null): SessionStateDTOnavigate(SessionStateDTO $state, int $edgeId, array $context = []): SessionStateDTOresume(string $sessionId, ?string $lang = null): SessionStateDTOdestroy(string $sessionId): boolinspect(string $flowId): GraphInspectionDTOstatus(string $sessionId): SessionStatusDTOIn SDK calls, a graph identifier is a string. The independent HTTP API also accepts a JSON integer through its own request contract.
| Call | Local adapter behavior | HTTP client request |
|---|---|---|
start |
Loads the graph, creates a session, confirms its save and returns the state. | POST /execkernel/session/start: flow, context when non-empty, optional lang. |
navigate |
Reloads the stored session by $state->sessionId; uses $state->lang for presentation and the separate context argument as updates. |
POST /execkernel/session/next: session_id, edge_id, context when non-empty. It sends neither the DTO state nor its language. |
resume |
Loads the stored state and regenerates its payload without saving it. | POST /execkernel/session/resume: session_id, optional lang. |
destroy |
Calls the store’s idempotent delete and returns its confirmation as true. |
DELETE /execkernel/session/{encoded-session-id}; returns whether deleted === true. |
inspect |
Loads and projects graph nodes, edges and labels. | POST /execkernel/graph/inspect: flow. |
status |
Resolves the stored position and its graph; returns active or terminal, with logsTail = null. |
GET /execkernel/sessions/{encoded-session-id}/status. |
A DTO supplied to local navigate does not replace the stored context, node or history. The adapter evaluates the edge against the stored session. Conditional writes are used when the core store advertises support; an unconfirmed save becomes EK-SYS-002, and deferred success events are published only after confirmation.
The local adapter uses the explicit language, otherwise the graph default, otherwise its first allowed language. Core session state does not persist that presentation language. The independent API keeps the start language in its own snapshot; a language passed to resume affects that response without changing subsequent next calls. See HTTP API endpoints for that server contract.
Implementing the local port
Section titled “Implementing the local port”LocalEngineInterface exposes start(string $flowId, array $context = [], ?string $lang = null): array, next(array $state, int $edgeId, array $context = []): array, restore(string $sessionId, ?string $lang = null): array, destroy(string $sessionId): array, inspect(string $flowId): array and status(string $sessionId): array.
The client hydrates session, inspection and status arrays using the rules below. destroy expects a deleted boolean. Your port owns execution and persistence; matching these method names alone does not provide the standard adapter’s save confirmation or conditional writes.
Session and payload DTOs
Section titled “Session and payload DTOs”The properties listed here are public and readonly. Session and payload constructors copy and validate data arrays.
| Type | Constructor parameters and public properties |
|---|---|
SessionStateDTO |
string $sessionId, int $nodeId, array $context = [], array $history = [], bool $isTerminal = false, NodePayloadDTO|TerminalPayloadDTO|null $payload = null, ?string $lang = null |
NodePayloadDTO |
int $nodeId; required nullable strings $title, $subtitle, $description; required array $edges; ?array $extras = null |
TerminalPayloadDTO |
int $nodeId, array $outputs, ?string $title = null, ?string $subtitle = null, ?string $description = null, ?array $extras = null |
GraphInspectionDTO |
Required arrays $nodes, $edges, $labels. |
SessionStatusDTO |
int $currentNode, ?string $nodeStatus = null, ?array $logsTail = null. |
ErrorDTO |
string $ekCode, string $message, string $severity = 'error', array $context = [], ?string $hint = null, array $details = []. Also exposes code as an alias of ekCode. |
A session’s payload node and terminal kind must agree with nodeId and isTerminal. Edges and outputs remain arrays of records, rather than separate PHP DTO classes. Edge records use an integer identifier and may include labels, source/target nodes, availability and a disabled reason. Outputs contain data your application interprets, such as content or a URL. See Node and terminal payloads for their field contracts.
SessionStateDTO is the SDK’s reduced view. It has no graph version, revision or timestamp properties, even if the server response’s state contains more fields.
Hydration and serialization
Section titled “Hydration and serialization”Call the hydration methods on a new PayloadHydrator() instance. StateSerializer::encode and decode are static methods.
| Method | Input and result |
|---|---|
hydrateSessionState(array $data): SessionStateDTO |
Session array with ID and current node; absent context/history become empty arrays and absent payload becomes null. |
hydrateInspection(array $data): GraphInspectionDTO |
Direct graph projection, or one under graph or data; requires node, edge and label lists. |
hydrateStatus(array $data): SessionStatusDTO |
Direct status fields, or fields under status. |
hydrateError(array $data): ErrorDTO |
Shared error envelope normalized into code and metadata. |
StateSerializer::encode(SessionStateDTO $state): string |
JSON representation of the SDK DTO. |
StateSerializer::decode(string $json): SessionStateDTO |
Decodes and hydrates it; rejects duplicate JSON keys. |
The hydrator accepts session_id/sessionId; current-node aliases node_id/nodeId/current_node/currentNode; and is_terminal/isTerminal. Payloads accept node_id/nodeId and infer type from exactly one of edges or outputs when it is absent. Conflicting aliases, contradictory payload identities, invalid types and duplicate edge IDs produce ExecKernelInvalidStateException.
The HTTP client additionally accepts session data inside state, merges compatible outer fields and verifies an echoed session ID. It rejects persisted: false with EK-SYS-002; the independent API does not include that flag. A requested start/resume language can fill the DTO when no lang arrives; navigate has no language fallback.
Serialization keeps this reduced representation. Decoding it does not restore a backend session or produce the core persistence format. StateSerializer::toArray is marked internal; use encode/decode for public JSON conversion.
Builders
Section titled “Builders”Builder methods return a new builder; retain the result. Producing an array does not execute a session operation.
| Builder | Constructor and methods |
|---|---|
ContextBuilder |
__construct(array $values = []); static from(array $values = []): self; with(string $key, mixed $value): self; remove(string $key): self; merge(array $values): self; toArray(): array; toJson(): string. |
EdgeChoiceBuilder |
__construct(?int $edgeId = null, array $context = [], ?string $lang = null); withEdgeId(int $edgeId): self; withContext(array|ContextBuilder $context): self; withLang(?string $lang): self; toArray(): array; toJson(): string. |
SessionSnapshotBuilder |
__construct(?string $sessionId = null, ?array $state = null, ?array $payload = null, string|int|null $flowId = null, ?string $lang = null, ?string $correlationId = null); static fromArray(array $snapshot): self; toArray(): array; toJson(): string. |
Snapshot updates are withSessionId(?string $sessionId), withState(?array $state), withPayload(?array $payload), withFlowId(string|int|null $flowId), withLang(?string $lang) and withCorrelationId(?string $correlationId); all return self.
ContextBuilder requires string keys and allows scalar values, null and flat lists of scalars or nulls. It rejects nested objects, nested lists and non-JSON data. Direct client context arrays have a broader SDK data check; neither check establishes what a graph’s runtime policy or server accepts. The independent API accepts only non-null scalar context values.
EdgeChoiceBuilder requires an edge ID when exporting. It emits edge_id, plus context when non-empty and lang when non-null. PHP navigate takes the edge ID and context separately; it does not accept a builder or forward its lang.
SessionSnapshotBuilder emits supplied non-null fields as sessionId, state, payload, flowId, lang and correlationId. It accepts snake-case identifier aliases on import and checks supplied identity, node, timestamp and payload relationships. It does not invent missing fields or write them to a store.
A small data example
Section titled “A small data example”Suppose your application presents a review screen at node 4 with confirmation edge 7. This fragment prepares the choice without changing the original context:
use ExecKernel\Builders\ContextBuilder;use ExecKernel\Builders\EdgeChoiceBuilder;
$original = ContextBuilder::from(['reviewed' => false]);$choice = (new EdgeChoiceBuilder()) ->withEdgeId(7) ->withContext($original->with('reviewed', true)) ->toArray();$choice is ['edge_id' => 7, 'context' => ['reviewed' => true]]; the original retains reviewed: false. These IDs belong to synthetic example data; this fragment loads no graph. The complete data example also hydrates a node, round-trips the DTO through JSON and builds a reduced snapshot. It requires the SDK autoloader and makes no server request.
HTTP transports and retries
Section titled “HTTP transports and retries”TransportInterface::request(string $method, string $uri, array $payload = [], array $headers = []): array returns status: int, body: array and optionally headers: array<string, list<string>>.
| Transport | Construction and behavior |
|---|---|
HttpTransport |
__construct(Config $config, ?SdkEventDispatcher $dispatcher = null). Uses PHP streams, applies timeoutSeconds, disables redirects, reads error bodies and checks incomplete replies. Failure opening the stream becomes a connection exception; an observed read timeout becomes a timeout exception. |
GuzzleTransport |
__construct(Config $config, Psr\Http\Client\ClientInterface $client, Psr\Http\Message\RequestFactoryInterface $requestFactory, Psr\Http\Message\StreamFactoryInterface $streamFactory, ?SdkEventDispatcher $dispatcher = null). Uses the supplied PSR-18 client. Configure its deadline and transport policy on that client: this adapter does not apply Config::timeoutSeconds(). |
Both built-in transports require a JSON object response and reject duplicate keys. Invalid JSON on a 2xx reply becomes ExecKernelRemoteErrorException with EK-SYS-003; on an HTTP error it becomes EK-EXTERNAL-000. The client treats 3xx–5xx statuses, or a non-false/non-null error field, as errors. A custom transport must return already decoded valid data with the stated metadata shape.
RetryPolicy::__construct(int $retries = 0, int $backoffMs = 0) rejects negative values and a backoff too large to convert to microseconds. The static factory is noRetries(): self. Instance methods are retries(): int, backoffMs(): int, shouldRetry(int $attempt, ?Throwable $exception = null, bool $readOnly = false): bool and wait(): void.
Only inspect and status are marked read-only for retries. Connection/timeout exceptions can be retried up to the configured additional attempts, with a fixed delay, when ($exception->details()['retryable_transport'] ?? true) === true. An absent marker or null allows retry. The client does not retry start, navigate, resume or delete, nor ordinary HTTP 429/5xx errors. Guzzle’s connection exception with handler error 28 is classified as a timeout; other PSR network exceptions are retryable, while generic thrown transport errors are not.
The client supplies content type, optional bearer/correlation headers and X-Session-Id for session operations. It sends no SDK/API version declaration automatically. The independent API uses X-Trace-Id for tracing; a correlation header is not a substitute.
Exceptions and SDK events
Section titled “Exceptions and SDK events”SDK exceptions live in ExecKernel\Exceptions, distinct from core ExecKernel\Exception classes.
| Exception | Typical source |
|---|---|
ExecKernelInvalidStateException |
Invalid SDK data; mapped SESSION, STATE, CYCLE and SELECT error-code families. |
ExecKernelRemoteErrorException |
Other mapped engine/server errors, malformed replies, unconfirmed persistence or unexpected adapter failures. It can also come from a local adapter. |
ExecKernelConnectionException |
Failed or incomplete transport delivery. |
ExecKernelTimeoutException |
Timeout recognized by a built-in transport. |
All extend ExecKernelException. Its constructor is (string $ekCode, string $message, array $details = [], string $severity = 'error', ?string $hint = null, ?Throwable $previous = null). Read the product code with code(): string; PHP’s inherited getCode() is numeric. Other methods are details(): array, context(): array (the same details), severity(): string, hint(): ?string, isCode(string $prefix): bool and toArray(): array. HTTP status and a valid response trace ID are attached when available.
An ExecKernelErrorMapper instance exposes fromErrorDto(ErrorDTO $error): ExecKernelException and fromThrowable(Throwable $throwable): ExecKernelException for this mapping. Unknown local adapter throwables become EK-SYS-001. Error codes and exceptions distinguishes domain codes from the independent API’s remapped errors.
SdkEventDispatcher::on(string $event, callable $listener): void registers observers; emit(string $event, array $payload = []): void invokes them. Event names are session:start, session:node, session:terminal, session:error, http:request and http:response. Start emits its start event followed by a node or terminal outcome; navigate and resume emit the outcome.
Session success events include session/node identifiers, terminal status, context, history and the typed payload; start also includes flow_id. HTTP events expose a structural method/endpoint/status projection. Error events expose a reduced error and safe HTTP/trace metadata. Observers are best-effort: listener failure does not replace a confirmed operation result. Your application still owns how it stores or displays successful session data.