# Animated Agent Pointer for UI SDK (/docs/components/agent-pointer)

See an agent act in your UI. Follow its UI SDK actions, approve sensitive steps, or take over to stop the rest.

<ComponentPreview slug="agent-pointer" source="{&#x22;code&#x22;:&#x22;\&#x22;use client\&#x22;\n\nimport { createAgent, type AgentStep } from \&#x22;@ui-sdk/react/agent\&#x22;\nimport { elementOf } from \&#x22;@ui-sdk/react/observe\&#x22;\nimport * as React from \&#x22;react\&#x22;\n\nimport { AgentPointer, createAgentPointer } from \&#x22;@/components/keyframery/agent-pointer\&#x22;\nimport { createApprovals } from \&#x22;@/components/keyframery/approval\&#x22;\nimport { Badge } from \&#x22;@/components/keyframery/badge\&#x22;\nimport { Button } from \&#x22;@/components/keyframery/button\&#x22;\nimport { Form, FormItem, FormLabel, FormMessage, FormStatus, FormSubmit } from \&#x22;@/components/keyframery/form\&#x22;\nimport { Input } from \&#x22;@/components/keyframery/input\&#x22;\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \&#x22;@/components/keyframery/select\&#x22;\n\nconst times = { \&#x22;sat-11\&#x22;: \&#x22;Saturday, 11:00\&#x22;, \&#x22;sat-14\&#x22;: \&#x22;Saturday, 14:00\&#x22; }\nconst bookingSteps: AgentStep[] = [\n  { ref: \&#x22;Full name\&#x22;, action: \&#x22;setValue\&#x22;, args: [\&#x22;Maya Okafor\&#x22;] },\n  { ref: \&#x22;Phone\&#x22;, action: \&#x22;setValue\&#x22;, args: [\&#x22;07700 900461\&#x22;] },\n  { ref: \&#x22;Email\&#x22;, action: \&#x22;setValue\&#x22;, args: [\&#x22;maya@okafor.studio\&#x22;] },\n  { ref: \&#x22;Viewing time\&#x22;, action: \&#x22;setValue\&#x22;, args: [\&#x22;sat-11\&#x22;] },\n  { ref: \&#x22;Book a viewing\&#x22;, action: \&#x22;submit\&#x22; },\n]\n\nconst planned: AgentStep[] = [\n  ...bookingSteps,\n  { ref: \&#x22;Manage booking\&#x22;, action: \&#x22;press\&#x22; },\n  { ref: \&#x22;Cancel booking\&#x22;, action: \&#x22;press\&#x22; },\n]\n\ntype DemoProps = {\n  label?: string\n  showValues?: boolean\n  themeSize?: number\n  themeRadius?: number\n  themeFont?: number\n  themeRing?: number\n  themeAccent?: string\n  themeInk?: string\n  themePreview?: string\n  themePreviewInk?: string\n}\n\nexport default function AgentPointerDemo({\n  label = \&#x22;Claude\&#x22;, showValues = true, themeSize = 25, themeRadius = 6, themeFont = 12, themeRing = 2,\n  themeAccent = \&#x22;\&#x22;, themeInk = \&#x22;\&#x22;, themePreview = \&#x22;\&#x22;, themePreviewInk = \&#x22;\&#x22;,\n}: DemoProps) {\n  const scope = React.useRef<HTMLDivElement>(null)\n  const dialog = React.useRef<HTMLDialogElement>(null)\n  const preview = React.useRef(showValues)\n  preview.current = showValues\n  const [booked, setBooked] = React.useState(false)\n  const [cancelled, setCancelled] = React.useState(false)\n  const [running, setRunning] = React.useState(false)\n  const [started, setStarted] = React.useState(false)\n  const [formKey, setFormKey] = React.useState(0)\n  const [{ pointer, bridge }] = React.useState(() => {\n    const approvals = createApprovals({\n      keep: 0,\n      describe: () => ({\n        title: \&#x22;Cancel the previous viewing?\&#x22;,\n        description: \&#x22;Maya’s Tuesday slot will be released. Her Saturday booking stays confirmed.\&#x22;,\n        target: \&#x22;\&#x22;,\n      }),\n    })\n    const pointer = createAgentPointer({\n      resolveTarget: (action) => action.action === \&#x22;submit\&#x22; ? scope.current?.querySelector('[data-slot=\&#x22;form-submit\&#x22;]') ?? undefined : undefined,\n      previewValue: ({ args: [value] }) => preview.current && typeof value === \&#x22;string\&#x22; ? times[value as keyof typeof times] ?? value : undefined,\n    })\n    const bridge = typeof window === \&#x22;undefined\&#x22; ? undefined : createAgent({\n      allow: pointer.wrapAllow({ approvals, authorize: (step) =>\n        !!scope.current?.contains(elementOf(step.ref)) &&\n        planned.some((item) => item.ref === step.label && item.action === step.action) }),\n    })\n    return { pointer, bridge }\n  })\n\n  async function run() {\n    if (running || started || !bridge) return\n    setStarted(true)\n    setRunning(true)\n    try {\n      const entries = bridge.snapshot()\n      // Autoplay previews the booking. Opening a modal requires the visitor to start the run.\n      const autoplaying = scope.current?.closest('[data-playback=\&#x22;playing\&#x22;]')\n      const steps = (autoplaying ? bookingSteps : planned).map((step) => {\n        const entry = entries.find((item) => item.label === step.ref && scope.current?.contains(elementOf(item.ref)))\n        return entry ? { ...step, ref: entry.ref } : step\n      })\n      const result = await pointer.run(bridge, { steps })\n      if (!result.ok) dialog.current?.close()\n    } finally {\n      setRunning(false)\n    }\n  }\n\n  function reset() {\n    dialog.current?.close()\n    pointer.reset()\n    setStarted(false)\n    setBooked(false)\n    setCancelled(false)\n    setFormKey((key) => key + 1)\n  }\n\n  const theme = {\n    \&#x22;--agent-pointer-accent\&#x22;: themeAccent || undefined,\n    \&#x22;--agent-pointer-ink\&#x22;: themeInk || undefined,\n    \&#x22;--agent-pointer-preview\&#x22;: themePreview || undefined,\n    \&#x22;--agent-pointer-preview-ink\&#x22;: themePreviewInk || undefined,\n    \&#x22;--agent-pointer-size\&#x22;: `${themeSize}px`,\n    \&#x22;--agent-pointer-radius\&#x22;: `${themeRadius}px`,\n    \&#x22;--agent-pointer-font\&#x22;: `${themeFont}px`,\n    \&#x22;--agent-pointer-ring\&#x22;: `${themeRing}px`,\n  } as React.CSSProperties\n\n  return (\n    <div ref={scope} className=\&#x22;@container w-full max-w-[680px]\&#x22; data-agent-pointer-demo data-agent-pointer-scope data-preview-values={showValues}>\n      <div className=\&#x22;rounded-[18px] border border-border bg-card text-card-foreground\&#x22;>\n        <div className=\&#x22;flex flex-wrap items-center justify-between gap-2.5 border-b border-border px-4 py-3\&#x22;>\n          <div className=\&#x22;space-y-0.5\&#x22;>\n            <div className=\&#x22;text-[13px] font-semibold\&#x22;>Viewing desk</div>\n            <div className=\&#x22;text-[11px] text-muted-foreground\&#x22;>Scripted run through UI SDK</div>\n          </div>\n          <div className=\&#x22;flex flex-wrap items-center gap-1.5\&#x22; data-agent-hidden>\n            <Button size=\&#x22;sm\&#x22; data-pointer-play=\&#x22;start\&#x22; disabled={started} onClick={run}>Let the agent do it</Button>\n            <Button variant=\&#x22;ghost\&#x22; size=\&#x22;sm\&#x22; disabled={running} onClick={reset}>Reset</Button>\n          </div>\n        </div>\n        <div className=\&#x22;grid gap-4 p-4 @min-[36rem]:grid-cols-[1fr_190px]\&#x22;>\n          <section className=\&#x22;min-w-0 rounded-[13px] bg-background p-3.5 ring-1 ring-border\&#x22;>\n            <div className=\&#x22;flex items-center gap-3\&#x22;>\n              <img src=\&#x22;/demo/canal.jpg\&#x22; alt=\&#x22;\&#x22; className=\&#x22;size-11 shrink-0 rounded-[8px] bg-muted object-cover\&#x22; />\n              <div className=\&#x22;min-w-0\&#x22;>\n                <div className=\&#x22;text-[14px] font-semibold tracking-tight\&#x22;>Book a viewing</div>\n                <div className=\&#x22;text-[12px] leading-snug text-muted-foreground\&#x22;>Two-bed flat on the canal, Hackney Wick</div>\n              </div>\n            </div>\n            <Form key={formKey} aria-label=\&#x22;Book a viewing\&#x22; submit={() => { setBooked(true); return { message: \&#x22;Saturday viewing confirmed.\&#x22; } }} className=\&#x22;mt-3.5 [--form-gap:10px]\&#x22;>\n              <div className=\&#x22;grid grid-cols-2 gap-2.5 @max-[23rem]:grid-cols-1\&#x22;>\n                <FormItem name=\&#x22;name\&#x22;>\n                  <FormLabel>Full name</FormLabel>\n                  <Input autoComplete=\&#x22;name\&#x22; required />\n                  <FormMessage match=\&#x22;valueMissing\&#x22;>Tell us who's coming.</FormMessage>\n                </FormItem>\n                <FormItem name=\&#x22;phone\&#x22;>\n                  <FormLabel>Phone</FormLabel>\n                  <Input type=\&#x22;tel\&#x22; autoComplete=\&#x22;tel\&#x22; required />\n                  <FormMessage match=\&#x22;valueMissing\&#x22;>Enter a phone number.</FormMessage>\n                </FormItem>\n              </div>\n              <FormItem name=\&#x22;email\&#x22;>\n                <FormLabel>Email</FormLabel>\n                <Input type=\&#x22;email\&#x22; autoComplete=\&#x22;email\&#x22; required />\n                <FormMessage match=\&#x22;typeMismatch\&#x22;>Enter a valid email address.</FormMessage>\n              </FormItem>\n              <div className=\&#x22;flex flex-wrap items-center gap-2.5 pt-1\&#x22;>\n                <Select name=\&#x22;slot\&#x22; required>\n                  <SelectTrigger aria-label=\&#x22;Viewing time\&#x22; className=\&#x22;w-[150px]\&#x22;>\n                    <SelectValue placeholder=\&#x22;Choose a time\&#x22; />\n                  </SelectTrigger>\n                  <SelectContent>\n                    {Object.entries(times).map(([value, text]) => <SelectItem key={value} value={value}>{text}</SelectItem>)}\n                  </SelectContent>\n                </Select>\n                <FormSubmit successLabel=\&#x22;Booked\&#x22;>Book viewing</FormSubmit>\n              </div>\n              <FormStatus />\n            </Form>\n          </section>\n          <section className=\&#x22;flex min-w-0 flex-col items-start gap-2.5 rounded-[13px] bg-muted/60 p-3.5\&#x22;>\n            <div className=\&#x22;text-[12px] font-semibold\&#x22;>Previous booking</div>\n            <div>\n              <div className=\&#x22;text-[13px] font-medium\&#x22;>Tuesday, 16:00</div>\n              <div className=\&#x22;text-[12px] text-muted-foreground\&#x22;>Hackney Wick · Maya Okafor</div>\n            </div>\n            <Badge variant={cancelled ? \&#x22;secondary\&#x22; : \&#x22;outline\&#x22;}>{cancelled ? \&#x22;Cancelled\&#x22; : \&#x22;Confirmed\&#x22;}</Badge>\n            <Button size=\&#x22;sm\&#x22; variant=\&#x22;default\&#x22; aria-label=\&#x22;Manage booking\&#x22; disabled={cancelled} onClick={() => dialog.current?.showModal()}>Manage booking</Button>\n          </section>\n        </div>\n        <div className=\&#x22;flex min-h-12 flex-wrap items-center justify-between gap-x-3 gap-y-1 border-t border-border px-4 py-1.5\&#x22;>\n          <AgentPointer controller={pointer} label={label} style={theme} />\n          <span className=\&#x22;text-[11px] text-muted-foreground\&#x22;>{booked ? \&#x22;New viewing booked\&#x22; : \&#x22;Booking #1048\&#x22;}</span>\n        </div>\n      </div>\n      <dialog ref={dialog} aria-label=\&#x22;Manage previous booking\&#x22; onCancel={() => pointer.takeOver()} className=\&#x22;m-auto w-[min(360px,calc(100%-32px))] rounded-[16px] border border-border bg-popover p-4 text-popover-foreground shadow-xl backdrop:bg-foreground/25 dark:backdrop:bg-background/65\&#x22;>\n        <div className=\&#x22;text-[15px] font-semibold\&#x22;>Previous viewing</div>\n        <p className=\&#x22;mt-1 text-[13px] text-muted-foreground\&#x22;>Tuesday, 16:00 · Hackney Wick</p>\n        <div className=\&#x22;mt-4 flex flex-wrap gap-2\&#x22;>\n          <Button size=\&#x22;sm\&#x22; variant=\&#x22;destructive\&#x22; autoFocus data-agent-confirm=\&#x22;Release Tuesday’s viewing slot\&#x22; onClick={() => { setCancelled(true); dialog.current?.close() }}>Cancel booking</Button>\n          <Button size=\&#x22;sm\&#x22; variant=\&#x22;default\&#x22; data-agent-hidden onClick={() => { pointer.takeOver(); dialog.current?.close() }}>Keep booking</Button>\n        </div>\n      </dialog>\n    </div>\n  )\n}&#x22;,&#x22;bindings&#x22;:{&#x22;label&#x22;:[1571,1579],&#x22;showValues&#x22;:[1594,1598],&#x22;themeSize&#x22;:[1612,1614],&#x22;themeRadius&#x22;:[1630,1631],&#x22;themeFont&#x22;:[1645,1647],&#x22;themeRing&#x22;:[1661,1662],&#x22;themeAccent&#x22;:[1680,1682],&#x22;themeInk&#x22;:[1695,1697],&#x22;themePreview&#x22;:[1714,1716],&#x22;themePreviewInk&#x22;:[1736,1738]},&#x22;root&#x22;:[4596,9895],&#x22;importOffset&#x22;:702}" />

## Connect the pointer to your agent [#connect-the-pointer-to-your-agent]

Create one controller for the mounted view. Pass `pointer.wrapAllow({ authorize, approvals })` to `createAgent({ allow })` and send planned mutations to `pointer.run(agent, { steps })`. Give `authorize` your app's permission policy. It runs before the pointer moves or asks the person. Pass `createApprovals()` from [Approval](/docs/components/approval) to let the person answer marked steps. A step marked `data-agent-confirm` fails with “Needs a person: no approval handler is configured.” when the handler is missing.

Wrap one model turn in `pointer.session(() => runModel(...))` to keep the status and **Take over** available while the model works between tool calls. For one-off calls to `pointer.run`, the control stays available briefly in case another call follows. Only one pointer run can be active per document.

**Take over** cancels remaining steps and puts the controller on hold across later calls. Changes already applied stay in place, and an action already executing can finish. If a tool result says the person took over, return it to the model and end the current tool loop. The person can choose **Let Claude continue**, or your app can call `pointer.resume()` on their behalf before starting a new turn. The status and approval controls are for the person using the app and are hidden from UI SDK's agent tools.

Send the model the schemas in `agent.tools`. Use `snapshot` and plain `query` to discover controls, and route each `act` through `pointer.run`. For dialogs, send an open step and a separate press step. Add this sentence to the model's system prompt.

> You may press buttons marked for confirmation, and the app will ask the person before carrying out those actions.

The pointer follows agents acting through UI SDK's bridge. It works with app-driven `act` and can show visible mutations from WebMCP tools published with `registerTools`. Screenshot and computer-use agents bypass this bridge. When registering WebMCP tools, give `registerTools` a separate caller policy and keep the human decision in `createAgent`. The native WebMCP registration owns its own call lifecycle in UI SDK beta.17. Use `pointer.run` for the full presentation and the Take over control.

See [WebMCP in React with approval](/docs/guides/webmcp-react) for a browser tool that calls `pointer.run` and waits for the person's answer.

The bridge reports a component ref. The pointer lands on the component unless the default button lookup or your `resolveTarget(action)` finds the exact element. If there is no visible target, the pointer shows status instead. Put `data-agent-pointer-scope` on the surrounding view to limit which scroll containers the pointer moves. It highlights changes reported for the same ref with source `agent`. An asynchronous outcome can arrive later as a programmatic change.

Values are hidden by default. Use `previewValue(action)` to return a display string for non-sensitive `setValue` steps. The typing effect is a visual treatment. UI SDK commits the whole value at once. Passwords, redacted values and controls marked `data-agent-secret` stay hidden. With reduced motion, the target is highlighted in place and the run skips the arrival wait.

## Installation [#installation]

**React**

**CLI**

```bash
npx shadcn@latest add @keyframery/agent-pointer @keyframery/input @keyframery/form @keyframery/select
```

This adds `components/keyframery/agent-pointer.tsx` and its primitive to your project, and installs UI SDK, along with [approval](/docs/components/approval), which it builds on. The motion tokens are added to your global CSS the first time you install a component. The install command also adds [input](/docs/components/input), [form](/docs/components/form), [select](/docs/components/select) for the preview and examples.

**Manual**

**Install the dependencies**

```bash
npm install @ui-sdk/core@0.1.0-beta.17 @ui-sdk/react@0.1.0-beta.17 clsx tailwind-merge
```

**Add the motion tokens**

Copy the [motion tokens](/docs/installation/manual#add-the-motion-tokens) into your global CSS, and this file into `lib/keyframery.tsx`. Every component shares them.

**lib/keyframery.tsx**

```tsx
"use client"

/* Speed for Keyframery components, as a prop.

   Every duration in the components is written as calc(Nms * var(--kf-speed, 1)). These helpers set
   that variable for you, so nobody has to know it exists:

     <Tabs speed="fast">                      one component
     <KeyframeryProvider speed="slow">        the whole app

   Parts that render in a portal (popups, menus, dialogs) are not inside the component in the page,
   so they pick the speed up through React context instead of the CSS cascade. */

import * as React from "react"

/** `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or any multiplier: `0.8` is 20% quicker. */
export type Speed = "fast" | "normal" | "slow" | number

export type SpeedProps = {
  /** How fast the component moves. `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or a multiplier like `0.8`. Popups follow it too. */
  speed?: Speed
}

export type MotionStyleName = "subtle" | "springy" | "calm" | "snappy" | "playful"

const presets = { fast: 0.6, normal: 1, slow: 1.4 } as const

export function speedValue(speed: Speed | undefined): number | undefined {
  if (speed === undefined) return undefined
  return typeof speed === "number" ? speed : presets[speed]
}

const SpeedContext = React.createContext<number | undefined>(undefined)

type SpeedStyle = React.CSSProperties & { "--kf-speed"?: number }

/* Wraps a component's parts. Without `speed` it adds nothing to the page. With it, a
   `display: contents` element carries the variable to the parts in place, and context carries it
   to the parts in a portal. */
export function Speed({ speed, children }: SpeedProps & { children?: React.ReactNode }) {
  const value = speedValue(speed)
  if (value === undefined) return children
  const style: SpeedStyle = { display: "contents", "--kf-speed": value }
  return (
    <SpeedContext value={value}>
      <span data-slot="speed" style={style}>
        {children}
      </span>
    </SpeedContext>
  )
}

/* For parts that render in a portal: adds the speed of the component they belong to. `style` can
   be an object or UI SDK's function of the part's state. */
export function useSpeedStyle<S>(style: S): S {
  return withSpeed(style, React.useContext(SpeedContext))
}

/* Adds a speed to a part's own `style`, for a part that takes `speed` and renders in a portal. */
export function withSpeed<S>(style: S, speed: Speed | undefined): S {
  const value = speedValue(speed)
  if (value === undefined) return style
  if (typeof style === "function")
    return ((state: unknown) => ({ "--kf-speed": value, ...(style as (s: unknown) => React.CSSProperties)(state) })) as S
  return { "--kf-speed": value, ...(style as React.CSSProperties | undefined) } as S
}

/* UI SDK parts take `children` as content or as a function of the part's state. A styled part
   that adds elements of its own (a chevron, a moving key) wraps either form with this, so the
   function form keeps working. */
export function mapChildren<State>(
  children: React.ReactNode | ((state: State) => React.ReactNode),
  wrap: (content: React.ReactNode) => React.ReactNode,
): React.ReactNode | ((state: State) => React.ReactNode) {
  return typeof children === "function" ? (state: State) => wrap(children(state)) : wrap(children)
}

/* Sets speed and motion style for the whole app, popups included. A component's own `speed` prop
   still wins inside that component. Server-rendered pages can put `data-motion` on <html> directly
   to avoid a change after hydration. */
export function KeyframeryProvider({
  speed,
  motion,
  children,
}: SpeedProps & {
  /** The motion style for the whole app: `"subtle"` (the default), `"calm"`, `"springy"`, `"snappy"` or `"playful"`. */
  motion?: MotionStyleName
  children?: React.ReactNode
}) {
  const value = speedValue(speed)
  React.useLayoutEffect(() => {
    const html = document.documentElement
    if (motion) html.setAttribute("data-motion", motion)
    if (value !== undefined) html.style.setProperty("--kf-speed", String(value))
    return () => {
      if (motion) html.removeAttribute("data-motion")
      if (value !== undefined) html.style.removeProperty("--kf-speed")
    }
  }, [motion, value])
  return children
}
```

**Add what it builds on**

Install [approval](/docs/components/approval) the same way first.

**Add the example components**

Install [input](/docs/components/input), [form](/docs/components/form), [select](/docs/components/select) to use the preview and examples on this page.

**Copy the component**

**components/keyframery/agent-pointer.tsx**

```tsx
"use client"

/* --agent-pointer-accent: Cursor, target and ripple.
   --agent-pointer-ink: Cursor label text.
   --agent-pointer-preview: Value preview surface.
   --agent-pointer-preview-ink: Value preview text.
   --agent-pointer-size: Cursor size.
   --agent-pointer-radius: Label and preview corners.
   --agent-pointer-font: Label text size.
   --agent-pointer-ring: Target outline thickness. */

import * as React from "react"
import { createPortal } from "react-dom"

import {
  AgentPointerRoot, AgentPointerStatus, AgentPointerAnnouncement, AgentPointerOverlay, AgentPointerCursor, AgentPointerHighlight,
  AgentPointerPanel, AgentPointerPreview, AgentPointerTakeOver, agentPointerMotion as motion, agentPointerKeyframes,
} from "@/components/keyframery/primitives/agent-pointer"
import type { AgentPointerController } from "@/components/keyframery/primitives/agent-pointer"
import { Approval } from "@/components/keyframery/approval"
import { useSpeedStyle, withSpeed, type SpeedProps } from "@/lib/keyframery"
import { cn } from "@/lib/utils"

export { createAgentPointer, type AgentPointerController, type AgentPointerOptions } from "@/components/keyframery/primitives/agent-pointer"

const takeOver = "inline-flex h-8 shrink-0 items-center rounded-[9px] border border-border bg-background px-2.5 text-[12px] font-medium text-foreground outline-none hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring aria-disabled:pointer-events-none aria-disabled:opacity-50"
const approvalTakeOver = "inline-flex h-8 shrink-0 items-center rounded-md px-2.5 text-[12px] font-medium text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
const approvalCard = "pointer-events-auto w-full max-w-[344px] [&_[data-slot=approval-title]]:whitespace-normal [&_[data-slot=approval-title]]:[overflow-wrap:anywhere]"
const statusText = "min-w-0 wrap-anywhere text-[12px] leading-snug text-muted-foreground"
const modalStatus = "mt-3 flex min-w-0 items-center justify-between gap-2 border-t border-border pt-2"

export type AgentPointerProps = Omit<React.ComponentProps<typeof AgentPointerRoot>, "children" | "pointerController"> & SpeedProps & {
  /** A controller created with createAgentPointer. */
  controller: AgentPointerController
}

/** Agent status, decorative pointer, and the person's controls. */
export function AgentPointer({ controller, speed, className, style, ...props }: AgentPointerProps) {
  const rootStyle = useSpeedStyle(withSpeed(style, speed))
  return (
    <AgentPointerRoot
      {...props}
      pointerController={controller}
      style={rootStyle}
      className={typeof className === "function" ? (state) => cn("flex min-w-0 items-center gap-2", className(state)) : cn("flex min-w-0 items-center gap-2", className)}
    >
      {(state) => {
        // The layer can move into a native modal. Carry the local CSS variables along with it.
        const styled = typeof rootStyle === "function" ? rootStyle(state) : rootStyle
        const layerStyle = styled && Object.fromEntries(Object.entries(styled).filter(([key]) => key.startsWith("--")))
        const control = (className: string) => (
          <AgentPointerTakeOver className={className}>{({ text }) => text}</AgentPointerTakeOver>
        )
        const approval = state.request && (
          <Approval key={state.request.id} request={state.request} autoFocus="deny" className={approvalCard}
            leadingAction={state.canTakeOver && control(approvalTakeOver)} />
        )
        const overlay = state.active && state.frame && (
          <AgentPointerOverlay className={motion.overlay} style={layerStyle}>
            {state.frame && (
              <>
                <AgentPointerHighlight className={cn(motion.ring, "rounded-[9px] outline-solid outline-[length:var(--agent-pointer-ring,2px)] outline-[color:var(--agent-pointer-accent,var(--primary))]")} />
                <AgentPointerCursor className={motion.cursor}>
                  {({ label }) => (
                    <>
                      <span className={cn(motion.ripple, "size-8 rounded-full border-2 border-[color:var(--agent-pointer-accent,var(--primary))]")} />
                      <svg viewBox="0 0 24 24" className="block size-[var(--agent-pointer-size,25px)] overflow-visible drop-shadow-sm" fill="var(--agent-pointer-accent,var(--primary))" stroke="var(--background)" strokeWidth="1.35" focusable="false">
                        <path d="M3 2.5 20 10l-7.6 2.2-3.8 7.3L3 2.5Z" strokeLinejoin="round" />
                      </svg>
                      <span className="absolute start-5 top-[15px] max-w-[min(12rem,50vw)] truncate rounded-[var(--agent-pointer-radius,6px)] bg-[var(--agent-pointer-accent,var(--primary))] px-2 py-1 text-[length:var(--agent-pointer-font,12px)] leading-none font-semibold text-[color:var(--agent-pointer-ink,var(--primary-foreground))] shadow-sm group-data-flip/pointer:start-auto group-data-flip/pointer:end-2">{label}</span>
                    </>
                  )}
                </AgentPointerCursor>
                {state.preview && state.previewAt && (
                  <AgentPointerPreview className={cn(motion.preview, "rounded-[var(--agent-pointer-radius,6px)] bg-[var(--agent-pointer-preview,var(--popover))] px-2 py-1 text-[12px] text-[color:var(--agent-pointer-preview-ink,var(--popover-foreground))] shadow-md ring-1 ring-border")}>
                    {({ preview }) => <span className={motion.reveal}>{preview}</span>}
                  </AgentPointerPreview>
                )}
              </>
            )}
            {approval && state.panel && (
              <AgentPointerPanel className={motion.panel}>{approval}</AgentPointerPanel>
            )}
          </AgentPointerOverlay>
        )
        return (
          <>
            <style href="kf-agent-pointer" precedence="default">{agentPointerKeyframes}</style>
            <div className={cn("flex min-w-0 flex-col gap-2", state.layer && "invisible")}>
              <div className="flex min-w-0 items-center gap-2">
                <AgentPointerStatus className={statusText}>{({ message }) => message}</AgentPointerStatus>
                {!state.layer && !state.request && (state.canTakeOver || state.held) && control(takeOver)}
              </div>
              {approval && !state.panel && !state.layer && <AgentPointerPanel>{approval}</AgentPointerPanel>}
            </div>
            {state.layer ? createPortal(
              <>
                <AgentPointerAnnouncement className="sr-only" />
                {approval
                  ? !state.panel && <AgentPointerPanel className="mt-3" style={layerStyle}>{approval}</AgentPointerPanel>
                  : (state.canTakeOver || state.held) && (
                    <AgentPointerPanel className={modalStatus} style={layerStyle}>
                      <AgentPointerStatus className={statusText}>{({ message }) => message}</AgentPointerStatus>
                      {control(takeOver)}
                    </AgentPointerPanel>
                  )}
              </>,
              state.layer,
            ) : <AgentPointerAnnouncement className="sr-only" />}
            {state.layer && overlay ? createPortal(overlay, state.layer) : overlay}
          </>
        )
      }}
    </AgentPointerRoot>
  )
}
```

**components/keyframery/primitives/agent-pointer.tsx**

```tsx
"use client"

import { elementOf } from "@ui-sdk/react/observe"
import { createParts } from "@ui-sdk/react/primitive"

import { agentPointer, makeAgentPointer, type AgentPointerOptions } from "@/components/keyframery/core/agent-pointer-core"

export type { AgentPointerController, AgentPointerOptions } from "@/components/keyframery/core/agent-pointer-core"

/** Connect an agent bridge to a pointer. Construct one per mounted view. */
export function createAgentPointer(options?: AgentPointerOptions) {
  return makeAgentPointer(elementOf, options)
}

export const {
  Root: AgentPointerRoot,
  Status: AgentPointerStatus,
  Announcement: AgentPointerAnnouncement,
  Overlay: AgentPointerOverlay,
  Cursor: AgentPointerCursor,
  Highlight: AgentPointerHighlight,
  Panel: AgentPointerPanel,
  Preview: AgentPointerPreview,
  TakeOver: AgentPointerTakeOver,
} = createParts(agentPointer, {
  root: "div", status: "span", announcement: "span", overlay: "div", cursor: "div",
  highlight: "span", panel: "div", preview: "span", takeOver: "button",
})

export const agentPointerMotion = {
  overlay: "group/pointer pointer-events-none fixed! inset-0! m-0! size-full! max-h-none! max-w-none! overflow-visible! border-0 bg-transparent p-0 text-inherit",
  cursor: "pointer-events-none fixed left-0 top-0 translate-x-(--kf-pointer-x) translate-y-(--kf-pointer-y) transition-[translate] duration-[calc(500ms*var(--kf-speed,1))] ease-house motion-reduce:hidden motion-reduce:transition-none",
  ring: "fixed left-(--kf-pointer-left) top-(--kf-pointer-top) h-(--kf-pointer-height) w-(--kf-pointer-width) opacity-0 group-data-[phase=changed]/pointer:animate-[kf-pointer-change_calc(380ms*var(--kf-speed,1))_var(--ease-house)_both] group-data-[phase=press]/pointer:opacity-100 group-data-[phase=approval]/pointer:opacity-100 motion-reduce:opacity-100 motion-reduce:animate-none",
  ripple: "absolute start-0 top-0 -translate-x-1/2 -translate-y-1/2 opacity-0 group-data-[phase=press]/pointer:animate-[kf-pointer-press_calc(290ms*var(--kf-speed,1))_var(--ease-house)_both] motion-reduce:animate-none",
  preview: "fixed left-(--kf-pointer-preview-x) top-(--kf-pointer-preview-y) inline-flex h-7 max-w-(--kf-pointer-preview-width) items-center overflow-hidden whitespace-nowrap",
  reveal: "block w-max max-w-full truncate animate-[kf-pointer-type_calc(360ms*var(--kf-speed,1))_steps(14,end)_both] motion-reduce:animate-none",
  panel: "pointer-events-none fixed left-(--kf-pointer-panel-x) top-(--kf-pointer-panel-y) w-[min(344px,calc(100vw-24px))] group-data-above/pointer:-translate-y-full",
}

export const agentPointerKeyframes = [
  "@starting-style{[data-slot=agent-pointer-cursor]{translate:var(--kf-pointer-start-x) var(--kf-pointer-start-y)}}",
  "@keyframes kf-pointer-press{0%{scale:0.55;opacity:0.88}100%{scale:calc(1.3 + 0.75*var(--kf-flourish,1));opacity:0}}",
  "@keyframes kf-pointer-change{0%{opacity:0.45}30%{opacity:1}100%{opacity:0.65}}",
  "@keyframes kf-pointer-type{from{clip-path:inset(0 100% 0 0)}to{clip-path:inset(0)}}",
].join("")
```

**components/keyframery/core/agent-pointer-core.ts**

```ts
import { definePrimitive } from "@ui-sdk/core"
import { observe, type ObservedChange } from "@ui-sdk/core/observe"
import type { AgentAction, AgentStep, createAgent } from "@ui-sdk/core/agent"

import type { Allow, ApprovalRequest, Approvals } from "@/components/keyframery/core/approval-core"
import { defaultTarget, matchesAction, matchesStepAction, plannedRef, previewPosition, privateValue, revealProbe, scrollToTarget, visible } from "@/components/keyframery/core/agent-pointer-target-core"

type Bridge = ReturnType<typeof createAgent>
type RunInput = Parameters<Bridge["act"]>[0]
type RunResult = Awaited<ReturnType<Bridge["act"]>>
type Phase = "idle" | "travel" | "preview" | "press" | "approval" | "changed" | "working" | "done" | "failed" | "denied" | "taken-over"

export type AgentPointerOptions = {
  /** Resolve the control inside a component. Returning undefined uses UI SDK's anchor and ARIA ownership. */
  resolveTarget?: (action: AgentAction) => Element | undefined
  /** Opt in to a visual preview of a non-secret setValue step. */
  previewValue?: (action: AgentAction) => string | undefined
}

type Frame = { x: number; y: number; startX: number; startY: number; left: number; top: number; width: number; height: number; flip: boolean }
type PanelPosition = { x: number; y: number; above: boolean }
type PointerState = {
  phase: Phase
  message: string
  announcement: string
  active: boolean
  canTakeOver: boolean
  held: boolean
  frame: Frame | null
  panel: PanelPosition | null
  layer: Element | null
  reduced: boolean
  preview: string
  previewAt: ReturnType<typeof previewPosition>
  request: ApprovalRequest | undefined
}

const idle: PointerState = {
  phase: "idle", message: "", announcement: "", active: false, canTakeOver: false, held: false,
  frame: null, panel: null, layer: null, reduced: false, preview: "", previewAt: null, request: undefined,
}

export type AgentPointerController = {
  wrapAllow(options?: { authorize?: Allow; approvals?: Approvals }): Allow
  run(bridge: Pick<Bridge, "act" | "snapshot" | "subscribe">, input: RunInput): Promise<RunResult>
  /** Keep the controls available across tool calls within one model turn. */
  session<T>(work: () => T | Promise<T>): Promise<T>
  takeOver(): void
  /** Give the agent permission to run again after Take over. */
  resume(): void
  reset(): void
  /** Mount the controller and abort its work when the view unmounts. */
  attach(element: HTMLElement, listener: (state: PointerState) => void, label?: () => string): () => void
}

const activeDocuments = new WeakMap<Document, AbortController>()
const takeoverError = "The person took over. Stop acting and ask them before continuing."
const takeoverMessage = "You took over. Changes so far are kept."
const deniedMessage = "You said no. Earlier changes are kept."
const takeOverGrace = 4000
const feedbackDelay = 380

type Outcome = { phase: "done" | "failed" | "denied"; message: string }

function stepWords(action: string, label = "", component = "", setting?: unknown): [string, string] {
  const choices = ["select", "native-select", "combobox", "listbox", "radio-group", "autocomplete"]
  switch (action) {
    case "press": case "click": return ["Pressing", "press"]
    case "submit": return ["Submitting", "submit"]
    case "setChecked": return setting === false ? ["Turning off", "turn off"] : ["Turning on", "turn on"]
    case "setValue":
      if (label.toLowerCase() === "plan" || choices.includes(component)) return ["Choosing", "choose"]
      if (["input", "textarea"].includes(component)) return ["Entering", "enter"]
      return ["Updating", "update"]
    case "open": case "setOpen": case "reveal": return setting === false ? ["Closing", "close"] : ["Opening", "open"]
    case "close": return ["Closing", "close"]
    case "reset": return ["Resetting", "reset"]
    default: return ["Working on", "complete the step for"]
  }
}

const stepLabel = (label: string | undefined, verb: string) =>
  label && label.toLowerCase() === "plan" && ["Choosing", "choose"].includes(verb) ? "a plan" : label || "this control"

function stepMessage(action: AgentAction) {
  const [verb] = stepWords(action.action, action.label, action.component, action.args[0])
  return `${verb} ${stepLabel(action.label, verb)}`
}

function failure(message: string): RunResult {
  return { ok: false, appeared: [], values: {}, steps: [], error: { step: 0, message } }
}

/** Wait for a feedback beat or approval. Cancel the wait immediately when the step ends. */
function abortable<T>(signal: AbortSignal, work: () => T | Promise<T>, cancelled: T): Promise<T> {
  if (signal.aborted) return Promise.resolve(cancelled)
  return new Promise<T>((resolve, reject) => {
    const abort = () => resolve(cancelled)
    signal.addEventListener("abort", abort, { once: true })
    Promise.resolve().then(() => signal.aborted ? cancelled : work()).then(resolve, reject)
      .finally(() => signal.removeEventListener("abort", abort))
  })
}

function beat(ms: number, signal: AbortSignal) {
  if (!ms || signal.aborted) return Promise.resolve()
  return new Promise<void>((resolve) => {
    const finish = () => {
      clearTimeout(timer)
      signal.removeEventListener("abort", finish)
      resolve()
    }
    const timer = setTimeout(finish, ms)
    signal.addEventListener("abort", finish, { once: true })
  })
}

/* Native WebMCP has no call-level lifecycle in beta.17. Present its visible interactions. */
function externalMutation(action: AgentAction) {
  return ["press", "submit", "reset", "setChecked"].includes(action.action) ||
    (action.action === "setValue" && ["input", "textarea", "select", "native-select"].includes(action.component))
}

export function makeAgentPointer(elementOf: (ref: string) => HTMLElement | undefined | null, options: AgentPointerOptions = {}): AgentPointerController {
  let state = idle
  let root: HTMLElement | undefined
  let label = () => "Claude"
  let measure: (() => void) | undefined
  let watched: { action: AgentAction; changedAt: number } | undefined
  let sessions = 0
  let outcome: Outcome | undefined
  let settlement: ReturnType<typeof setTimeout> | undefined
  let grace: ReturnType<typeof setTimeout> | undefined
  let stepNotice: ReturnType<typeof setTimeout> | undefined
  let lastStepNotice = -Infinity
  type Gate = { action: AgentAction; index: number; opened: boolean; approved: boolean; held: unknown }
  type Run = {
    abort: AbortController
    steps: { step: AgentStep; ref: string | undefined }[]
    consumed: Set<number>
    values: Map<string, unknown>
    gate?: Gate
    declined?: boolean
  }
  let run: Run | undefined
  let external: { release: () => void; settle: () => void; settling: boolean } | undefined
  const listeners = new Set<(state: PointerState) => void>()

  function update(patch: Partial<PointerState>) {
    state = { ...state, ...patch }
    listeners.forEach((listener) => listener(state))
  }

  function clearTarget() {
    measure?.()
    measure = undefined
    watched = undefined
    clearTimeout(stepNotice)
  }

  function modal(doc = root?.ownerDocument) {
    return doc ? [...doc.querySelectorAll("dialog:modal")].at(-1) ?? null : null
  }

  function hiddenMutation({ target }: MutationRecord) {
    return (target instanceof Element ? target : target.parentElement)?.closest("[data-agent-pointer-chrome]")
  }

  function attach(element: HTMLElement, listener: (state: PointerState) => void, name = () => "Claude") {
    root = element
    label = name
    listeners.add(listener)
    listener(state)
    const doc = element.ownerDocument
    const layers = new doc.defaultView!.MutationObserver((records) => {
      if (watched || (!state.canTakeOver && !state.held) || records.every(hiddenMutation)) return
      const layer = modal(doc)
      if (layer !== state.layer) update({ layer })
    })
    layers.observe(doc.body, { subtree: true, childList: true, attributes: true, attributeFilter: ["open"] })
    return () => {
      layers.disconnect()
      listeners.delete(listener)
      if (root !== element) return
      root = undefined
      run?.abort.abort()
      external?.release()
      clearTarget()
      clearTimeout(settlement)
      clearTimeout(grace)
      outcome = undefined
      state = state.held ? { ...idle, held: true, phase: "taken-over", message: takeoverMessage } : idle
    }
  }

  function anchorOf(action: AgentAction) {
    try { return elementOf(action.ref) } catch { return undefined }
  }

  function track(action: AgentAction, doc: Document) {
    const win = doc.defaultView!
    const scope = root?.closest<HTMLElement>("[data-agent-pointer-scope]") ?? null
    const start = root?.getBoundingClientRect()
    const startX = state.frame?.x ?? (start ? Math.max(16, Math.min(start.left + 12, win.innerWidth - 24)) : 16)
    const startY = state.frame?.y ?? (start ? Math.max(16, Math.min(start.top + 10, win.innerHeight - 24)) : 16)
    const media = win.matchMedia("(prefers-reduced-motion: reduce)")
    let target: Element | undefined
    const sizes = new win.ResizeObserver(() => refresh())
    function refresh(scroll = false) {
      const custom = options.resolveTarget?.(action)
      const next = visible(custom, doc) ? custom : defaultTarget(action, anchorOf(action), doc)
      if (next !== target) {
        sizes.disconnect()
        if (next) sizes.observe(next)
        target = next
      }
      if (scroll && next) scrollToTarget(next, scope)
      const rect = next?.getBoundingClientRect()
      const frame = rect && rect.right > 0 && rect.bottom > 0 && rect.left < win.innerWidth && rect.top < win.innerHeight
        ? {
            startX, startY,
            x: Math.max(12, Math.min(rect.left + Math.min(rect.width / 2, 18), win.innerWidth - 12)),
            y: Math.max(12, Math.min(rect.top + rect.height / 2, win.innerHeight - 12)),
            left: Math.max(0, rect.left), top: Math.max(0, rect.top),
            width: Math.min(rect.right, win.innerWidth) - Math.max(0, rect.left),
            height: Math.min(rect.bottom, win.innerHeight) - Math.max(0, rect.top),
            flip: rect.left > win.innerWidth - 165,
          } : null
      const layer = next?.closest("dialog:modal") ?? modal(doc)
      const anchor = frame ? layer?.getBoundingClientRect() ?? rect : undefined
      const panelWidth = Math.min(344, win.innerWidth - 24)
      const panelTop = (anchor?.bottom ?? 0) + (layer ? 12 : 34)
      const belowSpace = win.innerHeight - panelTop - 12
      const aboveSpace = (anchor?.top ?? 0) - 24
      const cardSpace = 212
      const above = belowSpace < cardSpace && aboveSpace > belowSpace
      const panel = anchor && (!layer || Math.max(aboveSpace, belowSpace) >= cardSpace) ? {
        x: Math.max(12, Math.min(layer ? anchor.left + (anchor.width - panelWidth) / 2 : anchor.left, win.innerWidth - panelWidth - 12)),
        y: above ? anchor.top - 12 : panelTop,
        above,
      } : null
      const safePreview = next && !privateValue(action, anchorOf(action), next) ? state.preview : ""
      const previewAt = frame && next && safePreview ? previewPosition(next) : null
      if (JSON.stringify(frame) !== JSON.stringify(state.frame) || JSON.stringify(panel) !== JSON.stringify(state.panel) || layer !== state.layer ||
          state.reduced !== media.matches || safePreview !== state.preview || JSON.stringify(previewAt) !== JSON.stringify(state.previewAt)) {
        update({ frame, panel, layer, reduced: media.matches, preview: safePreview, previewAt })
      }
      return frame ? next : undefined
    }
    const onGeometry = () => refresh()
    const mutations = new win.MutationObserver((records) => {
      if (records.some((record) => !hiddenMutation(record))) refresh()
    })
    mutations.observe(doc.body, { subtree: true, childList: true, attributes: true, attributeFilter: ["class", "style", "open", "inert", "hidden", "aria-hidden", "aria-controls", "aria-owns", "data-agent-secret", "type", "autocomplete"] })
    doc.addEventListener("scroll", onGeometry, true)
    win.addEventListener("resize", onGeometry)
    media.addEventListener("change", onGeometry)
    measure = () => {
      sizes.disconnect()
      mutations.disconnect()
      doc.removeEventListener("scroll", onGeometry, true)
      win.removeEventListener("resize", onGeometry)
      media.removeEventListener("change", onGeometry)
    }
    return refresh
  }

  function speed() {
    if (state.reduced || !root) return 0
    const multiplier = Number.parseFloat(root.ownerDocument.defaultView!.getComputedStyle(root).getPropertyValue("--kf-speed"))
    return Number.isFinite(multiplier) ? Math.max(0, multiplier) : 1
  }

  function highlight(change: ObservedChange) {
    if (change.key === "value") run?.values.set(change.ref, change.value)
    if (change.source !== "agent" || run?.abort.signal.aborted) return
    const gate = run?.gate
    if (gate?.action.ref === change.ref) {
      // listItems opens and closes a popup between the original and converted gate calls.
      if (gate.action.action === "setValue" && change.key === "open") {
        if (change.value === true) gate.opened = true
        return
      }
      gate.opened = false
    }
    if (change.ref !== watched?.action.ref) return
    watched.changedAt = Date.now()
    update({ phase: "changed", preview: "", previewAt: null })
  }

  function externalLease(doc: Document, signal: AbortSignal) {
    const abort = new AbortController()
    const stop = observe(highlight)
    const lease = {
      signal: abort.signal,
      settling: false,
      release() {
        if (external !== lease) return
        external = undefined
        abort.abort()
        stop()
        signal.removeEventListener("abort", lease.release)
        if (activeDocuments.get(doc) === abort) activeDocuments.delete(doc)
        clearTarget()
        if (root) update(idle)
      },
      settle() {
        lease.settling = true
        void beat(450 * speed(), abort.signal).then(lease.release)
      },
    }
    activeDocuments.set(doc, abort)
    external = lease
    signal.addEventListener("abort", lease.release, { once: true })
    return lease
  }

  function wrapAllow({ authorize, approvals }: { authorize?: Allow; approvals?: Approvals } = {}): Allow {
    return async (action, context) => {
      const bridgeSignal = context.signal
      if (state.held) throw new Error(takeoverError)
      if (bridgeSignal.aborted || run?.abort.signal.aborted) return false
      if (authorize && !await abortable(bridgeSignal, () => authorize(action, context), false)) {
        if (!bridgeSignal.aborted && action.confirm !== undefined) throw new Error(`The app refused ${action.action} on ${action.ref}.`)
        return false
      }
      if (state.held) throw new Error(takeoverError)
      if (run?.abort.signal.aborted || bridgeSignal.aborted) return false

      const doc = root?.ownerDocument
      const anchor = anchorOf(action)
      // A dialog can request the same press to reveal its contents, then request it again with
      // the button's confirm marker. Let the reveal happen without showing an arrival.
      const probingDialog = ["dialog", "alert-dialog"].includes(action.component) && action.action === "press" &&
        typeof action.args[0] === "string" && action.confirm === undefined && anchor?.getAttribute("aria-expanded") === "false"
      const plan = run
      const previous = plan?.gate
      const continuation = previous?.opened && previous.action.ref === action.ref && previous.action.action === action.action &&
        // A selection already held can finish after the first ask without emitting a value change.
        JSON.stringify(previous.action.args[0]) !== JSON.stringify(previous.held) &&
        (previous.action.confirm !== action.confirm || JSON.stringify(previous.action.args) !== JSON.stringify(action.args))
      let index = -1
      if (plan && !probingDialog) {
        const available = ({ step }: typeof plan.steps[number], i: number) => !plan.consumed.has(i) &&
          typeof step?.ref === "string" && matchesStepAction(step.action, action.action)
        index = continuation ? previous.index : plan.steps.findIndex((item, i) => available(item, i) && item.ref === action.ref)
        if (!continuation && index < 0) {
          index = plan.steps.findIndex((item, i) => available(item, i) && matchesAction(action, item.step.ref.split(">").at(-1)!))
        }
      }
      const marked = action.confirm !== undefined
      const mutation = !probingDialog && (index >= 0 || !!plan && !revealProbe(action))
      if (external?.settling) external.release()
      const native = doc && !run && !activeDocuments.has(doc) && !probingDialog && (marked || externalMutation(action))
        ? externalLease(doc, bridgeSignal) : undefined
      const signal = native?.signal ?? bridgeSignal
      const present = !!doc && (!!native || mutation || marked)
      const message = stepMessage(action)
      const approved = !!continuation && previous.approved && previous.action.confirm === action.confirm
      if (plan && (mutation || marked)) {
        if (index >= 0) plan.consumed.add(index)
        plan.gate = { action, index, opened: false, approved, held: plan.values.get(action.ref) }
      }

      if (present && !continuation) {
        if (watched?.changedAt) await beat(Math.max(0, 250 * speed() - (Date.now() - watched.changedAt)), signal)
        if (signal.aborted || run?.abort.signal.aborted) return false
        clearTarget()
        update({ active: true, phase: "travel", preview: "", previewAt: null, request: undefined, message })
      }

      try {
        if (present && continuation) {
          clearTarget()
          update({ phase: "working", message })
        }
        const refresh = present ? track(action, doc) : undefined
        if (present) watched = { action, changedAt: 0 }
        let target = refresh?.(!continuation)
        if (present && !continuation) {
          if (!target) update({ phase: "working", message: `${message}. No visible target.` })
          if (Date.now() - lastStepNotice >= 1200) {
            stepNotice = setTimeout(() => {
              lastStepNotice = Date.now()
              update({ announcement: message })
            }, 180)
          }
          if (target) {
            await beat(500 * speed(), signal)
            target = refresh?.()
            if (!target && !signal.aborted) update({ phase: "working", message: `${message}. No visible target.` })
          }
        }
        if (signal.aborted || run?.abort.signal.aborted) return false

        const sensitive = privateValue(action, anchor, target) || (action.action === "setValue" && !target && !anchor)
        // Mask the value while keeping the action distinct from a clear.
        const approvalAction = sensitive && action.action === "setValue" && action.args[0] !== undefined
          ? { ...action, args: ["••••"] }
          : action
        if (!approved && approvals && (present || !doc)) {
          const before = new Set(approvals.pending().map((request) => request.id))
          let requested = false
          const stop = approvals.subscribe(() => {
            const request = approvals.pending().find((item) => item.step === approvalAction && !before.has(item.id))
            if (!request) return
            if (requested) return
            requested = true
            clearTimeout(stepNotice)
            const message = `Needs your OK: ${action.confirm || stepLabel(action.label, "")}`
            if (present) update({ phase: "approval", request, message, announcement: message })
          })
          try {
            if (!await abortable(signal, () => approvals.allow(approvalAction, { signal }), false)) {
              if (requested && !signal.aborted && !plan?.abort.signal.aborted) {
                if (plan) plan.declined = true
                else if (present) update({ phase: "denied", message: deniedMessage, announcement: deniedMessage })
              }
              return false
            }
            if (requested && plan?.gate?.action === action) plan.gate.approved = true
          } finally {
            stop()
            if (present && state.request) update({ request: undefined, ...(state.phase === "approval" ? { phase: "working", message } : {}) })
          }
        } else if (!approvals && marked) {
          throw new Error("Needs a person: no approval handler is configured.")
        }

        target = refresh?.()
        if (present && target && action.action === "setValue" && !sensitive && !privateValue(action, anchorOf(action), target)) {
          const value = options.previewValue?.(action)
          const previewAt = value && !value.includes("[redacted]") ? previewPosition(target) : null
          if (value && previewAt) {
            update({ phase: "preview", preview: value, previewAt })
            await beat(370 * speed(), signal)
          }
        }
        if (signal.aborted || run?.abort.signal.aborted) return false
        if (present && (action.action === "press" || action.action === "submit")) {
          update({ phase: "press" })
          if (target) await beat(130 * speed(), signal)
        }
        return !signal.aborted && !run?.abort.signal.aborted
      } finally {
        native?.settle()
      }
    }
  }

  function announceOutcome(next: Outcome) {
    update({ ...next, announcement: next.message })
  }

  function settle() {
    if (!root || run || state.held || !outcome) return
    clearTimeout(settlement)
    const next = outcome
    if (next.phase === "denied") {
      announceOutcome(next)
    } else if (next.phase === "failed" || !sessions) {
      settlement = setTimeout(() => announceOutcome(next), feedbackDelay)
    }
    if (!sessions) {
      clearTimeout(grace)
      grace = setTimeout(() => {
        lastStepNotice = -Infinity
        update({ active: false, canTakeOver: false, layer: null })
      }, takeOverGrace)
    }
  }

  async function session<T>(work: () => T | Promise<T>): Promise<T> {
    if (!sessions) {
      outcome = undefined
      clearTimeout(grace)
      clearTimeout(settlement)
      lastStepNotice = -Infinity
      // Drop a previous turn's grace period if this turn hasn't acted yet.
      if (!run && !external && !state.held) update(idle)
    }
    sessions += 1
    try {
      return await work()
    } finally {
      sessions -= 1
      if (!sessions) settle()
    }
  }

  async function start(bridge: Pick<Bridge, "act" | "snapshot" | "subscribe">, input: RunInput): Promise<RunResult> {
    if (state.held) return failure(takeoverError)
    const doc = root?.ownerDocument ?? (typeof document === "undefined" ? undefined : document)
    if (!doc) return failure("Agent Pointer is available in the browser.")
    if (external?.settling) external.release()
    if (activeDocuments.has(doc)) return failure("An agent run is already active.")
    const steps = Array.isArray(input?.steps) ? input.steps : []
    const snapshot = steps.length ? bridge.snapshot() : []
    const abort = new AbortController()
    activeDocuments.set(doc, abort)
    const plan: Run = {
      abort,
      steps: steps.map((step) => ({ step, ref: plannedRef(step, snapshot) })),
      consumed: new Set(),
      values: new Map(snapshot.map(({ ref, value }) => [ref, value])),
    }
    run = plan
    clearTimeout(settlement)
    clearTimeout(grace)
    outcome = undefined
    if (root) update({
      ...idle, active: true, canTakeOver: true, phase: "working", layer: modal(doc),
      message: state.active && state.phase === "working" ? state.message : "Working…",
      announcement: state.active ? state.announcement : "",
    })
    const stop = bridge.subscribe(highlight)
    let result: RunResult
    try {
      result = await bridge.act(input, { signal: abort.signal })
      if (watched?.changedAt) await beat(Math.max(0, 300 * speed() - (Date.now() - watched.changedAt)), abort.signal)
    } catch (error) {
      result = failure(error instanceof Error ? error.message : "The step failed.")
    } finally {
      stop()
      clearTarget()
      run = undefined
      activeDocuments.delete(doc)
    }
    if (abort.signal.reason === takeoverError) return {
      ...result, ok: false, error: { step: result.error?.step ?? result.steps.length, message: takeoverError },
    }
    if (abort.signal.aborted) return result

    if (result.ok) {
      outcome = { phase: "done", message: "Done." }
    } else if (plan.declined) {
      outcome = { phase: "denied", message: deniedMessage }
    } else {
      const index = result.error?.step ?? -1
      const planned = plan.steps[index]
      const matched = snapshot.find(({ ref }) => ref === planned?.ref)
      const action = plan.gate?.index === index ? plan.gate.action : undefined
      const ref = typeof planned?.step?.ref === "string" ? planned.step.ref.split(">").at(-1)?.trim() : undefined
      const name = action?.label || matched?.label || (ref && !/^c\d+$/.test(ref) ? ref.slice(0, 80) : undefined)
      const [, verb] = stepWords(action?.action ?? planned?.step?.action ?? "", name, action?.component ?? matched?.component, planned?.step?.args?.[0])
      const detail = name ? `Couldn't ${verb} ${stepLabel(name, verb)}.` : "Couldn't complete that step."
      outcome = { phase: "failed", message: `${detail} ${label()} may try another way.` }
    }
    if (root) {
      update({ phase: "working", frame: null, panel: null, layer: modal(doc), preview: "", previewAt: null, request: undefined })
      settle()
    }
    return result
  }

  function takeOver() {
    if (state.held || (!run && !state.canTakeOver)) return
    const layer = modal()
    clearTimeout(settlement)
    clearTimeout(grace)
    outcome = undefined
    run?.abort.abort(takeoverError)
    external?.release()
    clearTarget()
    update({ ...idle, held: true, layer, phase: "taken-over", message: takeoverMessage, announcement: takeoverMessage })
  }

  function resume() {
    if (!state.held) return
    lastStepNotice = -Infinity
    update(idle)
  }

  function reset() {
    if (run || external || state.held) return
    clearTimeout(settlement)
    clearTimeout(grace)
    outcome = undefined
    lastStepNotice = -Infinity
    update(idle)
  }

  return { wrapAllow, run: start, session, takeOver, resume, reset, attach }
}

type PointerApi = { attach: (element: HTMLElement) => () => void; toggleControl: () => void }

type PointerOptions = {
  /** A controller created with createAgentPointer. */
  pointerController: AgentPointerController
  /** The name shown beside the pointer. */
  label?: string
}

function frameStyle({ frame, panel, previewAt }: PointerState) {
  const px = (value: number | undefined) => value === undefined ? "" : `${value}px`
  return {
    "--kf-pointer-x": px(frame?.x), "--kf-pointer-y": px(frame?.y),
    "--kf-pointer-start-x": px(frame?.startX), "--kf-pointer-start-y": px(frame?.startY),
    "--kf-pointer-left": px(frame?.left), "--kf-pointer-top": px(frame?.top),
    "--kf-pointer-width": px(frame?.width), "--kf-pointer-height": px(frame?.height),
    "--kf-pointer-panel-x": px(panel?.x), "--kf-pointer-panel-y": px(panel?.y),
    "--kf-pointer-preview-x": px(previewAt?.x), "--kf-pointer-preview-y": px(previewAt?.y),
    "--kf-pointer-preview-width": px(previewAt?.width),
  }
}

const personUi = { "data-agent-hidden": "", "data-agent-pointer-chrome": "" }

export const agentPointer = definePrimitive({
  name: "agent-pointer",
  options: { pointerController: "value", label: "string" },
  state: (options: PointerOptions) => ({ ...idle, label: options.label ?? "Claude" }),
  sync: (options) => ({ label: options.label ?? "Claude" }),
  api: (context): PointerApi => ({
    attach: (element: HTMLElement): (() => void) =>
      context.options().pointerController.attach(element, (next) => context.store.set(next), () => context.store.get().label),
    toggleControl: (): void => {
      const controller = context.options().pointerController
      if (context.store.get().held) controller.resume()
      else controller.takeOver()
    },
  }),
  slots: (slot) => ({
    root: slot<{}, PointerState>({
      state: (state) => state,
      attrs: (state) => ({ ...personUi, "data-phase": state.phase, "data-held": state.held ? "" : undefined }),
      bind: (el, part) => part.api.attach(el),
    }),
    status: slot<{}, { message: string }>({
      state: ({ message, label }) => ({ message: message || `${label} is ready.` }),
    }),
    announcement: slot({
      attrs: () => ({ ...personUi, role: "status", "aria-live": "polite", "aria-atomic": "true" }),
      bind: (el, part) => {
        let last = ""
        let timer: ReturnType<typeof setTimeout>
        const sync = () => {
          const next = part.store.get().announcement
          if (last === next) return
          last = next
          clearTimeout(timer)
          // Give assistive technology time to register a region newly mounted inside a modal.
          timer = setTimeout(() => { el.textContent = next }, 40)
        }
        sync()
        const stop = part.store.subscribe(sync)
        return () => {
          stop()
          clearTimeout(timer)
        }
      },
    }),
    overlay: slot<{}, PointerState>({
      state: (state) => state,
      attrs: (state) => ({
        ...personUi, popover: "manual", "data-phase": state.phase, "data-anchored": state.frame ? "" : undefined,
        "data-above": state.panel?.above ? "" : undefined,
        "data-flip": state.frame?.flip ? "" : undefined,
      }),
      bind: (el, part) => {
        const position = () => {
          for (const [key, value] of Object.entries(frameStyle(part.store.get()))) el.style.setProperty(key, value)
        }
        position()
        const stop = part.store.subscribe(position)
        el.showPopover?.()
        return () => {
          stop()
          if (el.matches(":popover-open")) el.hidePopover()
        }
      },
    }),
    cursor: slot<{}, { label: string; reduced: boolean }>({
      state: ({ label, reduced }) => ({ label, reduced }),
      attrs: () => ({ "aria-hidden": "true" }),
    }),
    highlight: slot({ attrs: () => ({ "aria-hidden": "true" }) }),
    panel: slot({ attrs: () => personUi }),
    preview: slot<{}, { preview: string }>({
      state: ({ preview }) => ({ preview }),
      attrs: () => ({ "aria-hidden": "true" }),
    }),
    takeOver: slot<{}, { text: string }>({
      role: "button",
      focus: { none: "The native button owns keyboard focus." },
      state: ({ held, label }) => ({ text: held ? `Let ${label} continue` : "Take over" }),
      press: (part) => part.api.toggleControl(),
      attrs: (state) => ({ ...personUi, type: "button", "aria-disabled": state.canTakeOver || state.held ? undefined : "true" }),
    }),
  }),
  // Even while mounted, this is the person's control surface.
  agent: { actions: [], shown: () => false },
})
```

**components/keyframery/core/agent-pointer-target-core.ts**

```ts
import type { AgentAction, AgentComponent, AgentStep } from "@ui-sdk/core/agent"

const ownership = "[aria-controls], [aria-owns]"

/** A popup can live outside its trigger's subtree. Follow both ARIA ownership attributes. */
export function ownedRegions(root: HTMLElement, accepts: (region: HTMLElement) => boolean = () => true) {
  const regions = new Set([root])
  for (const region of regions) {
    const controls = [...region.querySelectorAll<HTMLElement>(ownership)]
    if (region.matches(ownership)) controls.unshift(region)
    for (const control of controls) {
      const ids = [control.getAttribute("aria-controls"), control.getAttribute("aria-owns")].join(" ").trim().split(/\s+/)
      for (const id of ids) {
        const target = id && root.ownerDocument.getElementById(id)
        if (target && !target.contains(root) && accepts(target)) regions.add(target)
      }
    }
    if (regions.size > 100) break
  }
  return regions
}

const normalize = (text: string) => text.normalize("NFD").replace(/\p{M}/gu, "").trim().replace(/\s+/g, " ").toLowerCase()

export function matchesAction(action: AgentAction, ref: string) {
  if (ref === action.ref) return true
  const name = ` ${normalize(action.label ?? "")} `
  return name.includes(` ${normalize(ref)} `)
}

const words = (text: string) => ` ${normalize(text.replace(/[ßẞ]/g, "ss")).replace(/[^\p{L}\p{N}]+/gu, " ").trim()} `

export function matchesStepAction(step: string, action: string) {
  return step === action || (action === "press" && ["click", "setValue"].includes(step)) ||
    (["press", "click", "reveal", "open", "setValue"].includes(step) && ["open", "setValue"].includes(action))
}

/** Resolve only unambiguous names. A later step can refer to a component that has yet to mount. */
export function plannedRef(step: AgentStep, snapshot: AgentComponent[]) {
  if (typeof step?.ref !== "string") return
  const raw = step.ref
  if (snapshot.some(({ ref }) => ref === raw)) return raw
  const parts = raw.split(">").map((part) => part.trim())
  const name = parts.pop()!
  const needle = words(name)
  if (!needle.trim()) return
  const candidates = snapshot.filter((entry) => entry.component !== "more" && !entry.offPage &&
    (!parts.length || parts.every((part) => words(entry.section ?? "").includes(words(part)))))
  const named = candidates.filter(({ label, row }) => words(`${label ?? ""} ${row ?? ""}`).includes(needle))
  const found = named.length ? named : candidates.filter(({ items, component }) =>
    (matchesStepAction(step.action, "open") && items?.some((item) => normalize(item.label) === normalize(name))) ||
    component === name || component.endsWith(`-${name}`))
  if (found.length === 1) return found[0].ref
  const able = found.filter(({ actions }) => actions.some((action) => matchesStepAction(step.action, action)))
  if (able.length === 1) return able[0].ref
}

/** beta.17 visits closed regions with these gates before it reaches the requested control. */
export function revealProbe({ action, component, args }: AgentAction) {
  return (action === "setOpen" && component === "collapsible" && args[0] === true) ||
    (action === "setPage" && component === "pagination") ||
    (action === "open" && component === "accordion") ||
    (action === "setValue" && ["accordion", "tabs", "navigation-menu"].includes(component))
}

export function visible(element: Element | undefined, doc: Document): element is Element {
  if (!element?.isConnected || element.ownerDocument !== doc || element.closest("[inert], [hidden], [aria-hidden=true]")) return false
  const modals = [...doc.querySelectorAll("dialog:modal")]
  if (modals.length && !modals.some((modal) => modal.contains(element))) return false
  const { width, height } = element.getBoundingClientRect()
  return width > 0 && height > 0 && (element.checkVisibility?.({ visibilityProperty: true }) ?? true)
}

export function defaultTarget(action: AgentAction, anchor: HTMLElement | null | undefined, doc: Document) {
  if (anchor && action.action === "press" && typeof action.args[0] === "string") {
    const name = normalize(action.args[0])
    for (const region of ownedRegions(anchor)) {
      const buttons = [...region.querySelectorAll('button, [role="button"], input[type="button"], input[type="submit"]')]
      if (region.matches('button, [role="button"]')) buttons.unshift(region)
      const button = buttons.find((el) => {
        const labels = el.getAttribute("aria-labelledby")?.split(/\s+/).map((id) => doc.getElementById(id)?.textContent).join(" ")
        const text = labels || el.getAttribute("aria-label") || el.textContent || el.getAttribute("value") || ""
        return normalize(text) === name && !el.closest("[data-agent-hidden]") && visible(el, doc)
      })
      if (button) return button
    }
  }
  return visible(anchor ?? undefined, doc) ? anchor ?? undefined : undefined
}

const controls = 'button, input, select, textarea, a[href], summary, [tabindex], [contenteditable], [role="button"], [role="checkbox"], [role="switch"], [role="radio"], [role="combobox"], [role="option"], [role="tab"], [role="slider"], [role^="menuitem"]'

/** Fit the preview in free space around the target, including its label and focus clearance. */
export function previewPosition(target: Element) {
  const doc = target.ownerDocument
  const { innerWidth, innerHeight } = doc.defaultView!
  const rect = target.getBoundingClientRect()
  const occupied = [...doc.querySelectorAll(controls)]
    .filter((el) => !el.closest("[data-agent-hidden], [hidden], [aria-hidden=true]") && visible(el, doc))
    .map((el) => el.getBoundingClientRect())
  occupied.push(rect)
  const height = 28
  const gap = 8
  const availableWidth = Math.min(240, innerWidth * 0.6)
  const clamp = (value: number, max: number) => Math.max(gap, Math.min(value, max - gap))
  for (const width of [availableWidth, Math.min(112, availableWidth)]) {
    const x = clamp(rect.left, innerWidth - width)
    const middle = clamp(rect.top + (rect.height - height) / 2, innerHeight - height)
    const row = (top: number) => {
      const edges = occupied
        .filter((box) => top < box.bottom + gap && top + height > box.top - gap)
        .flatMap((box) => [box.left - width - gap, box.right + gap])
        .filter((left) => left <= rect.right && left + width >= rect.left)
        .sort((a, b) => Math.abs(a - x) - Math.abs(b - x))
      return [x, ...edges].map((left) => [left, top])
    }
    const candidates = [
      ...row(rect.top - height - gap),
      [rect.right + gap, middle],
      [rect.left - width - gap, middle],
      ...row(rect.bottom + gap),
    ]
    for (const [left, top] of candidates) {
      if (left < gap || top < gap || left + width > innerWidth - gap || top + height > innerHeight - gap) continue
      if (occupied.some((box) => left < box.right + 4 && left + width > box.left - 4 &&
        top < box.bottom + 4 && top + height > box.top - 4)) continue
      return { x: left, y: top, width }
    }
  }
  return null
}

const secret = '[data-agent-secret], input[type="password"], input[autocomplete~="current-password"], input[autocomplete~="new-password"], input[autocomplete~="one-time-code"], input[autocomplete~="cc-number"], input[autocomplete~="cc-csc"]'
function redacted(value: unknown, seen = new Set<object>()): boolean {
  if (typeof value === "string") return value.includes("[redacted]")
  if (!value || typeof value !== "object" || seen.has(value)) return false
  seen.add(value)
  return Object.values(value).some((item) => redacted(item, seen))
}

export function privateValue(action: AgentAction, anchor?: Element | null, target?: Element) {
  return redacted(action.args) || [anchor, target].some((el) => !!(el?.closest(secret) || el?.querySelector(secret)))
}

/** Scroll just the target's clipping ancestors, up to the supplied scope or the viewport. */
export function scrollToTarget(target: Element, scope: HTMLElement | null) {
  const win = target.ownerDocument.defaultView
  if (!win) return
  const boundary = scope?.contains(target) ? scope : target.closest("dialog:modal")
  for (let parent = target.parentElement; parent; parent = parent.parentElement) {
    const css = win.getComputedStyle(parent)
    if (/(auto|scroll)/.test(css.overflow + css.overflowX + css.overflowY)) {
      const rect = target.getBoundingClientRect()
      const frame = parent.getBoundingClientRect()
      const top = rect.top < frame.top + 8 || rect.bottom > frame.bottom - 8
        ? rect.top - frame.top - (parent.clientHeight - rect.height) / 2 : 0
      const left = rect.left < frame.left + 8 || rect.right > frame.right - 8
        ? rect.left - frame.left - (parent.clientWidth - rect.width) / 2 : 0
      if (top || left) parent.scrollBy({ top, left, behavior: "instant" })
    }
    if (parent === boundary) break
  }
  const rect = target.getBoundingClientRect()
  if (rect.bottom > win.innerHeight - 12 || rect.top < 12) {
    win.scrollBy({ top: rect.top - (win.innerHeight - rect.height) / 2, behavior: "instant" })
  }
}
```

**Check the import paths**

The files import from `@/components/keyframery/…` and `@/lib/…`. Change those if your project's aliases differ.

**Vue**

```bash
npx shadcn-vue@latest add https://keyframery.com/r/vue/agent-pointer.json https://keyframery.com/r/vue/input.json https://keyframery.com/r/vue/form.json https://keyframery.com/r/vue/select.json
```

This adds `components/keyframery/agent-pointer/` (one file per part, with the same part names as React) to your Vue or Nuxt project, installs UI SDK for Vue and adds the motion tokens to your global CSS. The install command also adds [input](/docs/components/input), [form](/docs/components/form), [select](/docs/components/select) for the preview and examples. See [Install for Vue](/docs/installation/vue).

## Usage [#usage]

**React**

```tsx
"use client"

import { createAgent } from "@ui-sdk/react/agent"
import * as React from "react"

import { AgentPointer, createAgentPointer } from "@/components/keyframery/agent-pointer"
import { Button } from "@/components/keyframery/button"
import { Input } from "@/components/keyframery/input"

export default function Usage() {
  const [pointer] = React.useState(createAgentPointer)
  const [agent] = React.useState(() => typeof window === "undefined" ? undefined : createAgent({
    allow: pointer.wrapAllow({ authorize: (step) => step.label === "Booking name" && step.action === "setValue" }),
  }))
  return (
    <div className="flex w-full max-w-sm flex-col gap-3">
      <Input aria-label="Booking name" />
      <Button data-agent-hidden onClick={() => agent && pointer.run(agent, {
        steps: [{ ref: "Booking name", action: "setValue", args: ["Maya Okafor"] }],
      })}>Enter booking name</Button>
      <AgentPointer controller={pointer} label="Claude" />
    </div>
  )
}
```

**Vue**

```vue
<script setup lang="ts">
import { createAgent } from "@ui-sdk/vue/agent"

import { AgentPointer, createAgentPointer } from "@/components/keyframery/agent-pointer"
import { Button } from "@/components/keyframery/button"
import { Input } from "@/components/keyframery/input"

const pointer = createAgentPointer()
const agent = typeof window === "undefined" ? undefined : createAgent({
  allow: pointer.wrapAllow({ authorize: (step) => step.label === "Booking name" && step.action === "setValue" }),
})

function run() {
  if (agent) return pointer.run(agent, { steps: [{ ref: "Booking name", action: "setValue", args: ["Maya Okafor"] }] })
}
</script>

<template>
  <div class="flex w-full max-w-sm flex-col gap-3">
    <Input aria-label="Booking name" />
    <Button data-agent-hidden="true" @click="run">Enter booking name</Button>
    <AgentPointer :controller="pointer" label="Claude" />
  </div>
</template>
```

## Examples [#examples]

### Basic [#basic]

A planned step sets a value through the bridge. Values are hidden from the cursor by default.

<ExamplePreview name="agent-pointer/basic">
**React**

  ```tsx
  "use client"

  import { createAgent } from "@ui-sdk/react/agent"
  import * as React from "react"

  import { AgentPointer, createAgentPointer } from "@/components/keyframery/agent-pointer"
  import { Button } from "@/components/keyframery/button"
  import { Input } from "@/components/keyframery/input"

  export default function Usage() {
    const [pointer] = React.useState(createAgentPointer)
    const [agent] = React.useState(() => typeof window === "undefined" ? undefined : createAgent({
      allow: pointer.wrapAllow({ authorize: (step) => step.label === "Booking name" && step.action === "setValue" }),
    }))
    return (
      <div className="flex w-full max-w-sm flex-col gap-3">
        <Input aria-label="Booking name" />
        <Button data-agent-hidden onClick={() => agent && pointer.run(agent, {
          steps: [{ ref: "Booking name", action: "setValue", args: ["Maya Okafor"] }],
        })}>Enter booking name</Button>
        <AgentPointer controller={pointer} label="Claude" />
      </div>
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { createAgent } from "@ui-sdk/vue/agent"

  import { AgentPointer, createAgentPointer } from "@/components/keyframery/agent-pointer"
  import { Button } from "@/components/keyframery/button"
  import { Input } from "@/components/keyframery/input"

  const pointer = createAgentPointer()
  const agent = typeof window === "undefined" ? undefined : createAgent({
    allow: pointer.wrapAllow({ authorize: (step) => step.label === "Booking name" && step.action === "setValue" }),
  })

  function run() {
    if (agent) return pointer.run(agent, { steps: [{ ref: "Booking name", action: "setValue", args: ["Maya Okafor"] }] })
  }
  </script>

  <template>
    <div class="flex w-full max-w-sm flex-col gap-3">
      <Input aria-label="Booking name" />
      <Button data-agent-hidden="true" @click="run">Enter booking name</Button>
      <AgentPointer :controller="pointer" label="Claude" />
    </div>
  </template>
  ```
</ExamplePreview>

### With approvals [#with-approvals]

The human decision runs once in the bridge. Approving the marked action archives the draft.

<ExamplePreview name="agent-pointer/approvals">
**React**

  ```tsx
  "use client"

  import { createAgent } from "@ui-sdk/react/agent"
  import * as React from "react"

  import { AgentPointer, createAgentPointer } from "@/components/keyframery/agent-pointer"
  import { createApprovals } from "@/components/keyframery/approval"
  import { Button } from "@/components/keyframery/button"

  export default function WithApprovals() {
    const [archived, setArchived] = React.useState(false)
    const [pointer] = React.useState(createAgentPointer)
    const [agent] = React.useState(() => typeof window === "undefined" ? undefined : createAgent({
      allow: pointer.wrapAllow({
        authorize: (step) => step.label === "Archive draft" && step.action === "press",
        approvals: createApprovals({ keep: 0 }),
      }),
    }))

    return (
      <div className="flex w-full max-w-sm flex-col items-start gap-3">
        <Button aria-label="Archive draft" data-agent-confirm="Archive the unsent draft" onClick={() => setArchived(true)}>
          Archive draft
        </Button>
        <Button data-agent-hidden onClick={() => agent && pointer.run(agent, {
          steps: [{ ref: "Archive draft", action: "press" }],
        })}>Ask Claude</Button>
        <span role="status" className="text-[12px] text-muted-foreground">{archived ? "Draft archived" : "Unsent draft"}</span>
        <AgentPointer controller={pointer} />
      </div>
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { createAgent } from "@ui-sdk/vue/agent"
  import { ref } from "vue"

  import { AgentPointer, createAgentPointer } from "@/components/keyframery/agent-pointer"
  import { createApprovals } from "@/components/keyframery/approval"
  import { Button } from "@/components/keyframery/button"

  const archived = ref(false)
  const pointer = createAgentPointer()
  const agent = typeof window === "undefined" ? undefined : createAgent({
    allow: pointer.wrapAllow({
      authorize: (step) => step.label === "Archive draft" && step.action === "press",
      approvals: createApprovals({ keep: 0 }),
    }),
  })

  function run() {
    if (agent) return pointer.run(agent, { steps: [{ ref: "Archive draft", action: "press" }] })
  }
  </script>

  <template>
    <div class="flex w-full max-w-sm flex-col items-start gap-3">
      <Button aria-label="Archive draft" data-agent-confirm="Archive the unsent draft" @click="archived = true">
        Archive draft
      </Button>
      <Button data-agent-hidden="true" @click="run">Ask Claude</Button>
      <span role="status" class="text-[12px] text-muted-foreground">{{ archived ? "Draft archived" : "Unsent draft" }}</span>
      <AgentPointer :controller="pointer" />
    </div>
  </template>
  ```
</ExamplePreview>

### Resolve a target [#resolve-a-target]

Point to the submit button when the bridge reports the form itself.

<ExamplePreview name="agent-pointer/resolve-target">
**React**

  ```tsx
  "use client"

  import { createAgent } from "@ui-sdk/react/agent"
  import * as React from "react"

  import { AgentPointer, createAgentPointer } from "@/components/keyframery/agent-pointer"
  import { Button } from "@/components/keyframery/button"
  import { Form, FormStatus, FormSubmit } from "@/components/keyframery/form"

  export default function ResolveTarget() {
    const submit = React.useRef<HTMLButtonElement>(null)
    const [pointer] = React.useState(() => createAgentPointer({
      resolveTarget: (step) => step.action === "submit" ? submit.current ?? undefined : undefined,
    }))
    const [agent] = React.useState(() => typeof window === "undefined" ? undefined : createAgent({
      allow: pointer.wrapAllow({ authorize: (step) => step.label === "Confirm RSVP" && step.action === "submit" }),
    }))
    return (
      <div className="flex w-full max-w-sm flex-col items-start gap-3">
        <Form aria-label="Confirm RSVP" submit={() => ({ message: "RSVP confirmed." })}>
          <FormSubmit ref={submit}>Confirm RSVP</FormSubmit>
          <FormStatus />
        </Form>
        <Button data-agent-hidden onClick={() => agent && pointer.run(agent, {
          steps: [{ ref: "Confirm RSVP", action: "submit" }],
        })}>Ask Claude</Button>
        <AgentPointer controller={pointer} />
      </div>
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { createAgent } from "@ui-sdk/vue/agent"
  import { ref } from "vue"

  import { AgentPointer, createAgentPointer } from "@/components/keyframery/agent-pointer"
  import { Button } from "@/components/keyframery/button"
  import { Form, FormStatus, FormSubmit } from "@/components/keyframery/form"

  const scope = ref<HTMLElement>()
  const pointer = createAgentPointer({
    resolveTarget: (step) => step.action === "submit" ? scope.value?.querySelector("button[type=submit]") ?? undefined : undefined,
  })
  const agent = typeof window === "undefined" ? undefined : createAgent({
    allow: pointer.wrapAllow({ authorize: (step) => step.label === "Confirm RSVP" && step.action === "submit" }),
  })

  function run() {
    if (agent) return pointer.run(agent, { steps: [{ ref: "Confirm RSVP", action: "submit" }] })
  }
  </script>

  <template>
    <div ref="scope" class="flex w-full max-w-sm flex-col items-start gap-3">
      <Form aria-label="Confirm RSVP" :submit="() => ({ message: 'RSVP confirmed.' })">
        <FormSubmit>Confirm RSVP</FormSubmit>
        <FormStatus />
      </Form>
      <Button data-agent-hidden="true" @click="run">Ask Claude</Button>
      <AgentPointer :controller="pointer" />
    </div>
  </template>
  ```
</ExamplePreview>

### Route a model's tool calls [#route-a-models-tool-calls]

Give your model adapter the UI SDK tool schemas and handlers. This demo uses scripted calls.

<ExamplePreview name="agent-pointer/model-tools">
**React**

  ```tsx
  "use client"

  import { createAgent } from "@ui-sdk/react/agent"
  import * as React from "react"

  import { AgentPointer, createAgentPointer, type AgentPointerController } from "@/components/keyframery/agent-pointer"
  import { createApprovals } from "@/components/keyframery/approval"
  import { Button } from "@/components/keyframery/button"
  import { Input } from "@/components/keyframery/input"

  type Bridge = ReturnType<typeof createAgent>
  type ToolHandlers = Pick<Bridge, "snapshot" | "query" | "act">
  type ModelLoop = (tools: Bridge["tools"], handlers: ToolHandlers) => Promise<unknown>

  function runTurn(pointer: AgentPointerController, agent: Bridge, runModel: ModelLoop) {
    return pointer.session(() => runModel(agent.tools, {
      snapshot: agent.snapshot,
      query: (input) => agent.query({ ...input, closed: false }),
      act: (input) => pointer.run(agent, input),
    }))
  }

  export default function ModelTools() {
    const [sent, setSent] = React.useState(false)
    const [running, setRunning] = React.useState(false)
    const [pointer] = React.useState(createAgentPointer)
    const [agent] = React.useState(() => typeof window === "undefined" ? undefined : createAgent({
      allow: pointer.wrapAllow({
        approvals: createApprovals(),
        authorize: ({ label, action }) =>
          (label === "Delivery note" && action === "setValue") ||
          (label === "Send note" && action === "press"),
      }),
    }))

    async function run() {
      if (!agent || running) return
      setRunning(true)
      try {
        // Replace this callback with your model loop. Validate each tool call against its schema.
        await runTurn(pointer, agent, async (_tools, handlers) => {
          await handlers.query({ text: "Delivery note" })
          const entered = await handlers.act({
            steps: [{ ref: "Delivery note", action: "setValue", args: ["Leave at reception"] }],
          })
          if (entered.ok) await handlers.act({ steps: [{ ref: "Send note", action: "press" }] })
        })
      } finally {
        setRunning(false)
      }
    }

    return (
      <div className="flex w-full max-w-sm flex-col gap-3">
        <Input aria-label="Delivery note" />
        <div className="flex flex-wrap gap-2">
          <Button data-agent-confirm="Send the delivery note" disabled={sent} onClick={() => setSent(true)}>
            {sent ? "Note sent" : "Send note"}
          </Button>
          <Button variant="primary" data-agent-hidden disabled={running || sent} onClick={run}>Run sample turn</Button>
        </div>
        <AgentPointer controller={pointer} />
      </div>
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { createAgent } from "@ui-sdk/vue/agent"
  import { ref } from "vue"

  import { AgentPointer, createAgentPointer, type AgentPointerController } from "@/components/keyframery/agent-pointer"
  import { createApprovals } from "@/components/keyframery/approval"
  import { Button } from "@/components/keyframery/button"
  import { Input } from "@/components/keyframery/input"

  type Bridge = ReturnType<typeof createAgent>
  type ToolHandlers = Pick<Bridge, "snapshot" | "query" | "act">
  type ModelLoop = (tools: Bridge["tools"], handlers: ToolHandlers) => Promise<unknown>

  function runTurn(pointer: AgentPointerController, agent: Bridge, runModel: ModelLoop) {
    return pointer.session(() => runModel(agent.tools, {
      snapshot: agent.snapshot,
      query: (input) => agent.query({ ...input, closed: false }),
      act: (input) => pointer.run(agent, input),
    }))
  }

  const sent = ref(false)
  const running = ref(false)
  const pointer = createAgentPointer()
  const agent = typeof window === "undefined" ? undefined : createAgent({
    allow: pointer.wrapAllow({
      approvals: createApprovals(),
      authorize: ({ label, action }) =>
        (label === "Delivery note" && action === "setValue") ||
        (label === "Send note" && action === "press"),
    }),
  })

  async function run() {
    if (!agent || running.value) return
    running.value = true
    try {
      // Replace this callback with your model loop. Validate each tool call against its schema.
      await runTurn(pointer, agent, async (_tools, handlers) => {
        await handlers.query({ text: "Delivery note" })
        const entered = await handlers.act({
          steps: [{ ref: "Delivery note", action: "setValue", args: ["Leave at reception"] }],
        })
        if (entered.ok) await handlers.act({ steps: [{ ref: "Send note", action: "press" }] })
      })
    } finally {
      running.value = false
    }
  }
  </script>

  <template>
    <div class="flex w-full max-w-sm flex-col gap-3">
      <Input aria-label="Delivery note" />
      <div class="flex flex-wrap gap-2">
        <Button data-agent-confirm="Send the delivery note" :disabled="sent" @click="sent = true">
          {{ sent ? "Note sent" : "Send note" }}
        </Button>
        <Button variant="primary" data-agent-hidden="true" :disabled="running || sent" @click="run">Run sample turn</Button>
      </div>
      <AgentPointer :controller="pointer" />
    </div>
  </template>
  ```
</ExamplePreview>

## Motion [#motion]

| Move      | What you see                                                                         |
| --------- | ------------------------------------------------------------------------------------ |
| **Glide** | The pointer travels to the control before the bridge applies the step.               |
| **Press** | A ripple marks a press. A target outline appears when a matching change is observed. |
| **Fade**  | With reduced motion, the target is outlined in place and there is no arrival wait.   |

Timing and springiness follow the [motion style](/docs/motion-styles) you set. To change how fast this agent pointer moves, pass `speed`:

**React**

```tsx
<AgentPointer controller={pointer} speed="fast" />
```

**Vue**

```vue
<AgentPointer :controller="pointer" speed="fast" />
```

`"fast"` is 0.6×, `"slow"` 1.4×, and a number sets the multiplier. With reduced motion turned on, nothing moves: changes happen at once or with a short fade.

## Theming [#theming]

Set these CSS variables on the component or a parent. Leave them unset to follow the light and dark theme. The open Customize panel below the preview lets you try these settings.

| Variable                      | What it changes                   | Default              |
| ----------------------------- | --------------------------------- | -------------------- |
| `--agent-pointer-accent`      | Cursor, target outline and ripple | --primary            |
| `--agent-pointer-ink`         | Label text colour                 | --primary-foreground |
| `--agent-pointer-preview`     | Value preview surface             | --popover            |
| `--agent-pointer-preview-ink` | Value preview text colour         | --popover-foreground |
| `--agent-pointer-size`        | Cursor size                       | 25px                 |
| `--agent-pointer-radius`      | Label and preview corners         | 6px                  |
| `--agent-pointer-font`        | Label text size                   | 12px                 |
| `--agent-pointer-ring`        | Target outline thickness          | 2px                  |

## API reference [#api-reference]

Every part takes `className` and `children`, along with the props of the element it renders. The parts are rendered by UI SDK, so they also take `render`, to draw your own element, and a function of their state for `className` and `style`.

### AgentPointer [#agentpointer]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;speed&#x22;,&#x22;type&#x22;:&#x22;\&#x22;fast\&#x22; | \&#x22;normal\&#x22; | \&#x22;slow\&#x22; | number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Changes the speed of the pointer's CSS motion and arrival wait.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;label&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The visible name beside the pointer. Defaults to Claude.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;controller&#x22;,&#x22;type&#x22;:&#x22;AgentPointerController&#x22;,&#x22;full&#x22;:&#x22;AgentPointerController&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The controller created by createAgentPointer. Keep the same controller for the life of the view.&#x22;,&#x22;required&#x22;:true}]" />

## Keyboard [#keyboard]

| Key                         | What it does                                                                                               |
| --------------------------- | ---------------------------------------------------------------------------------------------------------- |
| <kbd>Tab or Shift+Tab</kbd> | Moves between the person's controls. When the Approval card opens, it focuses Deny for a high-risk action. |
| <kbd>Enter or Space</kbd>   | Activates Approve, Deny, or Take over.                                                                     |

## Accessibility [#accessibility]

Roles, keyboard and focus are declared on the component's UI SDK primitive, and state is announced through the matching ARIA attributes. More in [Accessibility](/docs/accessibility).

## Built on UI SDK's core [#built-on-ui-sdks-core]

UI SDK doesn't ship a agent pointer, so this one is defined with its core: one `definePrimitive` in `components/keyframery/core/agent-pointer-core.ts`, with no React in it. UI SDK's adapters can render that same definition in Vue, Svelte, Solid and web components. To keep your own styling and take only the motion, import from `@/components/keyframery/primitives/agent-pointer`.

## Questions

### How does the animated Agent Pointer for UI SDK move?

Glide: The pointer travels to the control before the bridge applies the step. Press: A ripple marks a press. A target outline appears when a matching change is observed. Fade: With reduced motion, the target is outlined in place and there is no arrival wait.

### Do I need Motion or Framer Motion for the animated Agent Pointer?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### UI SDK has no agent pointer. How is this one built on UI SDK?

Its behaviour is one definition written with UI SDK's core (`definePrimitive`), in `components/keyframery/core/agent-pointer-core.ts`. Its parts are rendered by UI SDK's adapter, so they take `render`, state-based class names and `data-slot`, like every UI SDK component.

### What happens to the Agent Pointer when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
