Agent / foldkit-agent
agent
Letting an AI assistant or external service operate a web app usually ends up creating a second API layer with duplicated validation, separate authorization checks, and tool handlers that drift out of step with the UI. You want an assistant to use the exact same state transitions your buttons trigger, while seeing only the fields you choose to share.
foldkit-agent turns your Foldkit Model (your application state) and Message union (the actions sent to update) into a typed, protocol-neutral agent contract. You pick a read-only Projection from foldkit-surface for what the agent may read, expose selected Message variants with Agent.expose for what it may do, and bind the contract to your running app with Agent.host or Agent.headless. Protocol adapters (foldkit-agent-mcp, foldkit-agent-webmcp, foldkit-agent-a2a, foldkit-agent-native) serve that single contract over MCP, browser WebMCP, A2A, and Agent Native. See it running in the live Todo agent demo.
Install
pnpm add foldkit-agentfoldkit and effect are peer dependencies.
A first agent contract
Declare your Model and Message union, select which slice of state agents can read with Projection.pick, and expose only the Messages an agent is allowed to send:
import { Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import { Agent } from 'foldkit-agent'
import { Projection, Surface } from 'foldkit-surface'
const Todo = Schema.Struct({ id: Schema.String, title: Schema.String, completed: Schema.Boolean })
const Model = Schema.Struct({ todos: Schema.Array(Todo), selectedTodoId: Schema.Option(Schema.String) })
const Message = defineMessageUnion({
RequestedCreateTodo: { title: Schema.String },
RequestedDeleteTodo: { id: Schema.String },
ReceivedTodos: { todos: Schema.Array(Todo) },
})
const App = Surface.application({ Model, Message })
const TodoAgent = Agent.forApplication(App)
const AppAgent = TodoAgent.make({
context: Projection.pick(App.model.todos, App.model.selectedTodoId),
messages: TodoAgent.expose(Message, {
RequestedCreateTodo: 'Create a new todo',
RequestedDeleteTodo: {
name: 'delete_todo',
description: 'Delete a todo',
available: model => model.selectedTodoId._tag === 'Some',
},
}),
})AppAgent now defines two agent capabilities (requested_create_todo and delete_todo) with JSON Schemas derived from Message, plus a read-only todos and selectedTodoId context. ReceivedTodos stays internal and cannot be invoked by an agent because exposure is opt-in.
Bind the contract to a live Foldkit runtime using Agent.host, then dispatch capabilities through agentRuntime.messages.dispatch:
import { Effect } from 'effect'
import * as Runtime from 'foldkit/runtime'
const { config, host } = Agent.host({ Model, init, update, view, container })
Runtime.run(Runtime.makeApplication(config))
const agentRuntime = TodoAgent.bind({ definition: AppAgent, host })
const result = await Effect.runPromise(
agentRuntime.messages.dispatch(Message.RequestedCreateTodo, { title: 'Read the guide' }),
)Running dispatch decodes the payload against RequestedCreateTodo's schema, verifies available, sends the Message into the runtime's queue so update, Commands, and Subscriptions run just as they do for a user click, and resolves once the transition completes. When an operation finishes asynchronously in a later Message or state change, add a completion contract so dispatch waits for the outcome.
Agent.bind requires the host to accept every Message the contract can emit and—when variants declare authorize—provide a principal callback returning the matching principal type.
The host
Agent.bind accepts any { model, dispatch, subscribe?, observe?, principal? } host:
| Where the app runs | Host |
|---|---|
| Browser page on Foldkit runtime | Agent.host(config).host |
| Tests or server with no view | Agent.headless({ init, update, subscriptions?, resources? }).host |
| Local-first Sync replica | Return value of Sync.mount |
Across all hosts, model() reads the last committed Model, dispatch(message) resolves after update applies the Message (rejecting if the runtime stops or crashes first), subscribe fires on Model changes, and observe fires on every applied Message so completion contracts work.
Authorization belongs in the contract rather than the host: pass the current caller via host: { ...host, principal: () => principal }.
Each Agent.host(config) wraps a single runtime; call Agent.host separately for each runtime instance rather than reusing one wrapped config across two starts.
Agent.headless runs init, update, Commands, and Subscriptions with resources initialized once for its lifetime and no DOM. Server-side per-session agents typically bind one headless host per authenticated caller with that caller's RemoteClient. It omits managedResources, routing, ports, and keyed interruptible Commands (enforced by types and runtime checks). Calling dispose() stops the host and releases resources.
Join a foldkit-bundle assembly
Register the contract in a Bundle assembly via AppAgent.wiring() so module introspection sees the contract; it adds no Model fields or Subscriptions of its own.
Choose the completion boundary
| Capability behavior | What success means | Required host hooks |
|---|---|---|
| Synchronous transition | Validated dispatch finished | model, dispatch |
| Emits later result Message | Matching result Message seen | Add observe + correlate |
| Reaches a state condition | Predicate holds on state | Add subscribe (or source) |
Timeouts or cancellations after dispatch stop waiting without rolling back update. Read current state before retrying side-effectful calls.