Agents in your app

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.

Live. Drag a meeting onto Saturday yourself, then let the agent try: the policy refuses the agent only, and the step says why. Undo the agent takes back its changes and leaves yours.

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, Meeting, meetings and weekRules that the Quick start puts in calendar.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 changedHandler on RootWhere it says whoAn agent's value
The calendar's state: view, date, time zoneonViewChange, onAnchorDateChange, and so ondetail.source"agent"
An event: a move, an update, a create, a deleteonEventChange and onEventChangeResultdetail.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:

agent-audit.tsx
"use client";

import { createEventHistory } from "@moltenship/calendar";
import { useState } from "react";

import { CalendarToolbar } from "@/components/calendar/calendar-toolbar";

import { weekdaysForAgents } from "./agent-policy";
import { applyChange, timedOnly, type MeetingChange } from "./agent-save";
import { UndoAgentChange } from "./agent-undo";
import { Calendar, meetings as initialMeetings, weekRules, 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({ onLog }: { readonly onLog: (line: string) => void }) {
  const [meetings, setMeetings] = useState(initialMeetings);
  // The meeting each create became, by change ID, so the history can find it to undo.
  const [createdIds] = useState(() => new Map<string, string>());
  const [history] = useState(() =>
    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));
        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") onLog(`${detail.input} was refused: ${result.reason}`);
      }}
      // State changes say where they came from too: "agent", "mouse", "keyboard", "programmatic".
      onAnchorDateChange={(date, detail) => onLog(`${detail.source} went to ${date.toString()}`)}
      onViewChange={(view, detail) => 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 className="flex h-full flex-col">
        <CalendarToolbar calendar={Calendar}>
          <UndoAgentChange
            history={history}
            onRestore={({ id, title }) =>
              setMeetings((current) =>
                current.map((meeting) => (meeting.id === id ? { ...meeting, title } : meeting)),
              )
            }
          />
        </CalendarToolbar>
        <Calendar.Viewport className="min-h-0 flex-1">
          <Calendar.ActiveView />
        </Calendar.Viewport>
      </Calendar.Frame>
    </Calendar.Root>
  );
}

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 view

change.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:

agent-policy.ts
import type { CalendarPolicy } from "@moltenship/calendar";

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:

  • detail is optional in a policy. It's undefined when your own code calls a policy outside a proposal, so read it as detail?.input.
  • A policy can read what the agent sent. detail?.fields has the title and fields of a createEvent or an updateEvent, 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 input the drop will have, "pointer" or "keyboard", so a rule on detail?.input marks the preview the way it will decide the drop.
  • onEventChangeResult hears the refusal. It gets { status: "rejected", reason } with detail.input of "agent", once. The example's log adds agent 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 from getChange, 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:

agent-week-only.tsx
"use client";

import { CalendarToolbar } from "@/components/calendar/calendar-toolbar";

import { Calendar, meetings, weekRules } from "./calendar";

export function WeekOnlyForAgents() {
  return (
    <Calendar.Root
      label="Team calendar"
      events={meetings}
      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}
    >
      <Calendar.Frame className="flex h-full flex-col">
        <CalendarToolbar calendar={Calendar} />
        <Calendar.Viewport className="min-h-0 flex-1">
          <Calendar.ActiveView />
        </Calendar.Viewport>
      </Calendar.Frame>
    </Calendar.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:

agent-undo.tsx
"use client";

import { useCalendarHistory, type EventHistory } from "@moltenship/calendar";

import { Button } from "@/components/ui/button";

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({
  history,
  onRestore,
}: {
  readonly history: EventHistory<Meeting, string, never>;
  /** Hears the meeting as it was before the step that was undone. */
  readonly onRestore: (before: Meeting) => void;
}) {
  const { canUndo, past, undo } = useCalendarHistory(history);

  return (
    <Button
      disabled={!canUndo}
      onClick={async () => {
        // The step `undo` takes is the last. Its first change has your record as it was before.
        const before = past.at(-1)?.changes[0]?.event;
        const outcome = await 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) {
          onRestore(before);
        }
      }}
      variant="ghost"
    >
      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

Live. Each save takes two seconds. Run a change and read its status, ask again once it has landed, then make the server fail and do the same.

This page has two calendars, so this one 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 savegetChange returns
Hasn't settledThe change with status: "saving"
ResolvedThe change with status: "saved"
Rejected, or the handler threwThe 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":

agent-slow-save.tsx
"use client";

import { useState } from "react";

import { CalendarToolbar } from "@/components/calendar/calendar-toolbar";

import { applyChange, timedOnly, type MeetingChange } from "./agent-save";
import { Calendar, meetings as initialMeetings, weekRules, type Meeting } 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({ onAgentSaveFailed, save }: SavedCalendarProps) {
  const [meetings, setMeetings] = useState<readonly Meeting[]>(initialMeetings);

  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 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) onAgentSaveFailed(result.change);
      }}
      policies={[timedOnly]}
      defaultAnchorDate={Temporal.PlainDate.from("2026-10-08")}
      defaultTimeZone="Europe/Berlin"
      locale="en-US"
      weekRules={weekRules}
    >
      <Calendar.Frame className="flex h-full flex-col">
        <CalendarToolbar calendar={Calendar} />
        <Calendar.Viewport className="min-h-0 flex-1">
          <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 rejected has the reason and not your message. handler-error is all getChange says. 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 getChange before it reports a change that came back as saving or validating.

Next, deleting with the person's say.

On this page