{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tool-approval",
  "title": "Tool Approval",
  "description": "Approve or deny an AI SDK tool call, or a batch of them, with a gesture that matches its risk: undo for low, click again for medium, hold for high and a typed phrase for critical. Pass addToolApprovalResponse from useChat as onRespond.",
  "dependencies": [
    "@base-ui/react"
  ],
  "registryDependencies": [
    "button",
    "checkbox",
    "input",
    "label"
  ],
  "files": [
    {
      "path": "components/ui/sureui/confirmation.ts",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\ntype Fill = {\n  from: number\n  to: number\n  duration: number\n  startedAt: number\n  easing?: string\n}\n\nfunction prefersReducedMotion() {\n  return (\n    typeof window.matchMedia === \"function\" &&\n    window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n  )\n}\n\nfunction keyframes(element: Element, fill: Fill) {\n  if (element instanceof SVGElement)\n    return [\n      { strokeDashoffset: `${1 - fill.from}` },\n      { strokeDashoffset: `${1 - fill.to}` },\n    ]\n  return [{ scale: `${fill.from} 1` }, { scale: `${fill.to} 1` }]\n}\n\nfunction playFill(element: Element | null, fill: Fill) {\n  if (!element || typeof element.animate !== \"function\") return null\n  const animation = element.animate(keyframes(element, fill), {\n    duration: fill.duration,\n    easing: prefersReducedMotion() ? \"step-end\" : (fill.easing ?? \"linear\"),\n    fill: \"forwards\",\n  })\n  animation.currentTime = performance.now() - fill.startedAt\n  return animation\n}\n\nfunction useFill(\n  ref: React.RefObject<Element | null>,\n  fill: Fill | null,\n  paused: boolean\n) {\n  const animationRef = React.useRef<Animation | null>(null)\n\n  React.useEffect(() => {\n    if (!fill) return\n    const animation = playFill(ref.current, fill)\n    animationRef.current = animation\n    return () => {\n      animation?.cancel()\n      animationRef.current = null\n    }\n  }, [ref, fill])\n\n  React.useEffect(() => {\n    const animation = animationRef.current\n    if (paused) animation?.pause()\n    else if (animation?.playState === \"paused\") animation.play()\n  }, [paused, fill])\n}\n\ntype UndoPauseReason = \"hover\" | \"focus\" | \"hidden\"\n\ntype UndoDuration = boolean | number | \"manual\"\n\ntype UndoWindowOptions = {\n  duration?: UndoDuration\n  onExpire: () => void\n  onPauseChange?: (paused: boolean) => void\n  within?: () => Element | null\n}\n\ntype UndoWindow = {\n  duration: number\n  manual: boolean\n  elapsed: () => number\n  paused: () => boolean\n  pause: (reason: UndoPauseReason) => void\n  resume: (reason: UndoPauseReason) => void\n  cancel: () => void\n}\n\nfunction undoDuration(value: UndoDuration | undefined) {\n  if (typeof value !== \"number\" || !Number.isFinite(value)) return 5000\n  return Math.min(Math.max(value, 4000), 60000)\n}\n\nfunction startManualWindow({\n  onExpire,\n  within,\n}: UndoWindowOptions): UndoWindow {\n  let open = true\n\n  function stop() {\n    open = false\n    document.removeEventListener(\"pointerdown\", onOutside, true)\n    document.removeEventListener(\"focusin\", onOutside, true)\n  }\n\n  function onOutside(event: Event) {\n    const container = within?.()\n    const target = event.target\n    if (!open || !container || !(target instanceof Node)) return\n    if (container.contains(target)) return\n    stop()\n    onExpire()\n  }\n\n  if (within) {\n    document.addEventListener(\"pointerdown\", onOutside, true)\n    document.addEventListener(\"focusin\", onOutside, true)\n  }\n\n  return {\n    duration: Infinity,\n    manual: true,\n    elapsed: () => 0,\n    paused: () => false,\n    pause: () => {},\n    resume: () => {},\n    cancel: stop,\n  }\n}\n\nfunction startUndoWindow(options: UndoWindowOptions): UndoWindow {\n  const { duration, onExpire, onPauseChange } = options\n  if (duration === \"manual\") return startManualWindow(options)\n  const total = undoDuration(duration)\n  const pausedBy = new Set<UndoPauseReason>()\n  let open = true\n  let remaining = total\n  let startedAt = performance.now()\n  let timer = setTimeout(expire, remaining)\n\n  function stop() {\n    open = false\n    clearTimeout(timer)\n    document.removeEventListener(\"visibilitychange\", onVisibilityChange)\n  }\n\n  function expire() {\n    stop()\n    onExpire()\n  }\n\n  function pause(reason: UndoPauseReason) {\n    if (!open || pausedBy.has(reason)) return\n    pausedBy.add(reason)\n    if (pausedBy.size > 1) return\n    clearTimeout(timer)\n    remaining -= performance.now() - startedAt\n    onPauseChange?.(true)\n  }\n\n  function resume(reason: UndoPauseReason) {\n    if (!open || !pausedBy.delete(reason) || pausedBy.size > 0) return\n    startedAt = performance.now()\n    timer = setTimeout(expire, remaining)\n    onPauseChange?.(false)\n  }\n\n  function onVisibilityChange() {\n    if (document.visibilityState === \"hidden\") pause(\"hidden\")\n    else resume(\"hidden\")\n  }\n\n  document.addEventListener(\"visibilitychange\", onVisibilityChange)\n  onVisibilityChange()\n\n  return {\n    duration: total,\n    manual: false,\n    elapsed: () =>\n      total -\n      remaining +\n      (pausedBy.size > 0 ? 0 : performance.now() - startedAt),\n    paused: () => pausedBy.size > 0,\n    pause,\n    resume,\n    cancel: stop,\n  }\n}\n\ntype ConfirmationState = \"idle\" | \"armed\" | \"holding\" | \"undo\" | \"pending\"\n\ntype PauseReason = \"hover\" | \"focus\"\n\ntype InlineUndo = {\n  window: UndoWindow\n  pausable: Set<PauseReason>\n}\n\ninterface ConfirmationOptions {\n  onConfirm: () => void | Promise<unknown>\n  onCancel?: () => void\n  onConfirmError?: (error: unknown) => void\n  undo?: boolean | number | \"manual\"\n  pauseUndoOnHover?: boolean\n  pauseUndoOnFocus?: boolean\n}\n\ninterface GestureOptions {\n  gesture?: \"click\" | \"click-again\" | \"hold\" | \"slide\"\n  timeout?: number\n  duration?: number\n  holdFallback?: \"click-again\" | \"none\"\n  armDelay?: number\n  wait?: number\n  disabled?: boolean\n}\n\ntype TriggerProps<T extends Element> = {\n  disabled?: boolean\n  onClick?(event: React.MouseEvent<T>): void\n  onBlur?(event: React.FocusEvent<T>): void\n  onFocus?(event: React.FocusEvent<T>): void\n  onPointerDown?(event: React.PointerEvent<T>): void\n  onPointerUp?(event: React.PointerEvent<T>): void\n  onPointerMove?(event: React.PointerEvent<T>): void\n  onPointerEnter?(event: React.PointerEvent<T>): void\n  onPointerLeave?(event: React.PointerEvent<T>): void\n  onPointerCancel?(event: React.PointerEvent<T>): void\n  onKeyDown?(event: React.KeyboardEvent<T>): void\n  onKeyUp?(event: React.KeyboardEvent<T>): void\n  onContextMenu?(event: React.MouseEvent<T>): void\n  onMouseDown?(event: React.MouseEvent<T>): void\n}\n\nfunction hasSelection() {\n  const selection = window.getSelection()\n  return !!selection && !selection.isCollapsed\n}\n\nfunction clearSelection() {\n  if (hasSelection()) window.getSelection()?.removeAllRanges()\n}\n\nfunction isPromise(value: unknown): value is PromiseLike<unknown> {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    typeof (value as PromiseLike<unknown>).then === \"function\"\n  )\n}\n\nfunction toMs(value: number, fallback: number, min: number) {\n  return Number.isFinite(value)\n    ? Math.min(Math.max(value, min), 60000)\n    : fallback\n}\n\nfunction composeHandlers<E>(\n  theirs: ((event: E) => void) | undefined,\n  ours: (event: E) => void\n) {\n  return (event: E) => {\n    theirs?.(event)\n    ours(event)\n  }\n}\n\nfunction isPressKey(event: React.KeyboardEvent) {\n  return event.key === \" \" || event.key === \"Enter\"\n}\n\nfunction isVirtualPress(event: React.PointerEvent) {\n  const { width, height, pressure, pointerType } = event.nativeEvent\n  const android = /Android/i.test(navigator.userAgent)\n  if (width < 1 && height < 1) return !android\n  return (\n    android &&\n    pointerType === \"mouse\" &&\n    width === 1 &&\n    height === 1 &&\n    pressure === 0\n  )\n}\n\nfunction useConfirmationMachine(\n  options: ConfirmationOptions,\n  triggerRef: React.RefObject<Element | null>\n) {\n  const [state, setState] = React.useState<ConfirmationState>(\"idle\")\n  const [fill, setFill] = React.useState<Fill | null>(null)\n  const [paused, setPaused] = React.useState(false)\n  const [failed, setFailed] = React.useState(false)\n  const [undoSeconds, setUndoSeconds] = React.useState<number | null>(null)\n  const timerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)\n  const holdStartRef = React.useRef(0)\n  const holdDurationRef = React.useRef(0)\n  const undoRef = React.useRef<InlineUndo | null>(null)\n  const optionsRef = React.useRef(options)\n\n  React.useEffect(() => {\n    optionsRef.current = options\n  })\n\n  const clearTimer = React.useCallback(() => {\n    undoRef.current?.window.cancel()\n    undoRef.current = null\n    if (timerRef.current !== null) {\n      clearTimeout(timerRef.current)\n      timerRef.current = null\n    }\n  }, [])\n\n  React.useEffect(() => clearTimer, [clearTimer])\n\n  const enter = React.useCallback(\n    (next: ConfirmationState, nextFill: Fill | null = null) => {\n      setState(next)\n      setFill(nextFill)\n      setPaused(false)\n      setFailed(false)\n    },\n    []\n  )\n\n  const fail = React.useCallback((error: unknown) => {\n    setFailed(true)\n    const { onConfirmError } = optionsRef.current\n    if (!onConfirmError) throw error\n    onConfirmError(error)\n  }, [])\n\n  const commit = React.useCallback(\n    (run: ConfirmationOptions[\"onConfirm\"]) => {\n      clearTimer()\n      let result: ReturnType<ConfirmationOptions[\"onConfirm\"]>\n      try {\n        result = run()\n      } catch (error) {\n        enter(\"idle\")\n        return fail(error)\n      }\n      if (isPromise(result)) {\n        enter(\"pending\")\n        ;(async () => {\n          try {\n            await result\n            setState(\"idle\")\n          } catch (error) {\n            setState(\"idle\")\n            fail(error)\n          }\n        })()\n      } else {\n        enter(\"idle\")\n      }\n    },\n    [clearTimer, enter, fail]\n  )\n\n  const confirm = React.useCallback(() => {\n    const { undo, onConfirm } = optionsRef.current\n    clearTimer()\n    if (!undo) return commit(onConfirm)\n    const undoWindow = startUndoWindow({\n      duration: undo,\n      onExpire: () => commit(onConfirm),\n      onPauseChange: setPaused,\n      within: () => triggerRef.current,\n    })\n    undoRef.current = { window: undoWindow, pausable: new Set() }\n    setUndoSeconds(\n      undoWindow.manual ? null : Math.ceil(undoWindow.duration / 1000)\n    )\n    enter(\n      \"undo\",\n      undoWindow.manual\n        ? null\n        : {\n            from: 1,\n            to: 0,\n            duration: undoWindow.duration,\n            startedAt: performance.now(),\n          }\n    )\n    setPaused(undoWindow.paused())\n  }, [commit, clearTimer, enter, triggerRef])\n\n  const pauseUndo = React.useCallback((reason: PauseReason) => {\n    const { pauseUndoOnHover = true, pauseUndoOnFocus = true } =\n      optionsRef.current\n    if (reason === \"hover\" ? !pauseUndoOnHover : !pauseUndoOnFocus) return\n    const undo = undoRef.current\n    if (undo?.pausable.has(reason)) undo.window.pause(reason)\n  }, [])\n\n  const resumeUndo = React.useCallback((reason: PauseReason) => {\n    const undo = undoRef.current\n    if (!undo) return\n    undo.pausable.add(reason)\n    undo.window.resume(reason)\n  }, [])\n\n  React.useEffect(() => {\n    const undo = undoRef.current?.window\n    if (state !== \"undo\" || paused || !undo || undo.manual) return\n    let timer: ReturnType<typeof setTimeout>\n    function tick() {\n      const left = undo!.duration - undo!.elapsed()\n      setUndoSeconds(Math.max(1, Math.ceil(left / 1000)))\n      timer = setTimeout(tick, (left % 1000 || 1000) + 1)\n    }\n    timer = setTimeout(\n      tick,\n      ((undo.duration - undo.elapsed()) % 1000 || 1000) + 1\n    )\n    return () => clearTimeout(timer)\n  }, [state, paused])\n\n  const arm = React.useCallback(() => {\n    clearTimer()\n    enter(\"armed\")\n  }, [clearTimer, enter])\n\n  const hold = React.useCallback(\n    (duration: number) => {\n      const ms = toMs(duration, 1200, 800)\n      holdStartRef.current = performance.now()\n      holdDurationRef.current = ms\n      enter(\"holding\", {\n        from: 0,\n        to: 1,\n        duration: ms,\n        startedAt: holdStartRef.current,\n      })\n      timerRef.current = setTimeout(confirm, ms)\n    },\n    [confirm, enter]\n  )\n\n  const slide = React.useCallback(\n    (fraction: number) => {\n      enter(\"holding\", {\n        from: fraction,\n        to: fraction,\n        duration: 0,\n        startedAt: performance.now(),\n      })\n    },\n    [enter]\n  )\n\n  const release = React.useCallback(\n    (from?: number) => {\n      const now = performance.now()\n      const fraction =\n        from ??\n        Math.min((now - holdStartRef.current) / holdDurationRef.current, 1)\n      clearTimer()\n      enter(\"idle\", {\n        from: fraction,\n        to: 0,\n        duration: 200,\n        startedAt: now,\n        easing: \"ease-out\",\n      })\n      optionsRef.current.onCancel?.()\n    },\n    [clearTimer, enter]\n  )\n\n  const cancel = React.useCallback(() => {\n    clearTimer()\n    enter(\"idle\")\n    optionsRef.current.onCancel?.()\n  }, [clearTimer, enter])\n\n  const reset = React.useCallback(() => {\n    clearTimer()\n    enter(\"idle\")\n  }, [clearTimer, enter])\n\n  return {\n    state,\n    fill,\n    paused,\n    failed,\n    arm,\n    hold,\n    slide,\n    release,\n    confirm,\n    cancel,\n    pauseUndo,\n    resumeUndo,\n    reset,\n    undoSeconds: state === \"undo\" ? undoSeconds : null,\n  }\n}\n\nfunction useConfirmation<\n  T extends Element = HTMLElement,\n  F extends Element = HTMLSpanElement,\n>({\n  gesture = \"click\",\n  timeout = 3000,\n  duration = 1200,\n  holdFallback = \"click-again\",\n  armDelay = 0,\n  wait = 0,\n  disabled = false,\n  ...options\n}: ConfirmationOptions & GestureOptions) {\n  const triggerRef = React.useRef<T | null>(null)\n  const {\n    state,\n    fill,\n    paused,\n    failed,\n    arm,\n    hold,\n    slide,\n    release,\n    confirm,\n    cancel,\n    pauseUndo,\n    resumeUndo,\n    reset,\n    undoSeconds,\n  } = useConfirmationMachine(options, triggerRef)\n  const fillRef = React.useRef<F>(null)\n  useFill(fillRef, fill, paused)\n  const [waiting, setWaiting] = React.useState(() => waitSeconds(wait))\n\n  React.useEffect(() => {\n    if (waiting <= 0) return\n    const timer = setTimeout(() => setWaiting((left) => left - 1), 1000)\n    return () => clearTimeout(timer)\n  }, [waiting])\n  const armDelayRef = React.useRef(armDelay)\n  const quietRef = React.useRef(false)\n  const quietTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)\n  const repeatRef = React.useRef(false)\n  const undoPressRef = React.useRef(false)\n  const pressRef = React.useRef<\"none\" | \"pointer\" | \"virtual\" | \"key\">(\"none\")\n  const fallbackRef = React.useRef(false)\n  const selectedRef = React.useRef(false)\n  const slideRef = React.useRef<{\n    id: number\n    startX: number\n    width: number\n    progress: number\n    moved: boolean\n  } | null>(null)\n  const slidClickRef = React.useRef(false)\n\n  React.useEffect(() => {\n    armDelayRef.current = armDelay\n  })\n\n  const quiet = React.useCallback(() => {\n    const ms = toMs(armDelayRef.current, 0, 0)\n    if (quietTimerRef.current !== null) clearTimeout(quietTimerRef.current)\n    quietTimerRef.current = null\n    quietRef.current = ms > 0\n    if (ms <= 0) return\n    quietTimerRef.current = setTimeout(() => {\n      quietTimerRef.current = null\n      quietRef.current = false\n    }, ms)\n  }, [])\n\n  React.useEffect(() => {\n    quiet()\n    return () => {\n      if (quietTimerRef.current !== null) clearTimeout(quietTimerRef.current)\n      quietTimerRef.current = null\n      quietRef.current = false\n    }\n  }, [quiet])\n\n  React.useEffect(() => {\n    if (state !== \"armed\") fallbackRef.current = false\n  }, [state])\n\n  React.useEffect(() => {\n    if (state !== \"armed\" || fallbackRef.current) return\n    const timer = setTimeout(cancel, toMs(timeout, 3000, 0))\n    return () => clearTimeout(timer)\n  }, [state, timeout, cancel])\n\n  const isHold = gesture === \"hold\"\n  const isSlide = gesture === \"slide\"\n  const isHolding = state === \"holding\"\n  const fallback = isHold && holdFallback === \"click-again\"\n  const fallbackArmed = state === \"armed\" && fallbackRef.current\n\n  function undoFromPress() {\n    if (state !== \"undo\" || !undoPressRef.current) return\n    undoPressRef.current = false\n    cancel()\n  }\n\n  function armNow() {\n    arm()\n    quiet()\n  }\n\n  function armFallback() {\n    fallbackRef.current = true\n    armNow()\n  }\n\n  function holdClick() {\n    const press = pressRef.current\n    pressRef.current = \"none\"\n    const unpressed = press === \"none\" || press === \"virtual\"\n    if (state === \"undo\") {\n      if (fallback && press === \"none\") undoPressRef.current = true\n      return undoFromPress()\n    }\n    if (!fallback) return\n    if (fallbackArmed) confirm()\n    else if (state === \"idle\" && unpressed) armFallback()\n  }\n\n  function endSlide(target: Element) {\n    const current = slideRef.current\n    if (!current) return\n    slideRef.current = null\n    if (target.hasPointerCapture?.(current.id))\n      target.releasePointerCapture(current.id)\n    if (!current.moved) return\n    slidClickRef.current = true\n    if (current.progress >= 1) confirm()\n    else release(current.progress)\n  }\n\n  const handlers: Required<Omit<TriggerProps<T>, \"disabled\">> = {\n    onClick() {\n      if (quietRef.current) return\n      if (slidClickRef.current) {\n        slidClickRef.current = false\n        return\n      }\n      if (isHold) return holdClick()\n      if (repeatRef.current) return\n      if (state === \"undo\") cancel()\n      else if (state === \"armed\") confirm()\n      else if (state === \"idle\" && gesture === \"click\") confirm()\n      else if (state === \"idle\") armNow()\n    },\n    onBlur() {\n      resumeUndo(\"focus\")\n      const sliding = slideRef.current\n      slideRef.current = null\n      if (isHolding) release(sliding?.progress)\n      else if (state === \"armed\") cancel()\n    },\n    onFocus() {\n      pauseUndo(\"focus\")\n    },\n    onPointerEnter() {\n      pauseUndo(\"hover\")\n    },\n    onPointerLeave() {\n      resumeUndo(\"hover\")\n      if (isHolding && !isSlide) release()\n    },\n    onPointerDown(event) {\n      selectedRef.current = hasSelection()\n      slidClickRef.current = false\n      if (isSlide) {\n        pressRef.current = isVirtualPress(event) ? \"virtual\" : \"pointer\"\n        if (event.button !== 0 || quietRef.current || state !== \"idle\") return\n        if (pressRef.current === \"virtual\") return\n        try {\n          event.currentTarget.setPointerCapture?.(event.pointerId)\n        } catch {}\n        slideRef.current = {\n          id: event.pointerId,\n          startX: event.clientX,\n          width: event.currentTarget.getBoundingClientRect().width,\n          progress: 0,\n          moved: false,\n        }\n        return\n      }\n      if (!isHold || event.button !== 0 || quietRef.current) return\n      pressRef.current = isVirtualPress(event) ? \"virtual\" : \"pointer\"\n      undoPressRef.current = state === \"undo\"\n      if (state !== \"idle\") return\n      const target = event.currentTarget\n      if (target.hasPointerCapture?.(event.pointerId))\n        target.releasePointerCapture(event.pointerId)\n      hold(duration)\n    },\n    onPointerMove(event) {\n      const current = slideRef.current\n      if (!current || current.id !== event.pointerId) return\n      const distance = event.clientX - current.startX\n      if (!current.moved && Math.abs(distance) < 4) return\n      current.moved = true\n      current.progress = Math.min(\n        Math.max(distance / (current.width * 0.85), 0),\n        1\n      )\n      slide(current.progress)\n    },\n    onPointerUp(event) {\n      if (event.pointerType === \"touch\" && !selectedRef.current) {\n        requestAnimationFrame(clearSelection)\n      }\n      if (isSlide) return endSlide(event.currentTarget)\n      if (state !== \"holding\") return\n      if (fallback && pressRef.current === \"virtual\") reset()\n      else release()\n    },\n    onPointerCancel() {\n      if (isSlide) {\n        const current = slideRef.current\n        slideRef.current = null\n        if (current?.moved) release(current.progress)\n        return\n      }\n      if (isHolding) release()\n    },\n    onKeyDown(event) {\n      if (!isHold) {\n        repeatRef.current = event.repeat\n        return\n      }\n      if (event.key === \"Escape\" && fallbackArmed) return cancel()\n      if (!isPressKey(event)) return\n      event.preventDefault()\n      if (event.repeat || quietRef.current) return\n      pressRef.current = \"key\"\n      undoPressRef.current = state === \"undo\"\n      if (state === \"idle\") hold(duration)\n    },\n    onKeyUp(event) {\n      if (!isHold) {\n        repeatRef.current = false\n        return\n      }\n      if (!isPressKey(event)) return\n      const pressed = pressRef.current === \"key\"\n      pressRef.current = \"none\"\n      if (state === \"holding\") release()\n      else if (fallbackArmed && pressed) confirm()\n      else undoFromPress()\n    },\n    onMouseDown(event) {\n      if (event.detail > 1) event.preventDefault()\n    },\n    onContextMenu(event) {\n      if (isHold) event.preventDefault()\n    },\n  }\n\n  function getTriggerProps<P extends TriggerProps<T>>(props: P) {\n    const composed = { ...props }\n    for (const name of Object.keys(handlers) as (keyof typeof handlers)[]) {\n      const handler = handlers[name] as (event: unknown) => void\n      const theirs = props[name] as ((event: unknown) => void) | undefined\n      const ours = (event: { currentTarget: T }) => {\n        triggerRef.current = event.currentTarget\n        handler(event)\n      }\n      Object.assign(composed, { [name]: composeHandlers(theirs, ours) })\n    }\n    return {\n      ...composed,\n      disabled:\n        (disabled && state !== \"undo\") || state === \"pending\" || waiting > 0,\n    }\n  }\n\n  return { state, failed, waiting, undoSeconds, fillRef, getTriggerProps }\n}\n\ntype ConfirmationAnnouncements = {\n  hold?: string\n  armed?: string\n  fallback?: string\n  undo?: string\n  error?: string\n  wait?: string\n  slide?: string\n  success?: string\n}\n\nconst successMs = 1500\n\ninterface ConfirmationLabelOptions {\n  state: ConfirmationState\n  failed: boolean\n  gesture: NonNullable<GestureOptions[\"gesture\"]>\n  holdFallback: NonNullable<GestureOptions[\"holdFallback\"]>\n  undo: ConfirmationOptions[\"undo\"]\n  label: React.ReactNode\n  confirmLabel?: React.ReactNode\n  undoLabel?: React.ReactNode\n  errorLabel?: React.ReactNode\n  wait?: number\n  waiting?: number\n  waitLabel?: (seconds: number) => React.ReactNode\n  pendingLabel?: React.ReactNode\n  pendingDelay?: number\n  successLabel?: React.ReactNode\n  announcements?: ConfirmationAnnouncements\n  ariaLabel?: string\n  describedBy?: string\n}\n\nfunction waitSeconds(wait: number) {\n  return Math.ceil(toMs(wait, 0, 0) / 1000)\n}\n\nfunction text(node: React.ReactNode, fallback: string) {\n  return typeof node === \"string\" ? node : fallback\n}\n\nfunction useConfirmationLabels(options: ConfirmationLabelOptions) {\n  const {\n    state,\n    failed,\n    gesture,\n    holdFallback,\n    undo,\n    label,\n    confirmLabel,\n    undoLabel = \"Undo\",\n    errorLabel,\n    wait = 0,\n    waiting = 0,\n    waitLabel = (seconds: number) => `Wait ${seconds}s`,\n    pendingLabel,\n    pendingDelay = 0,\n    successLabel,\n    announcements,\n    ariaLabel,\n    describedBy,\n  } = options\n  const hintId = React.useId()\n  const [previous, setPrevious] = React.useState(state)\n  const [late, setLate] = React.useState(false)\n  const [succeeded, setSucceeded] = React.useState(false)\n  if (previous !== state) {\n    setPrevious(state)\n    setLate(false)\n    setSucceeded(\n      previous === \"pending\" &&\n        state === \"idle\" &&\n        !failed &&\n        successLabel != null\n    )\n  }\n\n  React.useEffect(() => {\n    if (state !== \"pending\") return\n    const id = setTimeout(() => setLate(true), Math.max(0, pendingDelay))\n    return () => clearTimeout(id)\n  }, [state, pendingDelay])\n\n  React.useEffect(() => {\n    if (!succeeded) return\n    const id = setTimeout(() => setSucceeded(false), successMs)\n    return () => clearTimeout(id)\n  }, [succeeded])\n\n  const waitTotal = waitSeconds(wait)\n  const isHold = gesture === \"hold\"\n  const isSlide = gesture === \"slide\"\n  const showError = failed && state === \"idle\" && errorLabel != null\n  const busy = state === \"pending\" && (late || pendingDelay <= 0)\n  const showPending = busy && pendingLabel != null\n  const showSuccess = succeeded && state === \"idle\"\n  const shown =\n    state === \"armed\" || state === \"undo\"\n      ? state\n      : waiting > 0\n        ? \"wait\"\n        : showPending\n          ? \"pending\"\n          : showSuccess\n            ? \"success\"\n            : showError\n              ? \"error\"\n              : \"idle\"\n  const labels: { state: string; node: React.ReactNode }[] = [\n    { state: \"idle\", node: label },\n  ]\n  if (\n    gesture === \"click-again\" ||\n    isSlide ||\n    (isHold && (confirmLabel != null || holdFallback !== \"none\"))\n  ) {\n    labels.push({\n      state: \"armed\",\n      node: confirmLabel ?? (isHold ? \"Confirm\" : \"Click again\"),\n    })\n  }\n  if (undo) labels.push({ state: \"undo\", node: undoLabel })\n  if (errorLabel != null) labels.push({ state: \"error\", node: errorLabel })\n  if (waitTotal > 0) {\n    labels.push({ state: \"wait\", node: waitLabel(waiting || waitTotal) })\n  }\n  if (pendingLabel != null)\n    labels.push({ state: \"pending\", node: pendingLabel })\n  if (successLabel != null)\n    labels.push({ state: \"success\", node: successLabel })\n\n  let announcement = \"\"\n  if (shown === \"wait\") {\n    announcement = announcements?.wait ?? `Available in ${waitTotal} seconds`\n  } else if (state === \"armed\" && isHold) {\n    announcement = announcements?.fallback ?? \"Activate again to confirm\"\n  } else if (state === \"armed\") {\n    announcement =\n      announcements?.armed ?? text(confirmLabel, \"Click again to confirm\")\n  } else if (state === \"undo\") {\n    announcement = announcements?.undo ?? \"Done. Undo is available.\"\n  } else if (showSuccess) {\n    announcement = announcements?.success ?? text(successLabel, \"Done\")\n  } else if (showError) {\n    announcement =\n      announcements?.error ??\n      text(errorLabel, \"Failed. Activate again to retry.\")\n  }\n\n  return {\n    shown,\n    busy,\n    labels,\n    ariaLabel:\n      ariaLabel && shown === \"undo\"\n        ? text(undoLabel, ariaLabel)\n        : ariaLabel && shown === \"error\"\n          ? text(errorLabel, ariaLabel)\n          : ariaLabel,\n    ariaDescribedBy:\n      isHold || isSlide\n        ? [hintId, describedBy].filter(Boolean).join(\" \")\n        : describedBy,\n    hint: isHold\n      ? {\n          id: hintId,\n          text:\n            announcements?.hold ??\n            (holdFallback === \"none\"\n              ? \"Press and hold to confirm\"\n              : \"Press and hold, or activate twice, to confirm\"),\n        }\n      : isSlide\n        ? {\n            id: hintId,\n            text:\n              announcements?.slide ??\n              \"Slide to the end, or activate twice, to confirm\",\n          }\n        : null,\n    announcement,\n  }\n}\n\nexport {\n  useConfirmation,\n  useConfirmationLabels,\n  composeHandlers,\n  isPromise,\n  playFill,\n  useFill,\n  startUndoWindow,\n  type ConfirmationState,\n  type ConfirmationAnnouncements,\n  type ConfirmationOptions,\n  type GestureOptions,\n  type Fill,\n  type UndoWindow,\n}\n",
      "type": "registry:lib",
      "target": "@ui/sureui/confirmation.ts"
    },
    {
      "path": "components/ui/sureui/confirm-button.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport {\n  useConfirmation,\n  useConfirmationLabels,\n  type ConfirmationAnnouncements,\n  type ConfirmationOptions,\n  type GestureOptions,\n} from \"@/components/ui/sureui/confirmation\"\n\ninterface ConfirmButtonProps\n  extends\n    React.ComponentProps<typeof Button>,\n    ConfirmationOptions,\n    GestureOptions {\n  confirmLabel?: React.ReactNode\n  undoLabel?: React.ReactNode\n  errorLabel?: React.ReactNode\n  waitLabel?: (seconds: number) => React.ReactNode\n  pendingIndicator?: \"ring\" | \"spinner\" | \"pulse\"\n  pendingLabel?: React.ReactNode\n  pendingDelay?: number\n  successLabel?: React.ReactNode\n  announcements?: ConfirmationAnnouncements\n}\n\nfunction useSpin<T extends Element>(duration: number) {\n  const ref = React.useRef<T>(null)\n\n  React.useEffect(() => {\n    const element = ref.current\n    if (!element) return\n    const still = window.matchMedia?.(\n      \"(prefers-reduced-motion: reduce)\"\n    ).matches\n    if (still || typeof element.animate !== \"function\") return\n    const animation = element.animate(\n      [{ rotate: \"0deg\" }, { rotate: \"360deg\" }],\n      { duration, iterations: Infinity }\n    )\n    return () => animation.cancel()\n  }, [duration])\n\n  return ref\n}\n\nfunction Spinner() {\n  const ref = useSpin<SVGSVGElement>(800)\n\n  return (\n    <svg ref={ref} viewBox=\"0 0 24 24\" aria-hidden className=\"size-4 shrink-0\">\n      <circle\n        cx=\"12\"\n        cy=\"12\"\n        r=\"9\"\n        pathLength={1}\n        strokeDasharray=\"0.7 0.3\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth=\"2\"\n        strokeLinecap=\"round\"\n      />\n    </svg>\n  )\n}\n\nfunction outline(button: HTMLElement, gap: number) {\n  const style = getComputedStyle(button)\n  const out = (parseFloat(style.borderTopWidth) || 0) + gap\n  const width = button.clientWidth + out * 2\n  const height = button.clientHeight + out * 2\n  const corner = (value: string) =>\n    Math.min((parseFloat(value) || 0) + gap, width / 2, height / 2)\n  const tl = corner(style.borderTopLeftRadius)\n  const tr = corner(style.borderTopRightRadius)\n  const br = corner(style.borderBottomRightRadius)\n  const bl = corner(style.borderBottomLeftRadius)\n  const right = width - out\n  const bottom = height - out\n  return [\n    `M${tl - out},${-out}`,\n    `H${right - tr}`,\n    `A${tr},${tr} 0 0 1 ${right},${tr - out}`,\n    `V${bottom - br}`,\n    `A${br},${br} 0 0 1 ${right - br},${bottom}`,\n    `H${bl - out}`,\n    `A${bl},${bl} 0 0 1 ${-out},${bottom - bl}`,\n    `V${tl - out}`,\n    `A${tl},${tl} 0 0 1 ${tl - out},${-out}`,\n    \"Z\",\n  ].join(\" \")\n}\n\nfunction Ring(props: { className?: string }) {\n  const ref = React.useRef<SVGPathElement>(null)\n\n  React.useEffect(() => {\n    const path = ref.current\n    const button = path?.closest(\"button\")\n    if (!path || !button) return\n    const draw = () => path.setAttribute(\"d\", outline(button, 3))\n    draw()\n    const observer =\n      typeof ResizeObserver === \"function\" ? new ResizeObserver(draw) : null\n    observer?.observe(button)\n    const still = window.matchMedia?.(\n      \"(prefers-reduced-motion: reduce)\"\n    ).matches\n    const animation =\n      still || typeof path.animate !== \"function\"\n        ? null\n        : path.animate([{ strokeDashoffset: 1 }, { strokeDashoffset: 0 }], {\n            duration: 1400,\n            iterations: Infinity,\n          })\n    return () => {\n      observer?.disconnect()\n      animation?.cancel()\n    }\n  }, [])\n\n  return (\n    <svg\n      aria-hidden\n      data-slot=\"pending-ring\"\n      className={cn(\n        \"pointer-events-none absolute inset-0 size-full overflow-visible\",\n        props.className\n      )}\n    >\n      <path\n        ref={ref}\n        pathLength={1}\n        strokeDasharray=\"0.3 0.7\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth={1.5}\n        strokeLinecap=\"round\"\n      />\n    </svg>\n  )\n}\n\nfunction pendingContent(\n  indicator: NonNullable<ConfirmButtonProps[\"pendingIndicator\"]>,\n  label: React.ReactNode\n) {\n  if (indicator !== \"spinner\") return label ?? undefined\n  return (\n    <>\n      <Spinner />\n      {label}\n    </>\n  )\n}\n\nfunction ConfirmButton(props: ConfirmButtonProps) {\n  const {\n    onConfirm,\n    onCancel,\n    onConfirmError,\n    undo,\n    pauseUndoOnHover,\n    pauseUndoOnFocus,\n    gesture = \"click\",\n    timeout,\n    duration,\n    holdFallback = \"click-again\",\n    armDelay,\n    wait,\n    disabled,\n    confirmLabel,\n    undoLabel,\n    errorLabel,\n    waitLabel,\n    pendingIndicator = \"ring\",\n    pendingLabel,\n    pendingDelay,\n    successLabel,\n    announcements,\n    className,\n    children,\n    \"aria-describedby\": describedBy,\n    ...rest\n  } = props\n  const { state, failed, waiting, fillRef, getTriggerProps } =\n    useConfirmation<HTMLButtonElement>({\n      onConfirm,\n      onCancel,\n      onConfirmError,\n      undo,\n      pauseUndoOnHover,\n      pauseUndoOnFocus,\n      gesture,\n      timeout,\n      duration,\n      holdFallback,\n      armDelay,\n      wait,\n      disabled,\n    })\n  const {\n    shown,\n    busy,\n    labels,\n    ariaLabel,\n    ariaDescribedBy,\n    hint,\n    announcement,\n  } = useConfirmationLabels({\n    state,\n    failed,\n    gesture,\n    holdFallback,\n    undo,\n    label: children,\n    confirmLabel,\n    undoLabel,\n    errorLabel,\n    wait,\n    waiting,\n    waitLabel,\n    pendingLabel: pendingContent(pendingIndicator, pendingLabel),\n    pendingDelay,\n    successLabel,\n    announcements,\n    ariaLabel: rest[\"aria-label\"],\n    describedBy,\n  })\n\n  return (\n    <>\n      <Button\n        {...getTriggerProps(rest)}\n        aria-label={ariaLabel}\n        aria-describedby={ariaDescribedBy}\n        data-state={state}\n        data-error={failed || undefined}\n        aria-busy={state === \"pending\" || undefined}\n        data-pending={busy || undefined}\n        className={cn(\n          \"relative transition-[color,background-color,border-color,box-shadow] active:not-aria-[haspopup]:translate-none aria-disabled:opacity-50\",\n          pendingIndicator === \"pulse\"\n            ? \"motion-safe:data-pending:animate-pulse motion-safe:aria-disabled:data-[state=pending]:opacity-100\"\n            : \"aria-disabled:data-[state=pending]:opacity-100\",\n          gesture === \"hold\"\n            ? \"touch-none\"\n            : gesture === \"slide\"\n              ? \"touch-pan-y\"\n              : \"touch-manipulation\",\n          className\n        )}\n        focusableWhenDisabled={\n          rest.focusableWhenDisabled || state === \"pending\"\n        }\n      >\n        <span\n          aria-hidden\n          className=\"absolute inset-0 overflow-hidden rounded-[inherit]\"\n        >\n          <span\n            ref={fillRef}\n            className=\"absolute inset-0 origin-left scale-x-0 bg-current opacity-20\"\n          />\n        </span>\n        {busy && pendingIndicator === \"ring\" && (\n          <Ring\n            className={\n              rest.variant === \"destructive\"\n                ? \"text-destructive\"\n                : !rest.variant || rest.variant === \"default\"\n                  ? \"text-primary\"\n                  : undefined\n            }\n          />\n        )}\n        <span className=\"grid gap-[inherit]\">\n          {labels.map((label) => (\n            <span\n              key={label.state}\n              aria-hidden={label.state !== shown || undefined}\n              className={cn(\n                \"col-start-1 row-start-1 inline-flex items-center justify-center gap-[inherit]\",\n                label.state !== shown && \"invisible\"\n              )}\n            >\n              {label.node}\n            </span>\n          ))}\n        </span>\n      </Button>\n      {hint && (\n        <span id={hint.id} className=\"sr-only\">\n          {hint.text}\n        </span>\n      )}\n      <span aria-live=\"polite\" className=\"sr-only\">\n        {announcement}\n      </span>\n    </>\n  )\n}\n\nexport { ConfirmButton, type ConfirmButtonProps }\n",
      "type": "registry:ui",
      "target": "@ui/sureui/confirm-button.tsx"
    },
    {
      "path": "components/ui/sureui/type-to-confirm.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Checkbox } from \"@/components/ui/checkbox\"\nimport { Input } from \"@/components/ui/input\"\nimport { Label } from \"@/components/ui/label\"\nimport {\n  ConfirmButton,\n  type ConfirmButtonProps,\n} from \"@/components/ui/sureui/confirm-button\"\nimport {\n  isPromise,\n  type ConfirmationOptions,\n} from \"@/components/ui/sureui/confirmation\"\n\ninterface ConfirmChoice {\n  name: string\n  label: React.ReactNode\n  defaultChecked?: boolean\n}\n\ntype ConfirmChoices = Record<string, boolean>\n\ninterface TypeToConfirmProps extends Omit<ConfirmationOptions, \"onConfirm\"> {\n  onConfirm: (choices: ConfirmChoices) => void | Promise<unknown>\n  phrase: string | string[]\n  caseSensitive?: boolean\n  trim?: boolean\n  label?: React.ReactNode | React.ReactNode[]\n  consequences?: React.ReactNode\n  announcements?: {\n    match?: string\n    undo?: string\n    error?: string\n  }\n  confirmLabel?: React.ReactNode\n  undoLabel?: React.ReactNode\n  errorLabel?: React.ReactNode\n  variant?: ConfirmButtonProps[\"variant\"]\n  acknowledgements?: string[]\n  choices?: ConfirmChoice[]\n  renderActions?: (confirmButton: React.ReactElement) => React.ReactNode\n  className?: string\n}\n\nfunction isIdle(button: HTMLElement | null) {\n  return button?.getAttribute(\"data-state\") === \"idle\"\n}\n\nfunction defaultChoices(choices: ConfirmChoice[]): ConfirmChoices {\n  return Object.fromEntries(\n    choices.map((choice) => [choice.name, choice.defaultChecked ?? false])\n  )\n}\n\nfunction ConfirmChoiceList({\n  choices,\n  value,\n  disabled,\n  onChange,\n}: {\n  choices: ConfirmChoice[]\n  value: ConfirmChoices\n  disabled?: boolean\n  onChange: (value: ConfirmChoices) => void\n}) {\n  return choices.map((choice) => (\n    <Label key={choice.name} className=\"items-start leading-normal font-normal\">\n      <Checkbox\n        className=\"mt-0.5\"\n        name={choice.name}\n        checked={value[choice.name] ?? false}\n        disabled={disabled}\n        onCheckedChange={(on) => onChange({ ...value, [choice.name]: on })}\n      />\n      {choice.label}\n    </Label>\n  ))\n}\n\nfunction TypeToConfirm(props: TypeToConfirmProps) {\n  const {\n    onConfirm,\n    onCancel,\n    onConfirmError,\n    undo,\n    pauseUndoOnHover,\n    pauseUndoOnFocus,\n    phrase,\n    caseSensitive = true,\n    trim = false,\n    label,\n    consequences,\n    announcements,\n    confirmLabel = \"Confirm\",\n    undoLabel = \"Undo\",\n    errorLabel,\n    variant = \"default\",\n    acknowledgements = [],\n    choices = [],\n    renderActions,\n    className,\n  } = props\n  const [values, setValues] = React.useState<string[]>([])\n  const [checked, setChecked] = React.useState<number[]>([])\n  const [picked, setPicked] = React.useState(() => defaultChoices(choices))\n  const [pending, setPending] = React.useState(false)\n  const committed = React.useRef(picked)\n  const buttonRef = React.useRef<HTMLButtonElement>(null)\n  const inputId = React.useId()\n\n  const phrases = Array.isArray(phrase) ? phrase : [phrase]\n  const labels = Array.isArray(phrase) && Array.isArray(label) ? label : [label]\n  const normalize = (text: string) => {\n    const trimmed = trim ? text.trim() : text\n    return caseSensitive ? trimmed : trimmed.toLocaleLowerCase()\n  }\n  const matches = phrases.map(\n    (text, index) => normalize(values[index] ?? \"\") === normalize(text)\n  )\n  const ready =\n    matches.every(Boolean) && checked.length === acknowledgements.length\n\n  function run() {\n    const result = onConfirm(committed.current)\n    if (isPromise(result)) {\n      const settle = () => setPending(false)\n      setPending(true)\n      Promise.resolve(result).then(settle, settle)\n    }\n    return result\n  }\n\n  const confirmButton = (\n    <ConfirmButton\n      ref={buttonRef}\n      type=\"button\"\n      variant={variant}\n      undo={undo}\n      undoLabel={undoLabel}\n      errorLabel={errorLabel}\n      announcements={{\n        undo: announcements?.undo,\n        error: announcements?.error,\n      }}\n      pauseUndoOnHover={pauseUndoOnHover}\n      pauseUndoOnFocus={pauseUndoOnFocus}\n      disabled={!ready}\n      className=\"justify-self-start\"\n      onClick={(event) => {\n        if (!isIdle(event.currentTarget)) return\n        committed.current = picked\n        setValues([])\n        setChecked([])\n        setPicked(defaultChoices(choices))\n      }}\n      onConfirm={run}\n      onCancel={onCancel}\n      onConfirmError={onConfirmError}\n    >\n      {confirmLabel}\n    </ConfirmButton>\n  )\n\n  return (\n    <form\n      className={cn(\"grid gap-4\", className)}\n      onSubmit={(event) => {\n        event.preventDefault()\n        if (ready && isIdle(buttonRef.current)) buttonRef.current?.click()\n      }}\n    >\n      {consequences}\n      {phrases.map((text, index) => (\n        <div key={index} className=\"grid gap-2\">\n          <Label\n            htmlFor={`${inputId}-${index}`}\n            className=\"block leading-normal select-text\"\n            onClick={(event) => {\n              if (window.getSelection()?.isCollapsed === false) {\n                event.preventDefault()\n              }\n            }}\n          >\n            {labels[index] ?? (\n              <>\n                Type{\" \"}\n                <code className=\"rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-[0.9em] font-semibold text-foreground\">\n                  {text}\n                </code>{\" \"}\n                to confirm\n              </>\n            )}\n          </Label>\n          <Input\n            id={`${inputId}-${index}`}\n            value={values[index] ?? \"\"}\n            autoComplete=\"off\"\n            spellCheck={false}\n            readOnly={pending}\n            onChange={(event) => {\n              const next = event.target.value\n              setValues((prev) =>\n                phrases.map((_, item) =>\n                  item === index ? next : (prev[item] ?? \"\")\n                )\n              )\n            }}\n          />\n          <p aria-live=\"polite\" className=\"sr-only\">\n            {matches[index] ? (announcements?.match ?? \"Phrase matches\") : \"\"}\n          </p>\n        </div>\n      ))}\n      {acknowledgements.map((text, index) => (\n        <Label key={index} className=\"items-start leading-normal font-normal\">\n          <Checkbox\n            className=\"mt-0.5\"\n            checked={checked.includes(index)}\n            disabled={pending}\n            onCheckedChange={(on) =>\n              setChecked((prev) =>\n                on ? [...prev, index] : prev.filter((item) => item !== index)\n              )\n            }\n          />\n          {text}\n        </Label>\n      ))}\n      <ConfirmChoiceList\n        choices={choices}\n        value={picked}\n        disabled={pending}\n        onChange={setPicked}\n      />\n      {renderActions ? renderActions(confirmButton) : confirmButton}\n    </form>\n  )\n}\n\nexport {\n  TypeToConfirm,\n  ConfirmChoiceList,\n  defaultChoices,\n  type ConfirmChoice,\n  type ConfirmChoices,\n  type TypeToConfirmProps,\n}\n",
      "type": "registry:ui",
      "target": "@ui/sureui/type-to-confirm.tsx"
    },
    {
      "path": "components/ui/sureui/tool-approval.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { Radio } from \"@base-ui/react/radio\"\nimport { RadioGroup } from \"@base-ui/react/radio-group\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button, buttonVariants } from \"@/components/ui/button\"\nimport { Input } from \"@/components/ui/input\"\nimport { ConfirmButton } from \"@/components/ui/sureui/confirm-button\"\nimport {\n  isPromise,\n  type ConfirmationOptions,\n  type GestureOptions,\n} from \"@/components/ui/sureui/confirmation\"\nimport { TypeToConfirm } from \"@/components/ui/sureui/type-to-confirm\"\n\ntype ToolApprovalRisk = \"low\" | \"medium\" | \"high\" | \"critical\"\n\ntype ToolApprovalScope = \"once\" | \"session\" | \"always\"\n\ninterface ToolApprovalPart {\n  state: string\n  approval?: {\n    id: string\n    approved?: boolean\n    reason?: string\n  }\n}\n\ninterface ToolApprovalResponse {\n  id: string\n  approved: boolean\n  reason?: string\n  scope?: ToolApprovalScope\n}\n\ntype ToolApprovalScopeLabels = Partial<\n  Record<ToolApprovalScope, React.ReactNode>\n> & { group?: string }\n\ninterface ToolApprovalOptions\n  extends\n    Pick<ConfirmationOptions, \"undo\" | \"onConfirmError\">,\n    Pick<GestureOptions, \"timeout\" | \"duration\" | \"armDelay\"> {\n  onRespond: (response: ToolApprovalResponse) => void | PromiseLike<unknown>\n  approveLabel?: React.ReactNode\n  denyLabel?: React.ReactNode\n  errorLabel?: React.ReactNode\n  approvedLabel?: React.ReactNode\n  deniedLabel?: React.ReactNode\n  scopes?: ToolApprovalScope[]\n  scopeLabels?: ToolApprovalScopeLabels\n  note?: boolean\n  noteLabel?: string\n  className?: string\n}\n\ninterface ToolApprovalBaseProps extends ToolApprovalOptions {\n  part: ToolApprovalPart\n}\n\ntype ToolApprovalProps = ToolApprovalBaseProps &\n  (\n    | {\n        risk?: \"low\" | \"medium\" | \"high\"\n        phrase?: never\n      }\n    | {\n        risk: \"critical\"\n        phrase: string\n      }\n  )\n\ninterface ToolApprovalBatchProps<\n  P extends ToolApprovalPart = ToolApprovalPart,\n> extends ToolApprovalOptions {\n  parts: P[]\n  risk?: ToolApprovalRisk | ((part: P) => ToolApprovalRisk)\n  phrase?: string\n}\n\ntype ApprovalActionsProps = Omit<\n  ToolApprovalOptions,\n  \"onRespond\" | \"approvedLabel\" | \"deniedLabel\"\n> & {\n  slot: string\n  risk: ToolApprovalRisk\n  phrase: string\n  scope?: ToolApprovalScope\n  onScopeChange: (scope: ToolApprovalScope) => void\n  disabled: boolean\n  onAnswer: (approved: boolean, reason?: string) => void | Promise<unknown>\n}\n\nconst answered = new Set([\n  \"approval-responded\",\n  \"output-available\",\n  \"output-error\",\n  \"output-denied\",\n])\n\nconst risks: ToolApprovalRisk[] = [\"low\", \"medium\", \"high\", \"critical\"]\n\nconst defaultScopeLabels = {\n  group: \"Remember\",\n  once: \"Once\",\n  session: \"This session\",\n  always: \"Always\",\n}\n\nfunction isRequested(part: ToolApprovalPart) {\n  return part.state === \"approval-requested\" && part.approval !== undefined\n}\n\nfunction withChoices(\n  response: ToolApprovalResponse,\n  scope: ToolApprovalScope | undefined,\n  reason: string | undefined\n) {\n  return {\n    ...response,\n    ...(reason && { reason }),\n    ...(scope && { scope }),\n  }\n}\n\nfunction Outcome({\n  slot,\n  approval,\n  approvedLabel,\n  deniedLabel,\n  className,\n}: {\n  slot: string\n  approval: { approved?: boolean; reason?: string }\n  approvedLabel: React.ReactNode\n  deniedLabel: React.ReactNode\n  className?: string\n}) {\n  return (\n    <p\n      data-slot={slot}\n      data-state={approval.approved ? \"approved\" : \"denied\"}\n      className={cn(\n        \"flex min-h-8 items-center text-sm text-muted-foreground\",\n        className\n      )}\n    >\n      {approval.approved ? approvedLabel : deniedLabel}\n      {approval.reason && `: ${approval.reason}`}\n    </p>\n  )\n}\n\nfunction ApprovalActions({\n  slot,\n  risk,\n  phrase,\n  approveLabel,\n  denyLabel,\n  errorLabel,\n  onConfirmError,\n  undo,\n  timeout,\n  duration,\n  armDelay,\n  scopes,\n  scopeLabels,\n  scope,\n  onScopeChange,\n  note,\n  noteLabel = \"Add a note for the agent\",\n  disabled,\n  onAnswer,\n  className,\n}: ApprovalActionsProps) {\n  const [undoing, setUndoing] = React.useState(false)\n  const [text, setText] = React.useState(\"\")\n  const reason = text.trim() || undefined\n  const labels = { ...defaultScopeLabels, ...scopeLabels }\n\n  const scopeGroup =\n    scopes && scopes.length > 0 ? (\n      <RadioGroup\n        data-slot=\"tool-approval-scope\"\n        aria-label={labels.group}\n        value={scope}\n        onValueChange={(value) => onScopeChange(value as ToolApprovalScope)}\n        disabled={undoing || disabled}\n        className=\"flex basis-full flex-wrap gap-1\"\n      >\n        {scopes.map((value) => (\n          <Radio.Root\n            key={value}\n            value={value}\n            className={cn(\n              buttonVariants({ variant: \"ghost\", size: \"sm\" }),\n              \"text-muted-foreground data-checked:bg-muted data-checked:text-foreground data-disabled:pointer-events-none data-disabled:opacity-50\"\n            )}\n          >\n            {labels[value]}\n          </Radio.Root>\n        ))}\n      </RadioGroup>\n    ) : null\n\n  const noteField = note ? (\n    <Input\n      data-slot=\"tool-approval-note\"\n      aria-label={noteLabel}\n      placeholder={noteLabel}\n      value={text}\n      onChange={(event) => setText(event.target.value)}\n      disabled={undoing || disabled}\n      className=\"basis-full\"\n    />\n  ) : null\n\n  function deny() {\n    if (!onConfirmError) return onAnswer(false, reason)\n    try {\n      const result = onAnswer(false, reason)\n      if (isPromise(result)) result.then(undefined, onConfirmError)\n    } catch (error) {\n      onConfirmError(error)\n    }\n  }\n\n  const denyButton = (\n    <Button\n      type=\"button\"\n      variant=\"outline\"\n      disabled={undoing || disabled}\n      onClick={deny}\n    >\n      {denyLabel}\n    </Button>\n  )\n\n  if (risk === \"critical\") {\n    return (\n      <div data-slot={slot} data-state=\"requested\" className={className}>\n        <TypeToConfirm\n          phrase={phrase}\n          variant=\"destructive\"\n          confirmLabel={approveLabel}\n          errorLabel={errorLabel}\n          onConfirm={() => onAnswer(true, reason)}\n          onConfirmError={onConfirmError}\n          renderActions={(approveButton) => (\n            <div className=\"flex flex-wrap gap-2\">\n              {noteField}\n              {scopeGroup}\n              {disabled\n                ? React.cloneElement(\n                    approveButton as React.ReactElement<{ disabled?: boolean }>,\n                    { disabled: true }\n                  )\n                : approveButton}\n              {denyButton}\n            </div>\n          )}\n        />\n      </div>\n    )\n  }\n\n  return (\n    <div\n      data-slot={slot}\n      data-state=\"requested\"\n      className={cn(\"flex flex-wrap gap-2\", className)}\n    >\n      {noteField}\n      {scopeGroup}\n      <ConfirmButton\n        gesture={\n          risk === \"low\" ? \"click\" : risk === \"medium\" ? \"click-again\" : \"hold\"\n        }\n        variant={risk === \"high\" ? \"destructive\" : \"default\"}\n        confirmLabel={risk === \"medium\" ? \"Confirm\" : undefined}\n        announcements={\n          risk === \"medium\" ? { armed: \"Click again to approve\" } : undefined\n        }\n        undo={risk === \"low\" ? undo : undefined}\n        timeout={timeout}\n        duration={duration}\n        armDelay={armDelay}\n        disabled={disabled}\n        errorLabel={errorLabel}\n        onClick={(event) => {\n          if (risk === \"low\" && event.currentTarget.dataset.state === \"idle\") {\n            setUndoing(true)\n          }\n        }}\n        onCancel={() => setUndoing(false)}\n        onConfirm={() => {\n          setUndoing(false)\n          return onAnswer(true, reason)\n        }}\n        onConfirmError={onConfirmError}\n      >\n        {approveLabel}\n      </ConfirmButton>\n      {denyButton}\n    </div>\n  )\n}\n\nfunction ToolApproval(props: ToolApprovalProps) {\n  const {\n    part,\n    onRespond,\n    risk = \"medium\",\n    phrase,\n    approveLabel = risk === \"high\" ? \"Hold to approve\" : \"Approve\",\n    denyLabel = \"Deny\",\n    errorLabel,\n    onConfirmError,\n    approvedLabel = \"Approved\",\n    deniedLabel = \"Denied\",\n    undo = true,\n    timeout,\n    duration,\n    armDelay,\n    scopes,\n    scopeLabels,\n    note,\n    noteLabel,\n    className,\n  } = props\n  const [responding, setResponding] = React.useState(false)\n  const [scope, setScope] = React.useState(scopes?.[0])\n  const respondedRef = React.useRef(false)\n  const approval = part.approval\n\n  if (!approval) return null\n\n  if (answered.has(part.state) && approval.approved !== undefined) {\n    return (\n      <Outcome\n        slot=\"tool-approval\"\n        approval={approval}\n        approvedLabel={approvedLabel}\n        deniedLabel={deniedLabel}\n        className={className}\n      />\n    )\n  }\n\n  if (part.state !== \"approval-requested\") return null\n\n  const id = approval.id\n\n  function respond(approved: boolean, reason?: string) {\n    if (respondedRef.current) return\n    respondedRef.current = true\n    setResponding(true)\n    const release = () => {\n      respondedRef.current = false\n      setResponding(false)\n    }\n    try {\n      const result = onRespond(withChoices({ id, approved }, scope, reason))\n      if (!result) return\n      return Promise.resolve(result).then(undefined, (error: unknown) => {\n        release()\n        throw error\n      })\n    } catch (error) {\n      release()\n      throw error\n    }\n  }\n\n  return (\n    <ApprovalActions\n      slot=\"tool-approval\"\n      risk={risk}\n      phrase={phrase ?? \"\"}\n      approveLabel={approveLabel}\n      denyLabel={denyLabel}\n      errorLabel={errorLabel}\n      onConfirmError={onConfirmError}\n      undo={undo}\n      timeout={timeout}\n      duration={duration}\n      armDelay={armDelay}\n      scopes={scopes}\n      scopeLabels={scopeLabels}\n      scope={scope}\n      onScopeChange={setScope}\n      note={note}\n      noteLabel={noteLabel}\n      disabled={responding}\n      onAnswer={respond}\n      className={className}\n    />\n  )\n}\n\nfunction ToolApprovalBatch<P extends ToolApprovalPart>(\n  props: ToolApprovalBatchProps<P>\n) {\n  const {\n    parts,\n    onRespond,\n    risk = \"medium\",\n    phrase = \"approve all\",\n    approveLabel,\n    denyLabel = \"Deny all\",\n    errorLabel,\n    onConfirmError,\n    approvedLabel = \"Approved\",\n    deniedLabel = \"Denied\",\n    undo = true,\n    timeout,\n    duration,\n    armDelay,\n    scopes,\n    scopeLabels,\n    note,\n    noteLabel,\n    className,\n  } = props\n  const [sent, setSent] = React.useState<ReadonlySet<string>>(() => new Set())\n  const [scope, setScope] = React.useState(scopes?.[0])\n\n  const requested = parts.filter(isRequested)\n  const pending = requested.filter((part) => !sent.has(part.approval!.id))\n\n  if (requested.length === 0) {\n    const approvals = parts.flatMap((part) =>\n      part.approval && answered.has(part.state) ? [part.approval] : []\n    )\n    const first = approvals[0]\n    if (\n      !first ||\n      first.approved === undefined ||\n      approvals.some((approval) => approval.approved !== first.approved)\n    ) {\n      return null\n    }\n    return (\n      <Outcome\n        slot=\"tool-approval-batch\"\n        approval={{ approved: first.approved }}\n        approvedLabel={approvedLabel}\n        deniedLabel={deniedLabel}\n        className={className}\n      />\n    )\n  }\n\n  const level = (pending.length > 0 ? pending : requested).reduce<\n    ToolApprovalRisk | undefined\n  >((highest, part) => {\n    const current = typeof risk === \"function\" ? risk(part) : risk\n    return highest && risks.indexOf(highest) >= risks.indexOf(current)\n      ? highest\n      : current\n  }, undefined)!\n  const ids = pending.map((part) => part.approval!.id)\n\n  function release(released: string[]) {\n    setSent((current) => {\n      const next = new Set(current)\n      for (const id of released) next.delete(id)\n      return next\n    })\n  }\n\n  function respond(approved: boolean, reason?: string) {\n    if (ids.length === 0) return\n    setSent((current) => new Set([...current, ...ids]))\n    const results: PromiseLike<unknown>[] = []\n    for (const [index, id] of ids.entries()) {\n      try {\n        const result = onRespond(withChoices({ id, approved }, scope, reason))\n        if (!result) continue\n        results.push(\n          Promise.resolve(result).then(undefined, (error: unknown) => {\n            release([id])\n            throw error\n          })\n        )\n      } catch (error) {\n        release(ids.slice(index))\n        throw error\n      }\n    }\n    if (results.length > 0) return Promise.all(results)\n  }\n\n  return (\n    <ApprovalActions\n      key={requested.map((part) => part.approval!.id).join(\" \")}\n      slot=\"tool-approval-batch\"\n      risk={level}\n      phrase={phrase}\n      approveLabel={\n        approveLabel ??\n        (level === \"high\" ? \"Hold to approve all\" : \"Approve all\")\n      }\n      denyLabel={denyLabel}\n      errorLabel={errorLabel}\n      onConfirmError={onConfirmError}\n      undo={undo}\n      timeout={timeout}\n      duration={duration}\n      armDelay={armDelay}\n      scopes={scopes}\n      scopeLabels={scopeLabels}\n      scope={scope}\n      onScopeChange={setScope}\n      note={note}\n      noteLabel={noteLabel}\n      disabled={ids.length === 0}\n      onAnswer={respond}\n      className={className}\n    />\n  )\n}\n\nexport {\n  ToolApproval,\n  ToolApprovalBatch,\n  type ToolApprovalBatchProps,\n  type ToolApprovalPart,\n  type ToolApprovalProps,\n  type ToolApprovalResponse,\n  type ToolApprovalRisk,\n  type ToolApprovalScope,\n  type ToolApprovalScopeLabels,\n}\n",
      "type": "registry:ui",
      "target": "@ui/sureui/tool-approval.tsx"
    }
  ],
  "categories": [
    "confirmation",
    "ai"
  ],
  "type": "registry:ui"
}