Custom terminal output types
A custom terminal output type gives a result a meaning that your application understands. ExecKernel recognises the type through a registered validator and returns its data when the session reaches the terminal. Your application interprets the type and implements the corresponding view or action.
The built-in terminal outputs cover content, links, navigation destinations and a combination of content with a URL. Use those types when they express the result you need. A custom type is useful when your application needs a more specific contract, such as a reference code that it offers to copy.
This tutorial defines copy-code. A small graph starts at node 10 and follows edge 101 to terminal 20, where it returns the demonstration reference REF-2026-A7. Your application displays that code with a copy button. The type identifies that behaviour; the button and clipboard operation are application code.
Define the data and its meaning
Section titled “Define the data and its meaning”Use the existing terminal output fields to describe your result. For this type, we choose the following contract:
| Field | Contract for copy-code |
|---|---|
type |
Exactly "copy-code". |
content |
The code: 4–32 uppercase ASCII letters, digits or hyphens. |
label |
Non-empty button text, up to 80 bytes. |
lang |
"en" or "es", identifying the localized output. |
url and open_behavior |
Omitted or null; this action does not open a destination. |
These restrictions belong to this example’s type. They let the producer and the view agree on what the data mean.
Registering a type does not add fields to the TerminalOutput object. A graph output uses type, url, label, open_behavior, lang and content, with node_id associating its declaration with a terminal. Arbitrary new properties in graph JSON do not become new properties in the returned output. For a separate presentation structure, use a payload output hook to add application data to the payload.
Implement a validator and a producer
Section titled “Implement a validator and a producer”The registry calls a validator with an output array and accepts the output only when the callback returns true. It chooses the callback using type. A missing or unregistered type is invalid.
CopyCodeType::validate() implements the contract above. The output() helper gives PHP code a convenient way to produce a declaration with the same contract:
final class CopyCodeType{ public const TYPE = 'copy-code';
public static function validate(array $output): bool { $allowed = array_fill_keys( ['node_id', 'type', 'url', 'label', 'open_behavior', 'lang', 'content'], true, );
return array_diff_key($output, $allowed) === [] && ($output['type'] ?? null) === self::TYPE && is_string($output['content'] ?? null) && preg_match('/\A[A-Z0-9-]{4,32}\z/D', $output['content']) === 1 && is_string($output['label'] ?? null) && trim($output['label']) !== '' && strlen($output['label']) <= 80 && in_array($output['lang'] ?? null, ['en', 'es'], true) && ($output['url'] ?? null) === null && ($output['open_behavior'] ?? null) === null; }
public static function output(int $nodeId, string $code, string $label, string $lang): array { $output = [ 'node_id' => $nodeId, 'type' => self::TYPE, 'lang' => $lang, 'content' => $code, 'label' => $label, ]; if (!self::validate($output)) { throw new \InvalidArgumentException('Invalid copy-code output.'); }
return $output; }}The validator accepts both a declaration that includes node_id and a returned output without that field. Graph loading checks which terminal the declaration belongs to. Optional standard fields may be absent in the declaration and present as null in the payload, which is why the validator accepts both representations.
For example, application code that builds a graph definition in PHP can produce its English output with:
$output = CopyCodeType::output(20, 'REF-2026-A7', 'Copy code', 'en');The helper returns an array; it does not navigate the graph or copy anything. The JSON declaration in the next section produces the same data without calling the helper.
Declare the result in the graph
Section titled “Declare the result in the graph”The complete bilingual graph contains the two nodes, edge 101, their texts and these output declarations:
{ "outputs": [ { "node_id": 20, "type": "copy-code", "lang": "en", "content": "REF-2026-A7", "label": "Copy code" }, { "node_id": 20, "type": "copy-code", "lang": "es", "content": "REF-2026-A7", "label": "Copiar código" } ]}Both records belong to terminal 20. Their code stays the same, while lang and label provide the two presentations. An English request selects the English record; a Spanish request selects the Spanish one. The language selection is the same as for the built-in output types.
The JSON is the producer in this path: it declares the result to return. The registered validator checks its shape and values when your application loads the graph.
Register the type before loading the graph
Section titled “Register the type before loading the graph”PluginRegistry::addTerminalOutputType() adds a name and callback to the registry of terminal types. A small plugin keeps that registration together with its manifest. Here provides.terminal_outputs contains the type name; it is different from provides.outputs, which declares payload hook classes.
use ExecKernel\Domain\Engine\PluginInterface;use ExecKernel\Domain\Engine\PluginRegistry;use ExecKernel\Domain\Versioning\CompatibilityMode;
final class CopyCodePlugin implements PluginInterface{ public function register(PluginRegistry $registry): void { $registry->addTerminalOutputType(CopyCodeType::TYPE, [CopyCodeType::class, 'validate']); }
public function boot(): void {}}
$plugins = new PluginRegistry( engineVersion: '0.2.0', compatibilityMode: CompatibilityMode::STRICT,);$plugins->registerPlugin(new CopyCodePlugin(), [ 'name' => 'copy-code-output', 'version' => '1.0.0', 'requires' => ['execkernel' => '0.2.0'], 'provides' => ['terminal_outputs' => [CopyCodeType::TYPE]],]);engineVersion: '0.2.0' explicitly supplies the plugin compatibility value, and the manifest requires that exact value. STRICT makes a mismatch fail registration. The plugin’s own version, 1.0.0, versions this example extension. Plugin architecture and lifecycle explains these separate roles.
The loader must receive the registry so it knows copy-code while checking the declaration. Use the same registry when building the engine, keeping its extension configuration consistent:
use ExecKernel\Infrastructure\Engine\ExecKernelFactory;use ExecKernel\Infrastructure\Loader\ArrayGraphLoader;
$definition = json_decode( file_get_contents(__DIR__ . '/custom-output-copy-code.json'), true, 512, JSON_THROW_ON_ERROR,);$graph = (new ArrayGraphLoader( $definition, pluginRegistry: $plugins, engineVersion: '0.2.0',))->load('welcome-code');
$engine = (new ExecKernelFactory())->build(pluginRegistry: $plugins);$started = $engine->start($graph, 'en');$finished = $engine->choose($graph, $started->state, 101, 'en');Loading validates the declared outputs before the graph is used. The accepted choice reaches terminal 20 and the payload includes the selected output. These are the fields relevant to the view:
{ "type": "terminal", "node_id": 20, "title": "Your reference", "outputs": [ { "type": "copy-code", "url": null, "label": "Copy code", "open_behavior": null, "lang": "en", "content": "REF-2026-A7" } ]}The enclosing node_id identifies terminal 20; the output record itself no longer needs it. The unused standard fields appear as null. The code, label and type are data for the application to interpret.
Turn the output into a visible action
Section titled “Turn the output into a visible action”Your result view can render payload.title as its heading and reserve a container for the custom outputs:
<div id="copy-code-results"></div>The function below handles copy-code records. It creates a text code, a button and a status message. The click handler asks the browser to copy the code and reports success only after that operation completes. If the clipboard is unavailable or the request fails, the code remains visible for manual copying.
export function renderCopyCodes(payload, target, clipboard = globalThis.navigator?.clipboard) { target.replaceChildren(); if (payload.type !== "terminal") return;
for (const output of payload.outputs) { if (output.type !== "copy-code") continue;
const section = document.createElement("section"); const code = document.createElement("code"); code.textContent = output.content; const button = document.createElement("button"); button.type = "button"; button.textContent = output.label; const status = document.createElement("p"); status.setAttribute("role", "status");
button.addEventListener("click", async () => { try { if (!clipboard?.writeText) throw new Error("Clipboard unavailable"); await clipboard.writeText(output.content); status.textContent = output.lang === "es" ? "Código copiado." : "Code copied."; } catch { status.textContent = output.lang === "es" ? "No se pudo copiar. Selecciona y copia el código manualmente." : "Copying failed. Select and copy the code manually."; } });
section.append(code, button, status); target.append(section); }}renderCopyCodes(payload, document.getElementById("copy-code-results"));The function uses textContent because the output fields are text. Browser clipboard availability depends on the page context and permissions, so the failure path is part of the view. Other output types can have their own handlers in your application; this function leaves them to those handlers.
The following illustration shows the data returned by ExecKernel and one possible application view after a successful click:
Check the integration at both ends
Section titled “Check the integration at both ends”A registered name alone does not make every value valid, and a valid output alone does not create its interface.
| Situation | Consequence |
|---|---|
The graph contains copy-code but the loader has no registration for it. |
Graph loading rejects the unknown type. |
| The code contains lowercase letters, the label is empty or another contract check fails. | The validator returns false and graph loading rejects the declaration. |
| A plugin tries to add an existing type name. | Registration rejects the duplicate. |
| Registration is attempted after the registry has been consumed and sealed. | The registry rejects the change; finish registration first. |
The application has no handler for copy-code. |
It has the data but has not implemented the copy action. |
When output hooks are configured, ExecKernel also validates the final terminal outputs after those hooks run. This allows a hook to produce a dynamic custom output while using the same registered type contract. A hook that changes only presentation data and a custom terminal type solve different parts of that integration.
Follow the same idea in QR Pass
Section titled “Follow the same idea in QR Pass”QR Pass is a real Showcase application that combines both extension points. Enter a fictional first name and complete its step, then observe the name, URL and output type in the resulting view.
Its QrPassPayloadHook reads the confirmed name and uses QrPassType::output() to create a qr-pass output at the terminal. QrPassPlugin registers both the hook and the type validator. The application then uses its PassCard component and QRCodeSVG to encode the returned URL as a QR code and display the associated link. Those rendering components belong to the application.
Open Source code in the demo to inspect the manifest, validator, producer, hook and registration together. The same source response exposes those backend files and the graph definition. Unlike the static copy-code declaration above, the QR Pass graph has no declared terminal output: the hook produces it from the confirmed session context. Its pass is a demonstration welcome page, not an access credential.
The complete PHP recipe, bilingual graph and JavaScript view provide the smaller example from this page. The PHP file uses your project’s Composer autoloader and expects the graph beside it; optional arguments select en or es and another graph path. Keep the validator, graph declaration and application handler aligned when you adapt the type.