Skip to content

Latest commit

 

History

History
535 lines (430 loc) · 18 KB

runtime-plan-ir.md

File metadata and controls

535 lines (430 loc) · 18 KB
title RuntimePlan IR
description Canonical RuntimePlan nodes, capabilities, state transitions, templates, imports, and source modules.

RuntimePlan IR Reference

The RuntimePlan is the intermediate representation (IR) at the heart of Renderify. Every piece of UI that Renderify renders — whether generated by an LLM, authored by hand, or loaded from a file — is expressed as a RuntimePlan.

RuntimePlan Structure

interface RuntimePlan {
  specVersion?: string; // Protocol version, e.g. "runtime-plan/v1"
  id: string; // Unique plan identifier
  version: number; // Positive integer, incremented on updates
  root: RuntimeNode; // The UI tree
  capabilities: RuntimeCapabilities; // Execution permissions and limits
  state?: RuntimeStateModel; // Optional reactive state
  imports?: string[]; // Module specifiers to pre-load
  moduleManifest?: RuntimeModuleManifest; // Resolved module URLs
  source?: RuntimeSourceModule; // Optional executable source code
  metadata?: RuntimePlanMetadata; // Provenance and tags
}

Required Fields

  • id — non-empty string identifying the plan. Used for state management and caching.
  • version — positive integer. Must be >= 1.
  • root — the top-level node of the UI tree.
  • capabilities — declares what the plan needs (even if empty {}).

Spec Version

The specVersion field declares the protocol contract. Currently the only version is "runtime-plan/v1". In strict and balanced security profiles, this field is required.

const RUNTIME_PLAN_SPEC_VERSION_V1 = "runtime-plan/v1";

Node Types

The UI tree is composed of five node types: text, element, and component render content, while each and if repeat or conditionally render their children.

Text Node

interface RuntimeTextNode {
  type: "text";
  value: string; // Text content, supports template interpolation
}

Template interpolation resolves {{state.count}}, {{context.userId}}, {{vars.name}} at render time.

Element Node

interface RuntimeElementNode {
  type: "element";
  tag: string; // HTML tag name
  props?: Record<string, JsonValue>; // Attributes and properties
  children?: RuntimeNode[]; // Child nodes
}

Props support standard HTML attributes. Event handlers use the onClick, onInput format and are converted to runtime event bindings; see Events and forms.

Component Node

interface RuntimeComponentNode {
  type: "component";
  module: string; // Module specifier (bare, URL, or relative)
  exportName?: string; // Named export (default: "default")
  props?: Record<string, JsonValue>;
  children?: RuntimeNode[];
}

Component nodes reference external modules loaded via the JSPM module loader. The module specifier is resolved through the module manifest or JSPM CDN.

The referenced export is invoked as a Renderify component factory and must return a RuntimeNode tree or a string. Component nodes are not React or Preact component hosts.

Each Node

interface RuntimeEachNode {
  type: "each";
  items: string; // Array reference: "state.todos" or "{{state.todos}}"
  as?: string; // Item variable (default: "item")
  index?: string; // Position variable (default: "index")
  key?: string; // Item field used as a stable key, e.g. "id"
  children?: RuntimeNode[]; // Rendered once per item
}

Children are rendered once per array item, in place: an each inside a ul produces li siblings without a wrapper element. Inside the loop, templates and props can read the loop variables, such as {{todo.title}} and {{index}}. Loops nest, and inner loops can read outer variables. as and index must be simple identifiers other than state, event, context, and vars.

With key, each element produced by an iteration gets a stable key, so removing or reordering items reuses the right DOM nodes (and keeps focus and checkbox state on the right row). A single render may produce at most 10,000 nodes through each; beyond that, rendering stops and the runtime reports RUNTIME_EACH_LIMIT_EXCEEDED.

If Node

interface RuntimeIfNode {
  type: "if";
  when: string; // Value reference: "state.open", "todo.done", "{{state.tab}}"
  equals?: string | number | boolean | null; // Compare instead of testing truthiness
  not?: boolean; // Invert the condition
  children?: RuntimeNode[];
}

Without equals, children render when the value is truthy. Truthiness follows JavaScript except that an empty array is false, so "when": "state.todos" means "has todos". With equals, primitives compare by their text form (2 equals "2"), and string values may be templates such as "{{item.id}}". Use two if nodes, one with "not": true, for if/else.

A control node in the plan root renders inside a <div data-renderify-fragment style="display:contents"> wrapper so it does not affect layout.

Capabilities

interface RuntimeCapabilities {
  domWrite?: boolean; // Allow DOM manipulation
  networkHosts?: string[]; // Allowed network hosts
  allowedModules?: string[]; // Permitted module specifiers
  timers?: boolean; // Allow setTimeout/setInterval
  storage?: Array<"localStorage" | "sessionStorage">;
  executionProfile?: RuntimeExecutionProfile;
  maxImports?: number; // Maximum import count
  maxComponentInvocations?: number; // Maximum component renders
  maxExecutionMs?: number; // Maximum execution time (ms)
}

Execution Profiles

type RuntimeExecutionProfile =
  | "standard" // Default, in-page execution
  | "isolated-vm" // Reserved; current runtimes fail closed before module loading
  | "sandbox-worker" // Terminable Web Worker sandbox
  | "sandbox-iframe" // Compatibility name routed to a Worker
  | "sandbox-shadowrealm"; // Compatibility name routed to a Worker

Execution Budgets

Three budget dimensions are enforced at runtime:

Budget Field Description
Import count maxImports Declared imports and distinct remote materializations
Component invocations maxComponentInvocations Number of component renders
Wall-clock time maxExecutionMs Total execution time in milliseconds

maxImports covers declared imports and remote modules reached transitively through component or runtime-source imports during the same execution. When a budget is exceeded, execution stops and a diagnostic error is emitted.

State Model

interface RuntimeStateModel {
  initial: RuntimeStateSnapshot; // Required: initial state values
  transitions?: Record<string, RuntimeAction[]>; // Event-driven mutations
}

type RuntimeStateSnapshot = Record<string, JsonValue>;

When state is present, state.initial is required. The runtime maintains a snapshot per plan ID.

Actions

Five action types are available for state transitions:

// Set a value at a path
interface RuntimeSetAction {
  type: "set";
  path: string; // Dot-separated path, e.g. "user.name"
  value: JsonValue | { $from: string }; // Literal or reference
}

// Increment a numeric value
interface RuntimeIncrementAction {
  type: "increment";
  path: string;
  by?: number; // Default: 1
}

// Toggle a boolean value
interface RuntimeToggleAction {
  type: "toggle";
  path: string;
}

// Push a value to an array
interface RuntimePushAction {
  type: "push";
  path: string;
  value: JsonValue | { $from: string };
}

// Delete a value; array items are spliced out
interface RuntimeRemoveAction {
  type: "remove";
  path: string;
}

Paths address array items by index (todos.2.done). A whole path segment may be a template, resolved when the event is handled, to target the item an event came from:

{ "type": "toggle", "path": "todos.{{event.payload.index}}.done" }
{ "type": "remove", "path": "todos.{{event.payload.index}}" }

A template must fill its segment, and its value must be a string or non-negative integer that forms one safe segment; otherwise the action is skipped with a RUNTIME_ACTION_PATH_UNRESOLVED diagnostic. Writing to a missing array index is also skipped rather than replacing the array.

Value References

The $from syntax references values from other contexts:

{ "$from": "state.count" }       // Current state
{ "$from": "event.payload.id" }  // Event payload
{ "$from": "context.userId" }    // Execution context
{ "$from": "vars.theme" }        // Context variables

References may appear anywhere inside a set or push value, so a new list item can combine bound state and literals:

{
  "type": "push",
  "path": "todos",
  "value": { "title": { "$from": "state.draft" }, "done": false }
}

Event binding payloads may contain references too. They are resolved against state when the event is handled, after earlier events in the same interaction have been applied, so the payload always carries what the user just entered. A payload that is a single reference, such as { "$from": "state.form" }, becomes the referenced object.

Events and forms

Element props named on + an event (onClick, onInput, onChange, onKeyDown, ...) dispatch a runtime event. The value is either a transition name or { "type": "...", "payload": { ... } }. Inside each, payload templates such as "{{index}}" capture the current item:

{ "onClick": { "type": "remove", "payload": { "index": "{{index}}" } } }

onEnter dispatches when Enter is pressed in a field (without modifier keys or an active IME composition) and suppresses the newline.

Events from input, textarea, and select elements carry the control's live value in event.payload.value: a boolean for checkboxes (with event.payload.checked), a number for number and range inputs, an array for multi-selects, and a string otherwise. Keys declared in the binding's payload take precedence over captured values.

Bound controls

bind keeps a form control and a state path in sync without writing transitions:

{ "type": "element", "tag": "input", "props": { "bind": "draft", "placeholder": "New task" } }
{ "type": "element", "tag": "input", "props": { "type": "checkbox", "bind": "todos.{{index}}.done" } }

The control shows the state value, and each edit writes back to the path (text-like controls on input, checkboxes, radios, and selects on change) through a renderify:bind runtime event before any transitions run. Checkboxes bind booleans; a radio is checked when the bound value equals its value; number inputs bind numbers. The state. prefix is optional, and loop templates in the path are resolved per item.

When state changes the bound value, for example when an "Add" transition clears draft, the control updates even if the user already edited it. A focused control is only updated when it is being cleared, so renders never overwrite text while the user is typing.

Password and file inputs are never bound and never captured, so their contents cannot reach plan state, events, or a host's model context.

Forms

A form element renders as an inert <div data-renderify-form> container without action, method, or target, so it can never navigate the page or post fields anywhere. The runtime emulates submission instead: onSubmit fires when a submit button inside the form is clicked or Enter is pressed in one of its text fields. The payload contains the form's named fields, merged under any declared payload keys:

{
  "type": "element",
  "tag": "form",
  "props": { "onSubmit": "tool:search_flights" },
  "children": [
    { "type": "element", "tag": "input", "props": { "name": "from" } },
    { "type": "element", "tag": "input", "props": { "name": "to" } },
    { "type": "element", "tag": "button", "children": [{ "type": "text", "value": "Search" }] }
  ]
}

Submitting this form dispatches tool:search_flights with { "from": "...", "to": "..." }. A lone checkbox is a boolean, same-named checkboxes are the array of checked values, and a radio group is the checked value or null. Disabled, password, and file fields are skipped. Fields keep what the user typed after a submit; bind them when a transition should clear them.

Path Safety

All state paths are validated against prototype pollution. The following segments are rejected:

  • __proto__
  • prototype
  • constructor

Module Manifest

type RuntimeModuleManifest = Record<string, RuntimeModuleDescriptor>;

interface RuntimeModuleDescriptor {
  resolvedUrl: string; // Full URL to the module
  integrity?: string; // SRI hash (e.g. "sha384-...")
  version?: string; // Package version
  signer?: string; // Signing authority
}

The manifest provides deterministic module resolution. In strict security profile, bare specifiers (like "recharts") must have a manifest entry. In strict mode, remote modules must also include integrity hashes.

Example Manifest

{
  "preact": {
    "resolvedUrl": "https://ga.jspm.io/npm:preact@10.28.3/dist/preact.module.js",
    "version": "10.28.3"
  },
  "recharts": {
    "resolvedUrl": "https://ga.jspm.io/npm:recharts@3.3.0/es6/index.js",
    "version": "3.3.0"
  }
}

Source Module

interface RuntimeSourceModule {
  code: string; // Source code
  language: "js" | "jsx" | "ts" | "tsx"; // Source language
  exportName?: string; // Export to render (default: "default")
  runtime?: "renderify" | "preact"; // JSX runtime target ("preact" is the trusted browser source lane)
}

Source modules enable richer interactivity than the declarative node tree. The source code is transpiled via Babel, imports are rewritten to browser-resolvable URLs, and the default export is rendered as a Preact component (when runtime: "preact") or as a RuntimeNode tree.

  • runtime: "renderify" expects the exported function to return RuntimeNode | string and can participate in the declarative execution/sandbox model.
  • runtime: "preact" expects a Preact-compatible component and should be rendered with renderTrustedPlanInBrowser or the trusted security profile.
  • runtime: "preact" does not run inside the browser worker/iframe/ShadowRealm sandbox adapters.

Example Source Module

{
  "source": {
    "code": "import { useState } from 'preact/hooks';\nexport default function Counter() {\n  const [count, setCount] = useState(0);\n  return <button onClick={() => setCount(c => c+1)}>Count: {count}</button>;\n}",
    "language": "tsx",
    "runtime": "preact"
  }
}

Metadata

interface RuntimePlanMetadata {
  sourcePrompt?: string; // The prompt that generated this plan
  sourceModel?: string; // LLM model used
  tags?: string[]; // Classification tags
  [key: string]: JsonValue | undefined; // Arbitrary extensions
}

Built-in Compatibility Aliases

The IR package includes pre-resolved module mappings for the React/Preact ecosystem:

Specifier Resolved To
preact preact@10.28.3/dist/preact.module.js
preact/hooks preact@10.28.3/hooks/dist/hooks.module.js
preact/compat preact@10.28.3/compat/dist/compat.module.js
react preact@10.28.3/compat/dist/compat.module.js
react-dom preact@10.28.3/compat/dist/compat.module.js
react-dom/client preact@10.28.3/compat/dist/compat.module.js
react/jsx-runtime preact@10.28.3/jsx-runtime/dist/jsxRuntime.module.js
recharts recharts@3.3.0/es6/index.js

These aliases mean LLMs can generate standard React code that runs directly via Preact.

Utility Functions

Node Creation

createTextNode("Hello");
createElementNode("div", { class: "card" }, [createTextNode("Content")]);
createComponentNode("npm:@acme/renderify-widgets", "SummaryCard", {
  title: "Quarterly Report",
});

Validation Guards

isRuntimePlan(value); // Full plan validation
isRuntimeNode(value); // Node type check
isRuntimeAction(value); // Action validation
isRuntimeStateModel(value); // State model validation
isRuntimeCapabilities(value); // Capabilities validation
isRuntimeSourceModule(value); // Source module validation
isRuntimeModuleManifest(value); // Manifest validation
isJsonValue(value); // JSON-safe value check

Tree Utilities

// Walk all nodes depth-first
walkRuntimeNode(plan.root, (node, depth) => {
  console.log(`${" ".repeat(depth * 2)}${node.type}`);
});

// Collect all component module specifiers
const modules = collectComponentModules(plan.root);
// => ["recharts", "my-component"]

Path Utilities

getValueByPath(state, "user.name"); // => "Alice"
setValueByPath(state, "user.name", "Bob"); // => true when written
setValueByPath(state, "todos.9.done", true); // => false for a missing item
removeValueByPath(state, "todos.0"); // splices the array
isSafePath("user.name"); // => true
isSafePath("__proto__.hack"); // => false

Complete Example

{
  "specVersion": "runtime-plan/v1",
  "id": "analytics-dashboard",
  "version": 1,
  "root": {
    "type": "element",
    "tag": "div",
    "props": { "style": "padding: 16px" },
    "children": [
      {
        "type": "element",
        "tag": "h1",
        "children": [{ "type": "text", "value": "Dashboard" }]
      },
      {
        "type": "element",
        "tag": "p",
        "children": [{ "type": "text", "value": "Count: {{state.count}}" }]
      }
    ]
  },
  "capabilities": {
    "domWrite": true,
    "maxExecutionMs": 5000,
    "maxComponentInvocations": 100
  },
  "state": {
    "initial": { "count": 0 },
    "transitions": {
      "increment": [{ "type": "increment", "path": "count" }]
    }
  },
  "imports": ["recharts"],
  "moduleManifest": {
    "recharts": {
      "resolvedUrl": "https://ga.jspm.io/npm:recharts@3.3.0/es6/index.js",
      "version": "3.3.0"
    }
  },
  "metadata": {
    "sourcePrompt": "Build an analytics dashboard",
    "sourceModel": "gpt-5-mini",
    "tags": ["dashboard", "analytics"]
  }
}