Who made a change
Tell an agent's change from a person's, refuse it with a policy, and undo it without touching what the person did.
An agent's change reaches the same handlers as a person's, with a detail that says who made it.
You can log it, refuse it, and take it back. This page's samples import the
Calendar and Meeting in the Quick start's calendar.tsx, the seed and
weekRules in its app.tsx, and
the bridge in agent.ts from Connect an agent.
Two kinds of change
The calendar tells an agent apart from a person in two places, one for each kind of change:
| What changed | Handler on Root | Where it says who | An agent's value |
|---|---|---|---|
| The calendar's state: view, date, time zone | onViewChange, onAnchorDateChange, and so on | detail.source | "agent" |
| An event: a move, an update, a create, a delete | onEventChange and onEventChangeResult | detail.input | "agent" |
detail.source is one of "agent", "mouse", "touch", "pen", "keyboard", "virtual" or
"programmatic". "keyboard" is a person's keys: a toolbar button pressed with Enter, and also
arrow-key navigation, moving focus between cells and events, and expanding a resource.
"virtual" is a click with no pointer or key behind it, which may come from assistive technology.
"programmatic" is your own code.
detail.input is one of "agent", "pointer", "keyboard" or "api". "api" is your own
proposeEventChange call. An agent's createEvent and updateEvent also bring detail.fields:
the title and the fields it sent, which
your handler stores.
Anything a step causes is the agent's, not only the calendar's own actions. An agent can press a
ui-sdk button your app rendered. If its handler calls proposeEventChange or an action such as
setView, the handlers above hear "agent", whatever input your code passed, and so do your
policies. A person's click on the same button reads as before.
That covers what the button's handler does before it returns. Work the handler starts and finishes
later, after an await, in a timer or in an effect, reads as your own code: "api" for a proposal
and "programmatic" for a state change. ui-sdk tracks the agent for the length of the press and no
longer. So a button that waits before it changes the calendar, as one that asks "are you sure?"
first, isn't covered by a policy on "agent". Keep such a button from agents: put it inside an
element with data-agent-hidden, or refuse the press in the bridge's allow.
This calendar logs both:
import { createEventHistory } from "@moltenship/calendar-solid";
import { createSignal } from "solid-js";
import { weekdaysForAgents } from "./agent-policy";
import { applyChange, timedOnly, type MeetingChange } from "./agent-save";
import { UndoAgentChange } from "./agent-undo";
import { seed, weekRules } from "./app";
import { Calendar, type Meeting } from "./calendar";
function describe(change: MeetingChange): string {
if (change.cause === "delete") return `deleted ${change.eventId}`;
if (change.cause === "create") return "created a meeting";
// "update" is an agent's `updateEvent`: a title, times, or both.
const verb =
change.cause === "move" ? "moved" : change.cause === "update" ? "updated" : "resized";
return `${verb} ${change.eventId}`;
}
export function AuditedCalendar(props: { readonly onLog: (line: string) => void }) {
const [meetings, setMeetings] = createSignal(seed);
// The meeting each create became, by change ID, so the history can find it to undo.
const createdIds = new Map<string, string>();
const history = createEventHistory<Meeting, string, never>({
// Only what an agent did: undo takes back its changes and leaves the person's alone.
inputs: ["agent"],
createdEventId: (change, events) => {
const id = createdIds.get(change.id);
return id !== undefined && events.get(id) !== undefined ? id : undefined;
},
});
return (
<Calendar.Root
label="Team calendar"
events={meetings()}
// `detail.input` says who proposed the change: "pointer", "keyboard", "api" or "agent".
onEventChange={(change, detail) => {
const id =
change.cause === "create" ? (change.event?.id ?? crypto.randomUUID()) : undefined;
if (id !== undefined) createdIds.set(change.id, id);
setMeetings((current) => applyChange(current, change, detail, id));
props.onLog(`${detail.input} ${describe(change)}`);
}}
// How every proposal ended, a policy's refusal included, with the same detail.
onEventChangeResult={(result, detail) => {
history.record(result, detail);
if (result.status === "rejected") {
props.onLog(`${detail.input} was refused: ${result.reason}`);
}
}}
// State changes say where they came from too: "agent", "mouse", "keyboard", "programmatic".
onAnchorDateChange={(date, detail) =>
props.onLog(`${detail.source} went to ${date.toString()}`)
}
onViewChange={(view, detail) => props.onLog(`${detail.source} switched to the ${view} view`)}
policies={[timedOnly, weekdaysForAgents]}
defaultAnchorDate={Temporal.PlainDate.from("2026-10-08")}
defaultTimeZone="Europe/Berlin"
locale="en-US"
weekRules={weekRules}
>
<Calendar.Frame>
<Calendar.Toolbar>
<Calendar.Title />
<UndoAgentChange
history={history}
onRestore={({ id, title }) =>
setMeetings((current) =>
current.map((meeting) => (meeting.id === id ? { ...meeting, title } : meeting)),
)
}
/>
</Calendar.Toolbar>
<Calendar.Viewport>
<Calendar.ActiveView />
</Calendar.Viewport>
</Calendar.Frame>
</Calendar.Root>
);
}The example at the top of this page shows what it logs. AgentSteps is the buttons and the
answer, from Agents in your app:
import { createSignal, For } from "solid-js";
import { agent } from "./agent";
import { AuditedCalendar } from "./agent-audit";
import { AgentSteps, step, type AgentCall } from "./agent-steps";
const calls: readonly AgentCall[] = [
{
label: "Move Standup to Friday at 10:00",
steps: [step("moveEvent", { eventId: "standup", start: "2026-10-09T10:00" })],
},
{
label: "Move Standup to Saturday at 10:00",
steps: [step("moveEvent", { eventId: "standup", start: "2026-10-10T10:00" })],
},
{
label: "Rename Standup",
steps: [step("updateEvent", { eventId: "standup", title: "Daily standup" })],
},
{ label: "Go to the next weeks", steps: [step("navigateNext")] },
];
export default function AgentLogPage() {
const [log, setLog] = createSignal<readonly string[]>([]);
return (
<AgentSteps agent={agent} calls={calls}>
<AuditedCalendar onLog={(line) => setLog((lines) => [...lines, line])} />
<h2>The app's log</h2>
<ol>
<For each={log()} fallback={<li>Nothing yet.</li>}>
{(line) => <li>{line}</li>}
</For>
</ol>
</AgentSteps>
);
}applyChange and timedOnly come from agent-save.ts in
Connect an agent. The policy and the undo button are
below.
After an agent moves the design review and renames the team lunch, a person clicks Next, and the agent switches to the month view, the log reads:
agent moved review
agent updated lunch
mouse went to 2026-10-15
agent switched to the month viewchange.cause is "update" for an agent's updateEvent, whether it changed the title, the times
or both. A person's drag makes a "move" or a resize.
Refuse an agent's change
A policy sees every proposed change before your handler does, and
its second argument has the same detail. This one lets a person book a Saturday and refuses an
agent that tries:
import type { CalendarPolicy } from "@moltenship/calendar-solid";
import type { Meeting } from "./calendar";
// An agent books weekdays only. A person can still drag a meeting onto Saturday: the policy
// reads who proposed the change.
export const weekdaysForAgents: CalendarPolicy<Meeting, string, never> = (
{ proposed },
{ detail, timeZone },
) => {
if (detail?.input !== "agent" || proposed === null || proposed.kind !== "timed") {
return { type: "accept" };
}
const { dayOfWeek } = proposed.start.toZonedDateTimeISO(timeZone);
return dayOfWeek >= 6
? { type: "reject", reason: "agents-book-weekdays-only" }
: { type: "accept" };
};Pass it to Root with your other policies, as policies={[timedOnly, weekdaysForAgents]} above.
The agent's step fails with the policy's reason, and your onEventChange isn't called:
{
"ok": false,
"error": {
"step": 1,
"message": "calendar-event-change-rejected: agents-book-weekdays-only"
},
"steps": [{ "step": 0, "ref": "c1" }],
"appeared": [],
"values": {}
}Write the reason for the model that reads it. agents-book-weekdays-only tells it what to try
next; rejected doesn't. An agent can't ask beforehand whether a change would pass, so the reason
is how it learns your rules.
A few things to know:
detailis optional in a policy. It'sundefinedwhen your own code calls a policy outside a proposal, so read it asdetail?.input.- A policy can read what the agent sent.
detail?.fieldshas the title and fields of acreateEventor anupdateEvent, before anything is saved. - Each policy runs once for an agent's change. A drag or a keyboard move asks your policies
more often: for each preview, then for the drop. Every one of those calls has the
inputthe drop will have,"pointer"or"keyboard", so a rule ondetail?.inputmarks the preview the way it will decide the drop. onEventChangeResulthears the refusal. It gets{ status: "rejected", reason }withdetail.inputof"agent", once. The example's log addsagent was refused: agents-book-weekdays-only.- A policy that returns a promise can't fail the step. The step returns the change with
status: "validating", and the agent reads the refusal fromgetChange, as for a save that takes a while. Where you can, decide an agent's changes with a policy that answers at once.
Your handler can refuse too, by throwing. The agent then reads handler-error and your error's
message, as in calendar-event-change-rejected: handler-error (This slot was just taken). Write
that message for the model as well, and keep anything private out of it.
The same policy works for every other input. detail?.input === "keyboard" is a keyboard move, and
detail?.history is "undo" or "redo" for a change the history proposes.
Refuse a state change
A state handler's detail has cancel(). This Root keeps an agent out of the month view:
import { seed, weekRules } from "./app";
import { TeamCalendar } from "./team-calendar";
export function ListOnlyForAgents() {
return (
<TeamCalendar.Root
label="Team calendar"
events={seed}
onViewChange={(view, detail) => {
// A person can still open the month view.
if (detail.source === "agent" && view === "month") detail.cancel();
}}
defaultAnchorDate={Temporal.PlainDate.from("2026-10-08")}
defaultTimeZone="Europe/Berlin"
locale="en-US"
weekRules={weekRules}
>
<TeamCalendar.Frame>
<TeamCalendar.Toolbar>
<TeamCalendar.Title />
<TeamCalendar.ViewSwitcher
aria-label="View"
getViewLabel={(view) => (view === "list" ? "Agenda" : "Month")}
/>
</TeamCalendar.Toolbar>
<TeamCalendar.Viewport>
<TeamCalendar.ActiveView />
</TeamCalendar.Viewport>
</TeamCalendar.Frame>
</TeamCalendar.Root>
);
}A cancelled change doesn't fail the step. The call returns ok: true and the step has no
changes, so the agent sees that nothing happened. To fail the step with a message instead,
refuse the action in the bridge's allow.
For a controlled value, not storing the new value does the same
as cancel().
Undo an agent's changes
An event history records changes and undoes them through the same pipeline.
inputs: ["agent"] makes one that records an agent's changes only, so its undo never takes back a
drag. AuditedCalendar in agent-audit.tsx creates it with
createEventHistory<Meeting, string, never>({ inputs: ["agent"], createdEventId }) and records
into it from onEventChangeResult with history.record(result, detail).
The button reads the history with useCalendarHistory, anywhere inside Root:
import { useCalendarHistory, type EventHistory } from "@moltenship/calendar-solid";
import type { Meeting } from "./calendar";
// Anywhere inside Root. The history it's given holds an agent's changes only, so this never
// undoes a drag.
export function UndoAgentChange(props: {
readonly history: EventHistory<Meeting, string, never>;
/** Hears the meeting as it was before the step that was undone. */
readonly onRestore: (before: Meeting) => void;
}) {
const controls = useCalendarHistory(props.history);
return (
<button
type="button"
disabled={!controls().canUndo}
onClick={async () => {
// The step `undo` takes is the last. Its first change has your record as it was before.
const before = controls().past.at(-1)?.changes[0]?.event;
const outcome = await controls().undo();
// The history puts times and resources back. It doesn't know your fields, so a title
// the agent changed is yours to restore.
if (outcome.status === "committed" && before !== undefined && before !== null) {
props.onRestore(before);
}
}}
>
Undo the agent
</button>
);
}The undo is a proposal of its own. When a person clicks the button, your onEventChange gets it
with detail.input of "api" and detail.history of "undo", and the log above adds
api moved review. It isn't the agent's, so a policy that refuses agents doesn't refuse it.
It is the agent's when the agent presses the button. Had this one been a ui-sdk button, a press
step on it would propose the undo with input: "agent" and history: "undo", and
weekdaysForAgents would have its say. Undoing a create proposes a delete, so on a Root without
allowAgentDelete the agent's press would be refused with agent-delete-not-allowed.
The history records where an event was, not your fields. Undoing an agent's rename proposes the
event's times again, with no detail.fields, and the new title would stay. So the button reads
the step it's about to undo: past.at(-1).changes[0].event is your record as it was before the
step, and onRestore puts its title back once the undo is saved. AuditedCalendar passes
onRestore a function that copies the title into its meetings.
To undo an agent's createEvent, the history has to find the event the create became. That's what
createdEventId in AuditedCalendar is for; Undo and redo
explains it.
For one history that holds everyone's changes, leave inputs out. Each step in past from
useCalendarHistory has the input that made it, so your UI can still mark the agent's.
Saves that take a while
The calendar in this section shares its page with another one, so it has a label of its own,
Bookings. An agent names a calendar by its label, and a step on a label two calendars share
fails: the bridge can't tell which one is meant.
When onEventChange returns a promise, the calendar shows the change as
pending while it settles. The agent's step doesn't wait for
it. It returns the change at once, with status: "saving":
{
"cause": "move",
"changeId": "change-1",
"eventId": "review",
"proposed": {
"start": "2026-10-09T10:00:00+02:00",
"end": "2026-10-09T11:00:00+02:00",
"kind": "timed",
"resourceIds": []
},
"status": "saving"
}The agent asks how it ended with getChange, a step like any other:
{ "ref": "Bookings", "action": "getChange", "args": [{ "changeId": "change-1" }] }| The save | getChange returns |
|---|---|
| Hasn't settled | The change with status: "saving" |
| Resolved | The change with status: "saved" |
| Rejected, or the handler threw | The change with status: "rejected", reason: "handler-error" |
While a change saves, describeCalendar lists it in pendingChanges, and listEvents shows a
moved or updated event where it's going, with "pending": true. A new event is different: it
isn't in listEvents until your events has it, so an agent that created one reads getChange
first and lists the events once it's saved. A calendar remembers the last 50 changes agents
proposed on it, so an ID from earlier in a conversation still answers.
Your app hears the same outcome at onEventChangeResult, with detail.input of "agent":
import { createSignal } from "solid-js";
import { applyChange, timedOnly, type MeetingChange } from "./agent-save";
import { seed, weekRules } from "./app";
import { Calendar } from "./calendar";
export interface SavedCalendarProps {
/** Hears an agent's change whose save failed after the agent was told "saving". */
readonly onAgentSaveFailed: (change: MeetingChange) => void;
/** Your server call: resolves once the change is stored, or rejects. */
readonly save: (change: MeetingChange) => Promise<void>;
}
export function SavedCalendar(props: SavedCalendarProps) {
const [meetings, setMeetings] = createSignal(seed);
return (
<Calendar.Root
// Its own name: a page with two calendars gives each one a label.
label="Bookings"
events={meetings()}
// The calendar shows the change as pending until this promise settles, and the agent's
// step returns it with `status: "saving"`.
onEventChange={async (change, detail) => {
await props.save(change);
setMeetings((current) => applyChange(current, change, detail));
}}
// How every proposal ended, the agent's included. The agent reads the same from `getChange`.
onEventChangeResult={(result, detail) => {
if (detail.input !== "agent" || result.status !== "rejected") return;
if (result.change !== undefined) props.onAgentSaveFailed(result.change);
}}
policies={[timedOnly]}
defaultAnchorDate={Temporal.PlainDate.from("2026-10-08")}
defaultTimeZone="Europe/Berlin"
locale="en-US"
weekRules={weekRules}
>
<Calendar.Frame>
<Calendar.Viewport>
<Calendar.ActiveView />
</Calendar.Viewport>
</Calendar.Frame>
</Calendar.Root>
);
}save is your own server call. When it fails, the calendar puts the event back as it was, the
agent's getChange reads rejected, and onAgentSaveFailed is where your app tells the person.
A failed save leaves nothing in the browser's console that you didn't put there.
Two differences from a refusal that fails the step:
- A late
rejectedhas the reason and not your message.handler-erroris allgetChangesays. A handler that throws before it returns a promise fails the step, and that message carries your error's text. - Nothing tells the agent. It reads a late outcome only when it asks. Tell your model to call
getChangebefore it reports a change that came back assavingorvalidating.