{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tool",
  "type": "registry:ui",
  "title": "Tool",
  "description": "Tool provides its canonical documented behavior.",
  "dependencies": [
    "lucide-react@0.561.0"
  ],
  "registryDependencies": [
    "https://ghost-ui.com/r/ghost-tokens.json",
    "https://ghost-ui.com/r/chat-model.json",
    "https://ghost-ui.com/r/activity.json",
    "https://ghost-ui.com/r/button.json",
    "https://ghost-ui.com/r/button-group.json",
    "https://ghost-ui.com/r/loader.json",
    "https://ghost-ui.com/r/card.json",
    "https://ghost-ui.com/r/dropdown-menu.json"
  ],
  "files": [
    {
      "path": "src/components/ui/tool.tsx",
      "type": "registry:component",
      "target": "@ui/tool.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { ChevronDown, ShieldQuestion, Wrench } from \"lucide-react\";\n\nimport type { ToolPart } from \"./chat-model\";\nimport {\n  Activity,\n  ActivityContent,\n  ActivityGroup,\n  ActivityTrigger,\n  ActivityDescription,\n  ActivityIcon,\n  ActivityLine,\n  ActivityTitle,\n} from \"./activity\";\nimport { Button } from \"./button\";\nimport { ButtonGroup } from \"./button-group\";\nimport { Card } from \"./card\";\nimport { DropdownMenu } from \"./dropdown-menu\";\nimport { Loader } from \"./loader\";\nimport \"./tool.css\";\n\nexport type ToolState = ToolPart[\"state\"];\nexport type ToolApprovalState =\n  | \"pending\"\n  | \"submitting\"\n  | \"approved\"\n  | \"denied\"\n  | \"failed\"\n  | \"expired\";\n\nconst stateLabels: Record<ToolState | \"unknown\", string> = {\n  \"input-streaming\": \"Receiving input\",\n  \"input-ready\": \"Input ready\",\n  \"approval-required\": \"Approval required\",\n  \"approval-resolved\": \"Approval recorded\",\n  running: \"Running\",\n  \"output-ready\": \"Result ready\",\n  error: \"Failed\",\n  cancelled: \"Cancelled\",\n  unknown: \"Unsupported state\",\n};\n\nfunction stateLabel(value: unknown): string {\n  return typeof value === \"string\" &&\n    Object.prototype.hasOwnProperty.call(stateLabels, value)\n    ? stateLabels[value as ToolState | \"unknown\"]\n    : stateLabels.unknown;\n}\n\nfunction asState(value: unknown): ToolState | \"unknown\" {\n  return typeof value === \"string\" &&\n    Object.prototype.hasOwnProperty.call(stateLabels, value)\n    ? (value as ToolState)\n    : \"unknown\";\n}\n\nfunction activityLineState(state: ToolState | \"unknown\") {\n  if (state === \"error\") return \"error\" as const;\n  if (state === \"cancelled\") return \"cancelled\" as const;\n  if (state === \"output-ready\" || state === \"approval-resolved\")\n    return undefined;\n  if (state === \"running\" || state === \"input-streaming\")\n    return \"active\" as const;\n  return \"pending\" as const;\n}\n\nexport interface ToolProps extends Omit<\n  React.HTMLAttributes<HTMLDivElement>,\n  \"title\" | \"part\"\n> {\n  part?: Pick<ToolPart, \"name\" | \"state\" | \"input\" | \"output\" | \"error\">;\n  name?: string;\n  state?: ToolState;\n  input?: unknown;\n  output?: unknown;\n  error?: string;\n  open?: boolean;\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean, details?: unknown) => void;\n  children?: React.ReactNode;\n}\n\nexport const Tool = React.forwardRef<HTMLDivElement, ToolProps>(function Tool(\n  {\n    part,\n    name,\n    state,\n    input: _input,\n    output: _output,\n    error,\n    open,\n    defaultOpen = false,\n    onOpenChange,\n    className,\n    children,\n    ...props\n  },\n  ref,\n) {\n  const resolvedName = name ?? part?.name ?? \"Tool\";\n  const resolvedState = asState(state ?? part?.state);\n  const resolvedError = error ?? part?.error;\n  const childParts = React.Children.toArray(children);\n  const suppliedHeader = childParts.find(\n    (child) => React.isValidElement(child) && child.type === ToolHeader,\n  );\n  const suppliedError = childParts.some(\n    (child) => React.isValidElement(child) && child.type === ToolError,\n  );\n  const approvals = childParts.filter(\n    (child) => React.isValidElement(child) && child.type === ToolApproval,\n  );\n  const contentChildren = childParts.filter(\n    (child) => child !== suppliedHeader && !approvals.includes(child),\n  );\n  return (\n    <Activity\n      {...props}\n      ref={ref}\n      className={[\"ui-tool\", className].filter(Boolean).join(\" \")}\n      open={open}\n      defaultOpen={defaultOpen}\n      onOpenChange={onOpenChange}\n      data-tool-state={resolvedState}\n      aria-label={props[\"aria-label\"] ?? `${resolvedName} tool`}\n    >\n      <span className=\"ui-sr-only\" role=\"status\" aria-live=\"polite\">\n        {stateLabel(resolvedState)}\n      </span>\n      {suppliedHeader ??\n        (contentChildren.length || resolvedError ? (\n          <ToolHeader name={resolvedName} state={resolvedState} />\n        ) : (\n          <ToolLine\n            name={resolvedName}\n            state={resolvedState}\n            className=\"ui-tool__header\"\n          />\n        ))}\n      <ActivityContent className=\"ui-tool__content\">\n        {contentChildren}\n        {resolvedError && !suppliedError ? (\n          <ToolError>{resolvedError}</ToolError>\n        ) : null}\n      </ActivityContent>\n      {approvals.length ? <ActivityGroup>{approvals}</ActivityGroup> : null}\n    </Activity>\n  );\n});\n\nexport interface ToolHeaderProps extends Omit<\n  React.ComponentPropsWithoutRef<typeof ActivityTrigger>,\n  \"children\"\n> {\n  name: string;\n  state: ToolState | \"unknown\";\n  glyphState?: \"pending\" | \"active\" | \"complete\" | \"error\" | \"cancelled\";\n  icon?: React.ReactNode;\n}\n\nexport const ToolHeader = React.forwardRef<HTMLButtonElement, ToolHeaderProps>(\n  function ToolHeader(\n    { name, state, glyphState, icon, className, ...props },\n    ref,\n  ) {\n    return (\n      <ActivityTrigger\n        {...props}\n        ref={ref}\n        className={[\"ui-tool__header\", className].filter(Boolean).join(\" \")}\n      >\n        <ToolLine\n          name={name}\n          state={state}\n          glyphState={glyphState}\n          icon={icon}\n        />\n      </ActivityTrigger>\n    );\n  },\n);\n\nfunction ToolLine({\n  name,\n  state,\n  glyphState,\n  icon,\n  className,\n}: Pick<ToolHeaderProps, \"name\" | \"state\" | \"glyphState\" | \"icon\"> & {\n  className?: string;\n}) {\n  state = asState(state);\n  return (\n    <ActivityLine\n      className={className}\n      state={glyphState ?? activityLineState(state)}\n    >\n      <ActivityIcon>\n        {icon ??\n          (state === \"approval-required\" ? (\n            <ShieldQuestion />\n          ) : activityLineState(state) ? undefined : (\n            <Wrench />\n          ))}\n      </ActivityIcon>\n      <ActivityTitle className=\"ui-tool__name\">{name}</ActivityTitle>\n      {state === \"unknown\" ? (\n        <ActivityDescription>\n          status unavailable\n        </ActivityDescription>\n      ) : null}\n    </ActivityLine>\n  );\n}\n\nexport interface ToolInputProps extends React.HTMLAttributes<HTMLDivElement> {\n  children?: React.ReactNode;\n}\n\nexport const ToolInput = React.forwardRef<HTMLDivElement, ToolInputProps>(\n  function ToolInput({ children, className, ...props }, ref) {\n    if (children == null) return null;\n    return (\n      <Card.Root\n        {...props}\n        render={<section />}\n        density=\"compact\"\n        data-ai-surface=\"\"\n        ref={ref}\n        className={[\"ui-tool__section\", \"ui-tool__input\", className]\n          .filter(Boolean)\n          .join(\" \")}\n        aria-label={props[\"aria-label\"] ?? \"Tool input\"}\n      >\n        <h3>Input</h3>\n        <div className=\"ui-ai-card-content\">{children}</div>\n      </Card.Root>\n    );\n  },\n);\n\nexport interface ToolOutputProps extends React.HTMLAttributes<HTMLDivElement> {\n  children?: React.ReactNode;\n}\n\nexport const ToolOutput = React.forwardRef<HTMLDivElement, ToolOutputProps>(\n  function ToolOutput({ children, className, ...props }, ref) {\n    if (children == null) return null;\n    return (\n      <Card.Root\n        {...props}\n        render={<section />}\n        density=\"compact\"\n        data-ai-surface=\"\"\n        ref={ref}\n        className={[\"ui-tool__section\", \"ui-tool__output\", className]\n          .filter(Boolean)\n          .join(\" \")}\n        aria-label={props[\"aria-label\"] ?? \"Tool output\"}\n      >\n        <h3>Result</h3>\n        <div className=\"ui-ai-card-content\">{children}</div>\n      </Card.Root>\n    );\n  },\n);\n\nexport interface ToolErrorProps extends React.HTMLAttributes<HTMLDivElement> {\n  children?: React.ReactNode;\n}\n\nexport const ToolError = React.forwardRef<HTMLDivElement, ToolErrorProps>(\n  function ToolError({ children, className, ...props }, ref) {\n    return (\n      <div\n        {...props}\n        ref={ref}\n        className={[\"ui-tool__error\", className].filter(Boolean).join(\" \")}\n        role={props.role ?? \"alert\"}\n      >\n        {children ?? \"The tool failed.\"}\n      </div>\n    );\n  },\n);\n\nexport interface ToolApprovalOption {\n  id: string;\n  label: string;\n  disabled?: boolean;\n}\n\nexport interface ToolApprovalProps extends Omit<\n  React.HTMLAttributes<HTMLDivElement>,\n  \"children\"\n> {\n  state?: ToolApprovalState;\n  /** Caller identity. A new request invalidates late results from the prior one. */\n  approvalId?: string;\n  onApprove?: (optionId?: string) => void | Promise<void>;\n  onDeny?: () => void | Promise<void>;\n  onRetry?: () => void | Promise<void>;\n  error?: string;\n  approveLabel?: string;\n  /** Only choices the host can honor. The host owns scope and persistence. */\n  approveOptions?: readonly ToolApprovalOption[];\n  /** Header actions align right (default); content actions sit below the review target, aligned left. */\n  actionsPlacement?: \"header\" | \"content\";\n  /** A compact approval panel can attach to Composer.secondary. */\n  layout?: \"default\" | \"compact\";\n  /** The decision question shown in place of the generic pending heading. */\n  prompt?: React.ReactNode;\n  disabled?: boolean;\n  children?: React.ReactNode;\n}\n\nexport const ToolApproval = React.forwardRef<HTMLDivElement, ToolApprovalProps>(\n  function ToolApproval(\n    {\n      state = \"pending\",\n      approvalId,\n      onApprove,\n      onDeny,\n      onRetry,\n      error,\n      approveLabel,\n      approveOptions,\n      actionsPlacement = \"header\",\n      layout = \"default\",\n      prompt,\n      disabled = false,\n      children,\n      className,\n      ...props\n    },\n    ref,\n  ) {\n    const mounted = React.useRef(true);\n    const token = React.useRef(0);\n    const lock = React.useRef<\"approve\" | \"deny\" | null>(null);\n    const [pending, setPending] = React.useState<\"approve\" | \"deny\" | null>(\n      null,\n    );\n    const [awaiting, setAwaiting] = React.useState(false);\n    const [failure, setFailure] = React.useState<string | null>(null);\n    const promptId = React.useId();\n    const requestIdentity = approvalId ?? props.id;\n    React.useEffect(() => {\n      mounted.current = true;\n      return () => {\n        mounted.current = false;\n        token.current += 1;\n        lock.current = null;\n      };\n    }, []);\n    React.useEffect(() => {\n      token.current += 1;\n      lock.current = null;\n      setPending(null);\n      setAwaiting(false);\n      setFailure(null);\n    }, [requestIdentity, state]);\n\n    const terminal =\n      state === \"approved\" || state === \"denied\" || state === \"expired\";\n    const failed = state === \"failed\";\n    const externalBusy = state === \"submitting\";\n    const seen = new Set<string>();\n    const options = (Array.isArray(approveOptions) ? approveOptions : []).filter((option): option is ToolApprovalOption => {\n      if (!option || typeof option.id !== \"string\" || !option.id.trim() || typeof option.label !== \"string\" || !option.label.trim() || seen.has(option.id)) return false;\n      seen.add(option.id);\n      return true;\n    });\n    const decide = async (decision: \"approve\" | \"deny\", optionId?: string) => {\n      if (\n        terminal ||\n        failed ||\n        externalBusy ||\n        disabled ||\n        lock.current ||\n        awaiting\n      )\n        return;\n      if (decision === \"approve\" && approveOptions !== undefined && !options.some(option => option.id === optionId && !option.disabled)) return;\n      const callback = decision === \"approve\" ? onApprove : onDeny;\n      if (!callback) return;\n      const currentToken = ++token.current;\n      lock.current = decision;\n      setPending(decision);\n      setFailure(null);\n      try {\n        if (decision === \"approve\") await onApprove?.(optionId);\n        else await onDeny?.();\n        if (!mounted.current || currentToken !== token.current) return;\n        // Retain the synchronous decision lock until caller acknowledgement.\n        // React's awaiting state may not have rendered when this promise settles.\n        setPending(null);\n        setAwaiting(true);\n      } catch (reason) {\n        if (!mounted.current || currentToken !== token.current) return;\n        lock.current = null;\n        setPending(null);\n        setAwaiting(false);\n        setFailure(\n          reason instanceof Error\n            ? reason.message\n            : \"The decision could not be submitted.\",\n        );\n      }\n    };\n\n    const retry = async () => {\n      if (!failed || !onRetry || disabled || lock.current || pending) return;\n      const currentToken = ++token.current;\n      lock.current = \"approve\";\n      setPending(\"approve\");\n      setFailure(null);\n      try {\n        await onRetry();\n        if (!mounted.current || currentToken !== token.current) return;\n        setPending(null);\n        setAwaiting(true);\n      } catch (reason) {\n        if (!mounted.current || currentToken !== token.current) return;\n        lock.current = null;\n        setPending(null);\n        setFailure(\n          reason instanceof Error\n            ? reason.message\n            : \"The decision could not be submitted.\",\n        );\n      }\n    };\n\n    const label =\n      state === \"approved\"\n        ? \"Approved\"\n        : state === \"denied\"\n          ? \"Denied\"\n          : state === \"expired\"\n            ? \"Expired\"\n            : externalBusy || pending\n              ? \"Submitting decision\"\n              : awaiting\n                ? \"Waiting for confirmation\"\n                : state === \"failed\"\n                  ? \"Approval failed\"\n                  : \"Approval required\";\n    const busy = disabled || externalBusy || pending !== null || awaiting;\n    const allowDisabled = busy || !onApprove || (approveOptions !== undefined && !options.some(option => !option.disabled));\n    const allowText = approveLabel ?? \"Allow\";\n    const menuOptions: readonly ToolApprovalOption[] = approveOptions === undefined ? [{ id: \"once\", label: \"Allow once\" }] : options;\n    const allow = (\n      <DropdownMenu.Root>\n        <DropdownMenu.Trigger render={<Button type=\"button\" variant=\"solid\" size=\"xs\" disabled={allowDisabled} trailingIcon={<ChevronDown />} />}>{allowText}</DropdownMenu.Trigger>\n        <DropdownMenu.Portal>\n          <DropdownMenu.Positioner align=\"end\">\n            <DropdownMenu.Popup aria-label=\"Approval scope\">\n              {menuOptions.map(option => <DropdownMenu.Item key={option.id} disabled={allowDisabled || option.disabled} onClick={() => void decide(\"approve\", approveOptions === undefined ? undefined : option.id)}>{option.label}</DropdownMenu.Item>)}\n            </DropdownMenu.Popup>\n          </DropdownMenu.Positioner>\n        </DropdownMenu.Portal>\n      </DropdownMenu.Root>\n    );\n    const deny = <ButtonGroup aria-label=\"Decline\"><Button type=\"button\" variant={actionsPlacement === \"content\" ? \"subtle\" : \"text\"} size=\"xs\" disabled={busy || !onDeny} onClick={() => void decide(\"deny\")}>Deny</Button></ButtonGroup>;\n    const approve = <ButtonGroup aria-label=\"Allow\">{allow}</ButtonGroup>;\n    const actions = !failed && !terminal ? (\n      <ButtonGroup className=\"ui-tool__approval-actions\" aria-label=\"Approval decision\" aria-describedby={promptId}>\n        {actionsPlacement === \"header\" ? <>{deny}{approve}</> : <>{approve}{deny}</>}\n      </ButtonGroup>\n    ) : null;\n    const contentCard = actionsPlacement === \"content\" && React.isValidElement<{ children?: React.ReactNode; className?: string }>(children) && children.type === Card.Root;\n    const content = contentCard ? React.cloneElement(children, {\n      className: [\"ui-tool__approval-card\", children.props.className].filter(Boolean).join(\" \"),\n      children: <>{children.props.children}{actions}</>,\n    }) : children;\n    return (\n      <Card.Root\n        {...props}\n        render={<section />}\n        variant=\"outline\"\n        density=\"compact\"\n        data-ai-surface=\"\"\n        ref={ref}\n        className={[\"ui-tool__approval\", className].filter(Boolean).join(\" \")}\n        aria-label={props[\"aria-label\"] ?? \"Tool approval\"}\n        aria-busy={externalBusy || pending !== null || awaiting || undefined}\n        data-state={state}\n        data-layout={layout}\n        data-actions-placement={actionsPlacement}\n      >\n        <div className=\"ui-tool__approval-layout\">\n        <div className=\"ui-tool__approval-header\">\n          <strong id={promptId} role={terminal || awaiting || externalBusy || pending ? \"status\" : undefined}>\n            {externalBusy || pending || awaiting ? <Loader size={14} /> : null}\n            {state === \"pending\" && !pending && !awaiting && prompt ? prompt : label}\n          </strong>\n          {actionsPlacement === \"header\" ? actions : null}\n        </div>\n        {children ? <div className=\"ui-tool__approval-content ui-ai-card-content\"><div className=\"ui-tool__approval-description\">{content}</div>{actionsPlacement === \"content\" && !contentCard ? actions : null}</div> : null}\n        {actionsPlacement === \"content\" && !children ? actions : null}\n        {failure || failed ? (\n          <ToolError>\n            <span>{failure ?? error ?? \"The decision could not be submitted.\"}</span>\n            {failed && onRetry ? (\n              <Button type=\"button\" variant=\"text\" size=\"xs\" disabled={disabled || pending !== null || awaiting} onClick={() => void retry()}>Retry</Button>\n            ) : null}\n          </ToolError>\n        ) : null}\n        </div>\n      </Card.Root>\n    );\n  },\n);\n\nTool.displayName = \"Tool\";\nToolHeader.displayName = \"ToolHeader\";\nToolInput.displayName = \"ToolInput\";\nToolOutput.displayName = \"ToolOutput\";\nToolError.displayName = \"ToolError\";\nToolApproval.displayName = \"ToolApproval\";\n"
    },
    {
      "path": "src/components/ui/tool.css",
      "type": "registry:file",
      "target": "@ui/tool.css",
      "content": "@import \"./tokens.css\";\n\n.ui-tool {\n  display: grid;\n  min-width: 0;\n  gap: var(--gap-list);\n  color: var(--foreground);\n}\n\n.ui-tool__header { min-width: 0; }\n.ui-tool__name { min-width: 0; overflow-wrap: anywhere; }\n.ui-tool__content { min-width: 0; }\n.ui-tool__approval,\n.ui-tool__section {\n  display: grid;\n  min-width: 0;\n  gap: var(--gap-list);\n}\n\n.ui-tool__section h3 { margin: 0; font-size: var(--font-size-caption); font-weight: var(--font-weight-regular); }\n.ui-tool__section p { margin: 0; color: var(--muted-foreground); font-size: var(--font-size-xs); line-height: var(--space-5); overflow-wrap: anywhere; }\n.ui-tool__error { min-width: 0; padding: var(--space-control-y) var(--space-control-x); border: 1px solid var(--destructive); border-radius: var(--radius-lg); color: var(--destructive); overflow-wrap: anywhere; }\n/* Intrinsic width keeps containment from collapsing an approval inside Message. */\n.ui-tool__approval { container: ui-tool-approval / inline-size; contain-intrinsic-inline-size: 22rem; width: 100%; gap: var(--space-2); font: var(--font-weight-regular) var(--font-size-xs)/var(--space-5) var(--font-sans); }\n.ui-tool__approval-layout { position: relative; display: flow-root; min-width: 0; }\n.ui-tool__approval-layout > .ui-tool__error { margin-block-start: var(--space-2); }\n.ui-tool__approval-header { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2) var(--space-3); min-width: 0; }\n.ui-tool__approval-header > strong { display: block; flex: 1 1 12ch; min-width: 0; font: inherit; overflow-wrap: anywhere; }\n.ui-tool__approval-header .ui-loader { display: inline-flex; margin-inline-end: var(--space-2); vertical-align: text-bottom; }\n.ui-tool__approval-header > .ui-tool__approval-actions { flex: 0 0 auto; max-width: 100%; margin-inline-start: auto; }\n.ui-tool__approval-layout > .ui-tool__approval-actions { display: flex; width: fit-content; max-width: 100%; margin-block-start: var(--space-2); }\n.ui-tool__approval-actions { flex-wrap: wrap; }\n.ui-tool__approval-description { display: grid; min-width: 0; gap: var(--space-2); color: var(--foreground); font: inherit; overflow-wrap: anywhere; }\n.ui-tool__approval-description > small { color: var(--muted-foreground); font-size: var(--font-size-2xs); line-height: var(--space-4); }\n.ui-tool__approval-record { margin: 0; color: var(--muted-foreground); font-size: var(--font-size-2xs); line-height: var(--space-4); overflow-wrap: anywhere; }\n.ui-tool__content > .ui-activity-content__inner { display: grid; gap: var(--space-2); }\n.ui-tool__error { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--space-1) var(--space-3); font: var(--font-weight-regular) var(--font-size-xs)/var(--space-5) var(--font-sans); }\n.ui-tool__error > span { flex: 1 1 12rem; }\n.ui-tool__error > .ui-button { flex: none; }\n/* Flow layout reserves space for long payloads instead of covering them. */\n.ui-tool__approval-content { clear: both; min-width: 0; padding-block-start: var(--space-2); }\n.ui-tool__approval-content > .ui-tool__approval-actions,\n.ui-tool__approval-card > .ui-tool__approval-actions { display: flex; width: fit-content; max-width: 100%; margin-inline-start: 0; margin-block-start: var(--space-2); }\n"
    },
    {
      "path": "src/components/ui/tool-approval.tsx",
      "type": "registry:component",
      "target": "@ui/tool-approval.tsx",
      "content": "/** Approval decisions are distinct from tool execution history. */\nexport { ToolApproval } from \"./tool\";\nexport type { ToolApprovalProps, ToolApprovalState, ToolApprovalOption } from \"./tool\";\n"
    }
  ]
}
