Skip to main content

Event mapping

The server side of mekik reduces to one pure function: eventToFrames (the TurnMapper) consumes the IlmekEvent stream of a single run and produces mekik frames. This page is that contract. It is the closed, machine-checkable core — the golden fixtures pin it byte-for-byte across both languages, and where this prose and a fixture disagree, the fixture wins.

What the mapper is​

The TurnMapper is turn-stateful but conversation-stateless:

  • It owns the current turn's GenUI streamId, the per-stream chunk counter, and the id of the open text run (so consecutive text deltas share one chunk id — one growing bubble, not one per token).
  • It is handed the conversation's persistent-seq allocator, an id minter, a clock, and the reply selector.

That split is deliberate. Because the conversation state (seq, ids) is injected, the mapper is a pure function of (events, seqAllocator, minter, clock, reply) — which is exactly what makes it reproducible across languages. Production passes a random minter and the wall clock; the fixtures pass a deterministic minter and a fixed clock. Only those injected pieces differ.

The IlmekEvent variants​

mekik consumes ilmek's typed event stream (@ilmek/core / Ilmek.Core). The variants:

run_start · step_start · node_start · custom{payload} · node_end{node,update} ·
node_error{node,error} · node_retry · state{channels} · checkpoint{id} ·
interrupt{pending: Pending[]} · run_end{status: done|interrupted|error|aborted, …}

Most of these produce nothing in v1. The mapper cares about four: run_start, custom, interrupt, and run_end. The rest (node_*, step_start, state, checkpoint) are reserved for a future debug stream mode.

The mapping table​

IlmekEventconditionframe(s) emitted
run_start—run{started}
customisToken(payload) (ilmek {type:"token",text,meta?})a genui text chunk {type:"text", content: payload.text, id: <text-run id>}, done:false — consecutive text deltas reuse the open text run's id
custompayload.$mekik == "genui"a genui frame with chunk = payload.chunk, done:false. Without a chunk.id, a text chunk joins the open text run; a ui/event chunk closes it and takes nextChunkId. An explicit id is kept and also closes the run
custompayload.$mekik == "tool"a tool_call frame {data: payload.call} (upsert by call.id)
custompayload.$mekik == "skill"a skill frame {data: payload.use} (upsert by use.id)
custompayload.$mekik == "message"a rich message frame {type: payload.messageType, id: payload.id ?? mint(), from:"bot", data: payload.data, timestamp} — dropped if messageType is a reserved protocol frame type (except "text")
customotherwisenothing (a reserved onCustom extension hook, not shipped — see below)
node_*, step_start, state, checkpoint—nothing in v1
interruptfor each p in pendingone interrupt frame {id: p.id, data: unwrapInterrupt(p.payload)}
run_endstatus == "interrupted"run{interrupted}
run_endstatus == "done"close the turn stream if open (genui {done:true, chunk:{type:"event", name:"stream_done"}}); then, if the run produced a reply, a bot text frame; then run{finished}
run_endstatus == "error"a bot text {text:"⚠️ " + message} then run{error} — message is <node>: <error> per recorded error, joined by ;
run_endstatus == "aborted"run{aborted} (no text; the last checkpoint stands)

Order within a run is the order ilmek yields events; the mapper preserves it. The terminal run{...} frame is always the last frame of its run.

That holds even when the event stream itself throws mid-run instead of yielding a run_end — ilmek's recursion limit (recursionLimit / RecursionLimit) or a failing checkpointer. Every tab has already seen run{started}, so the engine closes the run exactly as run_end{error} would: a persistent ⚠️ bot text carrying the exception's message, then run{error}. Over MCP such a turn is a result with isError, not a JSON-RPC error.

Why authoring helpers exist​

You never write those custom payloads by hand. The authoring helpers produce them:

HelperEmits the custom payload……which maps to
mekik.text(ctx, content)ilmek token eventgenui text chunk
mekik.ui(ctx, component, props){$mekik:"genui", chunk:{type:"ui",…}}genui ui chunk
mekik.event(ctx, name, payload){$mekik:"genui", chunk:{type:"event",…}}genui event chunk
mekik.mount(ctx, component, props){$mekik:"genui", chunk:{type:"ui",…, id}} (same id on every update)genui ui chunk, updated in place
mekik.tool(ctx, name, params, fn){$mekik:"tool", call:{…}} (running → completed/error)tool_call upsert
mekik.approve(ctx, payload, opts)ctx.interrupt with $mekik:{ui,actions}interrupt frame
mekik.choose(ctx, payload, options)ctx.interrupt with $mekik:{actions} built from the optionsinterrupt frame
mekik.message(ctx, type, data){$mekik:"message", messageType, data, id?}rich message frame
mekik.onEvent(ctx, eventType)ctx.interrupt with $mekik:{event}interrupt frame carrying data.event
mekik.callClientTool(ctx, name, params){$mekik:"tool", …} traces, then ctx.interrupt with $mekik:{tool} — or, for a notify tool, a client_tool event chunktool_call + interrupt carrying data.tool (or a genui event chunk)
mekik.loadSkill(ctx, name){$mekik:"skill", use:{…}}skill upsert

The $mekik key is the reserved namespace the mapper keys on. It's an implementation detail of the helpers — but knowing it exists explains the fixtures.

Interrupt payload wrapping (unwrapInterrupt)​

mekik.approve attaches presentation metadata under $mekik before calling ctx.interrupt:

// what the node passed to ctx.interrupt(...)
{ "title": "249.90₺ refund",
"$mekik": { "ui": { "component": "approval-form", "props": {…} },
"actions": [ { "label": "Approve", "value": { "approved": true } } ] } }

unwrapInterrupt(payload) splits it into the interrupt frame's data:

{ "payload": { "title": "249.90₺ refund" }, // $mekik stripped
"ui": { "component": "approval-form", "props": {…} }, // present only if given
"actions": [ { "label": "Approve", "value": { "approved": true } } ] } // present only if given

A plain ctx.interrupt(x) with no $mekik key yields {payload: x} with no ui/actions — the client falls back to default Approve/Cancel chips. (Each suite's mapper unit tests pin this; the single-approval and client-tool-call fixtures pin the ui/actions and tool splits.)

mekik.onEvent uses the same envelope as $mekik:{event:"<name>"}, which surfaces as data.event, and mekik.callClientTool as $mekik:{tool:{name, params?}}, which surfaces as data.tool. Either one tells the client not to render default chips.

The reply text frame​

At run_end{done} the adapter selects the run's reply from final channel state via MekikOptions.reply. If it returns a non-empty string, the mapper emits one persistent bot text frame carrying it. If it returns undefined or empty, no text frame is emitted — the run's genui/tool frames were the whole answer.

A crucial distinction:

Streaming tokens (ctx.emitToken / mekik.text) are not the reply. They are genui text chunks of the turn's stream — persisted and replayed like every genui frame — while the consolidated text frame at run end is a separate message bubble.

So a node that streams prose token-by-token and returns the same text as its reply shows the answer twice, live and on every replay. A node that streams its whole answer returns no reply; runAgent / Agent.RunAsync with streaming on do exactly that. (Fixtures mixed-turn and skill-loaded pin the consolidated frame; tokens pins the streaming chunks.)

Resume routing​

A resume frame maps to ilmek's resumeKeyedStream(g, answers, {threadId: conversationId}). Two rules the engine enforces:

  • Route by the thread-scoped interrupt id, never ilmek's task-scoped key. Answering by key silently collapses concurrent pauses (ilmek MODEL.md §6.1). Conformance scenario 6 proves it.
  • When the resume run starts, the engine first emits an interrupt_resolved frame for each answered id, then the new run's frames.

There's a convenience path: a genui_event{eventType:"submit", payload:{id, answer}} whose id names an open interrupt is coerced by the engine to resume{answers:{[id]: answer}}. A form mounted by an interrupt frame's ui already knows its interrupt id, so it can either answer with a plain resume on submit (the ordinary path) or fire a submit event — no server-side stream↔interrupt binding is needed either way. A genui_event that does not name an open interrupt is routed by its scope: to a node parked on onEvent, or to onGenUiEvent.

Extending the mapping (reserved)​

custom payloads the mapper doesn't recognise are dropped by default — the core mapping is closed so the golden fixtures stay authoritative. PROTOCOL.md §8 reserves an onCustom(payload, emit) seam for mapping them to extra frames, kept deliberately outside that closed core.

It's a reserved extension point, not a shipped option: there is no onCustom field on MekikOptions in 0.9. To produce custom frames today, emit a payload the mapper already recognises from your node via the authoring helpers — mekik.ui / mekik.event for GenUI chunks, mekik.tool for traces, and mekik.message for a rich message frame of any client renderer type.

Where to go next​