Events

Emit and await structured events, and present the durable session log

Kaya programs can emit and await structured events. These events become part of a durable session log that clients use to present conversation, tasks, and interactions. For scheduled playback, see The Timeline.

Events — the two-way protocol

A program emits an event with emitEvent() and awaits one with awaitEvent() (suspends) or consumeEvent() (non-blocking poll).

// Outbound: tell the world something happened.
emitEvent(eventType: "game.state", data: {board: board})

// Inbound: suspend until a move arrives (the program "dehydrates" until then).
let move = awaitEvent(eventType: "game.move")
Run in Browser No model needed

Events are appended to the authoritative session log as durable role: "event" entries and streamed live to connected clients — so they survive reload and replay, and drive a live UI at the same time. Chat is a separate projection of that log.

Think of the session log as an ordered fact stream, not as a list owned by the chat UI. The client fetches exact cursor pages; Rust-backed projections derive chat, tasks, interactions, audio, game state, and scene state from those same rows:

const page = await client.getSessionLog(sessionId); // one cursor page
const completeLog = await client.loadSessionLog(sessionId); // paging included

Fetching, pagination, history/live overlap, and streamed wake-ups belong to the client. SSE frames never become presentation truth: after a wake-up, the host fetches the new durable rows and appends them to the same portable Rust kernel used for replay. A captured log can therefore render without a Kaya engine.

Event types match hierarchically at dot boundaries, with a root firehose "*". Patterns fail loud (never a silent no-op) — see Event-type matching.

let any = awaitEvent(eventType: "*")          // the firehose: every event
let pay = awaitEvent(eventType: "payment")    // payment, payment.success, payment.error, …

Each event can also name three independent session-envelope axes:

  • from — the human, agent, service, or system that authored or caused it;
  • to — an array of identity, group, or component addresses; omission means the authorized session audience;
  • subject — the domain entity the fact is about, which does not route it.

source remains trusted provenance stamped by the runtime or transport. For example, Ted can be from, a game board and spectator group can be to, and a chess piece can be subject, while source still proves that the program emitted the event.

Files on events

Generated media travels on events as a file reference, not as bytes inside the session-log entry or live event frame:

let clip = generateAudio(
  prompt: "Welcome to the show.",
  model: voiceModel,
  filename: "intro.wav"
)

emitEvent(
  eventType: "speech.segment",
  data: {text: "Welcome to the show.", audio: clip},
  channel: "podcast.main",
  timing: {mode: "queue"}
)

The file object retains its session-VFS path. At the emitEvent() boundary, Kaya also publishes each nested pinned file (see below) and adds a loadable url for browsers and remote consumers. The event therefore links to the same bytes locally and remotely while the transport carries only small JSON metadata. Local exporters should prefer the VFS path and use the URL as a remote fallback.

A file value carries a pin: the size and sha256 of its bytes. Every builtin that makes a file pins it (save(), copyFile(), asset(), generateImage(), generateAudio(), speak(), image search and the renderers). Kaya publishes only pinned files, and checks each pin against its bytes first: a mismatch, or a pin that claims more than 256 MiB, fails the run. A viewer that verifies the pin therefore reads exactly what the program emitted, even if the file is overwritten later. An object you build yourself with path, filename and mimeType but no sha256 is plain data and gets no url; emit the value the builtin returned instead. Publication never adds a pin, so a file-shaped object that arrives as event data cannot pass for a file.

What you can wait for — and what you can't

awaitEvent / consumeEvent match on the event type, with two optional narrowers:

let move    = awaitEvent(eventType: "game.move")                          // any game.move (+ subtree)
let stripe  = awaitEvent(eventType: "payment", eventProvider: "stripe")   // only events from this provider
let thisOne = awaitEvent(eventType: "payment", correlationId: orderId)    // only the matching operation
  • eventType — hierarchical, exact dot boundaries ("payment" matches payment.success but not payments), case-sensitive, with the "*" firehose. Interior globs like actors.*.speech are not a thing for matching.
  • eventProvider — exact match on who sent it ("stripe", "scheduler", …).
  • correlationId — exact match, to pair one operation's reply (e.g. from requestPayment / generateResearch).

You cannot await on a channel. A channel is a timeline lane — it travels on the event but is never used for matching, so there is no channel: filter. channel and eventType are independent: an event can be eventType: "game.move" on channel: "actors.p1.actions". To "wait for a channel," give the events you await a hierarchical eventType and match on that (most programs make the two strings the same by convention, e.g. game.move).

The Timeline

See The Timeline to schedule events across channels and play, pause, or seek a session.

For timing keys, anchors, and channel modes, see Scheduling.

The Browser — present the durable session log

The reference Kaya Browser renders the semantic session view through the Rust presentation kernel and a Web Component host. React owns application lifecycle and navigation, but it does not reinterpret session facts.

The deployment—not the program or session log—chooses a strict presentation manifest. That manifest can name only view and theme modules already installed in a local allowlist. This keeps replay deterministic and prevents a session entry from selecting JavaScript or widening artifact, input, audio, or scene authority.

"Welcome to the route planner."

emitEvent(
  eventType: "task.card.set",
  data: {
    version: "1",
    taskId: "route",
    title: "Choose a route",
    status: "running"
  }
)

let route = input(
  prompt: "Which route should we take?",
  options: [
    {id: "north", label: "North coast"},
    {id: "south", label: "South coast"}
  ]
)
setGameEntity(entityId: "journey", kind: "route", state: {choice: "{{route}}"})
"Route {{route}} confirmed."

Today, ordinary assistant output, typed input() obligations, and known structured event contracts such as task, presence, audio, and scene facts can drive this host. The input obligation is durable: the browser submits a typed response, the daemon appends arrival/submission/closure facts, and the engine consumes it through the normal FIFO message door before resuming the program.

Choice options may carry retained artifact references, so the same interaction contract covers text lists and image galleries without granting the session log any byte-fetching authority. setGameEntity() and removeGameEntity() likewise author reserved game facts without exposing their verified source.

Faces

A face is the program's own interface: an HTML document, authored by the program or its author, that the host shows in a sandboxed pane and wires to the session's events. mount() selects one by authoring a durable browser.mount event — but the program only selects; the host declares. A declaration pins the face's bytes by sha256 and states its contract: which event types it may read and which it may send (each send type with a schema the data must validate against).

mount(component: "vote-panel", layout: "panel", props: {round: 3})

// The face sees the program's demo.tick rows (its reads)…
emitEvent(eventType: "demo.tick", data: {n: 1})

// …and the program awaits the face's demo.vote sends (its sends).
let vote = awaitEvent(eventType: "demo.vote")

The kernel enforces the contract as a firewall, independent of whatever the face's code does:

  • The face receives only verified program rows whose type is in its reads, in log order. Seeking backwards resets its list; seeking forward replays.
  • Every send is refused unless its type is in the face's sends, its data validates against that type's schema, and it fits the size and in-flight limits. The kernel forwards the schema-normalized data, so a face cannot smuggle keys past validation.
  • A component that names no declared face is a diagnostic, never a load.

The host loads the face's bytes into a locked-down iframe — scripts only, no network requests, no storage, no parent-page access — after verifying them against the declared digest, and bridges them over a dedicated message channel that no other frame can reach. A face that floods the channel or navigates its frame away is stopped and replaced with a placeholder. Program-supplied faces ask the person for approval of that exact face and contract before they load; author-supplied faces skip the card, with an identical sandbox and firewall either way.

Bundling a face with a project

In the Kaya IDE (the website's /try and every example), a project bundles its faces: an HTML file beside main.kaya, plus a faces.json that declares it.

{
  "faces": {
    "tic-tac-toe": {
      "file": "board.html",
      "title": "Tic-Tac-Toe",
      "reads": ["ttt.state"],
      "sends": {
        "ttt.move": {
          "zodTypeName": "Object",
          "shape": { "cell": { "zodTypeName": "Number" } },
          "unknownKeys": "strict"
        }
      }
    }
  }
}

When you press Run, the IDE reads faces.json and the face files from that run's own copy of the project, pins each face to the exact bytes it will serve, and declares them as your own (author trust, so no approval card). The face appears in Preview, which opens by itself when the program mounts it; reopening a past run shows the face it ran with. Inside the face, the injected window.kaya object is the whole interface:

<script>
  kaya.onEvent((event) => {
    if (event.eventType === "ttt.state") draw(event.data);
  });
  // Resolves with the event id once the kernel accepts the send.
  kaya.send("ttt.move", { cell: 4 }).catch((error) => show(error.message));
</script>

A face draws state and reports input; the program keeps every rule and validates what it consumes, because any session client can post the same event type past the face. See the Tic-Tac-Toe example for a complete game, and the face authoring reference (FACES.md in @kaya/presentation-web) for the shim, the sandbox, and the failure catalog.

Faces the program writes

A program can also write its face while it runs, from a template or from a model's output: save the HTML, then mount it with its contract.

let page = save(content: html, filename: "counter.html")
mount(
  component: "counter",
  face: page,
  reads: ["counter.state"],
  sends: {"counter.add": {zodTypeName: "Object", shape: {}}}
)

The runtime pins the document's size and digest into the mount row, so the viewer loads exactly those bytes. Because the program supplied them, the viewer shows a consent card first: it names the face, its digest, and what the face may read and send, and nothing loads until you approve it. The IDE remembers the approval in this browser for that exact face, digest, and contract. The face gets the same sandbox and firewall as a bundled one, and it may not take an id the project already declares. See the counter example.

Pictures and sounds in a face

A face cannot fetch anything, so it shows pictures and sounds through kaya.media(). Put a pinned file on an event the face reads:

resource "kitchen.png"

let picture = asset(path: "kitchen.png")
emitEvent(eventType: "story.scene", data: {text: "Morning.", picture: picture})

Then hand the file value to kaya.media(), which resolves with a blob: URL the face can use:

<img id="scene" alt="">
<script>
  let latest = 0;
  kaya.onEvent((event) => {
    if (event.eventType !== "story.scene") return;
    const turn = ++latest;
    // A reopened face receives every scene at once: ask only for the newest.
    queueMicrotask(() => {
      if (turn !== latest) return;
      kaya.media(event.data.picture).then((url) => {
        if (turn !== latest) return URL.revokeObjectURL(url);
        if (scene.src) URL.revokeObjectURL(scene.src);
        scene.src = url;
      }, (error) => console.warn(error.message));
    });
  });
</script>

The viewer hands over the bytes only for a pinned file one of the face's events carried, after checking them against that pin. Every builtin that makes a file pins it, so generated pictures (generateImage()) and voices (generateAudio(), speak()) reach a face the same way as a package's assets. Faces can show PNG, JPEG, GIF and WebP images and play MP3, Opus, WAV, Ogg, WebM, MP4, AAC and FLAC audio, up to 32 MiB per file. SVG is refused because it can carry script.

Program blocks, the client doesn't

The two sides have opposite concurrency models — by design:

  • Program side — one at a time. A program is single-threaded: awaitEvent suspends the whole program until a matching event arrives. You wait for one thing, handle it, then loop. There is no parallel await on the program side.
  • Client side — many at once. Hosts can project conversation, tasks, interactions, audio, and scene state concurrently. There is no client-side awaitEvent; live transport wakes a durable catch-up, and typed host actions enter through daemon ingress without blocking unrelated views.

So one program loop can drive—and be driven by—a whole panel of independent, concurrently updating views while one ordered log remains the source of truth.