{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "agent-12",
  "title": "Scheduled agent",
  "description": "An agent that runs on a schedule, in words and as a cron badge, with the time to the next run, Pause that greys it out, and its last seven runs as marks, where Run now adds a new one that joins the row.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/live-duration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/mesh-tile.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/replay-button.json",
    "https://ui.ndekocode.dev/r/run-session.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/use-session.json",
    "https://ui.ndekocode.dev/r/use-timeouts.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/agent/agent-12.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useRef, useState } from 'react';\n\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport {\n  useSession,\n  type SessionStep,\n} from '@/registry/ndeko/hooks/use-session';\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\nimport type { RunAgent } from '@/registry/ndeko/lib/agent-run';\nimport {\n  pressedQuietOf,\n  pressedSolidOf,\n  spokenUnless,\n} from '@/registry/ndeko/lib/demonstration';\nimport {\n  CalendarIcon,\n  CheckIcon,\n  ClockIcon,\n  LoaderIcon,\n  MinusIcon,\n  PauseIcon,\n  PlayIcon,\n  XIcon,\n  ZapIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { SPRING } from '@/registry/ndeko/lib/motion-presets';\nimport { restingOf } from '@/registry/ndeko/lib/run-session';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { ClockGate, useLiveNow } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\n\nimport { AgentTile } from './_parts/agent-tile';\nimport { WRITER } from './_parts/crew';\n\nexport type RunMarkStatus = 'done' | 'failed' | 'skipped' | 'running';\n\nexport type RunMark = {\n  id: string;\n  status: RunMarkStatus;\n  /** When the run happened, in a few words: \"Mon 9 Nov\". */\n  when: string;\n  /** What to say of the run, in a few words: \"Done in 38 s\". */\n  note: string;\n};\n\nconst MARK_LOOK: Record<RunMarkStatus, string> = {\n  done: 'bg-success/15 text-success-foreground',\n  failed: 'bg-destructive/15 text-destructive-ink',\n  skipped: 'bg-foreground/[0.06] text-muted-foreground',\n  running: 'bg-info/15 text-info-foreground',\n};\n\nconst MARK_WORD: Record<RunMarkStatus, string> = {\n  done: 'Done',\n  failed: 'Failed',\n  skipped: 'Skipped',\n  running: 'Running',\n};\n\nconst MARK_KEYS = ['ArrowLeft', 'ArrowRight', 'Home', 'End'];\n\nconst MINUTE_MS = 60_000;\n\nconst HOUR_MS = 60 * MINUTE_MS;\n\nfunction markGlyphOf(status: RunMarkStatus) {\n  if (status === 'done') {\n    return <CheckIcon className='size-3' />;\n  }\n  if (status === 'failed') {\n    return <XIcon className='size-3' />;\n  }\n  if (status === 'skipped') {\n    return <MinusIcon className='size-3' />;\n  }\n  return <LoaderIcon className='size-3 animate-spin' />;\n}\n\nfunction markLabelOf(run: RunMark) {\n  const word = MARK_WORD[run.status];\n  return `${run.when}: ${word}. ${run.note}`;\n}\n\nfunction untilOf(milliseconds: number) {\n  if (milliseconds <= 0) {\n    return 'any moment';\n  }\n  const hours = Math.floor(milliseconds / HOUR_MS);\n  const minutes = Math.floor((milliseconds % HOUR_MS) / MINUTE_MS);\n  if (hours > 0) {\n    return `in ${hours}h ${minutes}m`;\n  }\n  const seconds = Math.floor((milliseconds % MINUTE_MS) / 1000);\n  return `in ${minutes}m ${seconds}s`;\n}\n\n/** The clock reads 0 until the page is live, so the countdown holds a dash instead of a wrong time. */\nfunction NextRunIn({ at }: { at: number }) {\n  const now = useLiveNow(1000, true);\n  const hasClock = now > 0;\n  if (!hasClock) {\n    return <span className='tabular-nums'>-</span>;\n  }\n  return <span className='tabular-nums'>{untilOf(at - now)}</span>;\n}\n\nfunction summaryOf(runs: RunMark[]) {\n  const doneCount = runs.filter((run) => run.status === 'done').length;\n  return `${doneCount} of ${runs.length} runs done`;\n}\n\nfunction readoutOf(active: RunMark | undefined, runs: RunMark[]) {\n  if (active) {\n    return markLabelOf(active);\n  }\n  return summaryOf(runs);\n}\n\nfunction tabStopOf(runs: RunMark[], tabStopId: string | null) {\n  const known = runs.find((run) => run.id === tabStopId);\n  if (known) {\n    return known.id;\n  }\n  const last = runs[runs.length - 1];\n  return last?.id;\n}\n\nfunction tabIndexOf(isTabStop: boolean) {\n  if (isTabStop) {\n    return 0;\n  }\n  return -1;\n}\n\nfunction targetIndexOf(key: string, index: number, count: number) {\n  if (key === 'Home') {\n    return 0;\n  }\n  if (key === 'End') {\n    return count - 1;\n  }\n  if (key === 'ArrowLeft') {\n    return Math.max(0, index - 1);\n  }\n  return Math.min(count - 1, index + 1);\n}\n\nfunction markPresenceOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return {\n      initial: { opacity: 0 },\n      animate: { opacity: 1 },\n      exit: { opacity: 0 },\n    };\n  }\n  return {\n    initial: { opacity: 0, x: 14, scale: 0.8 },\n    animate: { opacity: 1, x: 0, scale: 1 },\n    exit: { opacity: 0, x: -14, scale: 0.8 },\n  };\n}\n\ntype RunMarksProps = {\n  runs: RunMark[];\n};\n\nfunction RunMarks({ runs }: RunMarksProps) {\n  const [hoveredId, setHoveredId] = useState<string | null>(null);\n  const [focusedId, setFocusedId] = useState<string | null>(null);\n  const [tabStopId, setTabStopId] = useState<string | null>(null);\n  const groupRef = useRef<HTMLDivElement>(null);\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const presence = markPresenceOf(shouldReduceMotion);\n  const activeId = hoveredId ?? focusedId;\n  const active = runs.find((run) => run.id === activeId);\n  const tabStop = tabStopOf(runs, tabStopId);\n  const order = runs.map((run) => run.id).join(' ');\n  const readout = readoutOf(active, runs);\n\n  function moveFocus(event: React.KeyboardEvent<HTMLDivElement>) {\n    const isMarkKey = MARK_KEYS.includes(event.key);\n    const group = groupRef.current;\n    if (!isMarkKey || !group) {\n      return;\n    }\n    const buttons = Array.from(group.querySelectorAll('button'));\n    const current = buttons.findIndex((button) => button === event.target);\n    if (current < 0) {\n      return;\n    }\n    event.preventDefault();\n    const target = targetIndexOf(event.key, current, buttons.length);\n    buttons[target]?.focus();\n  }\n\n  return (\n    <div className='flex flex-col gap-2'>\n      <div\n        ref={groupRef}\n        role='group'\n        aria-label={`Last ${runs.length} runs`}\n        onKeyDown={moveFocus}\n        className='relative flex items-center'\n      >\n        <AnimatePresence mode='popLayout' initial={false}>\n          {runs.map((run) => (\n            <motion.span\n              key={run.id}\n              layout='position'\n              layoutDependency={order}\n              transition={SPRING}\n              className='inline-flex'\n              {...presence}\n            >\n              <button\n                type='button'\n                aria-label={markLabelOf(run)}\n                tabIndex={tabIndexOf(run.id === tabStop)}\n                onPointerEnter={() => setHoveredId(run.id)}\n                onPointerLeave={() => setHoveredId(null)}\n                onFocus={() => {\n                  setFocusedId(run.id);\n                  setTabStopId(run.id);\n                }}\n                onBlur={() => setFocusedId(null)}\n                className='focus-visible:ring-ring/25 inline-flex size-7 cursor-pointer items-center justify-center rounded-md outline-none focus-visible:ring-[3px]'\n              >\n                <span\n                  className={cn(\n                    'inline-flex size-5 items-center justify-center rounded-[5px] transition-colors duration-200',\n                    MARK_LOOK[run.status]\n                  )}\n                >\n                  <Swap swapKey={run.status}>{markGlyphOf(run.status)}</Swap>\n                </span>\n              </button>\n            </motion.span>\n          ))}\n        </AnimatePresence>\n      </div>\n      <p className='text-muted-foreground min-h-5 text-xs leading-5'>\n        {readout}\n      </p>\n    </div>\n  );\n}\n\nexport type ScheduledAgentProps = {\n  agent: Pick<RunAgent, 'name' | 'series'>;\n  task: string;\n  /** The schedule in words: \"Every weekday at 9:00\". */\n  schedule: string;\n  /** The same schedule as a cron expression: \"0 9 * * 1-5\". */\n  cron: string;\n  /** When the next run starts, in milliseconds. */\n  nextRunAt: number;\n  isPaused: boolean;\n  /** The last runs, oldest first. */\n  runs: RunMark[];\n  onPausedChange?: (isPaused: boolean) => void;\n  onRunNow?: () => void;\n  /** Shows Pause held down, for a demonstration that presses it. */\n  isPausePressed?: boolean;\n  /** Shows Run now held down, for a demonstration that presses it. */\n  isRunPressed?: boolean;\n  className?: string;\n};\n\nconst PAUSE_GLYPH = <PauseIcon />;\n\nconst RESUME_GLYPH = <PlayIcon />;\n\nfunction pauseGlyphOf(isPaused: boolean) {\n  if (isPaused) {\n    return RESUME_GLYPH;\n  }\n  return PAUSE_GLYPH;\n}\n\nfunction pauseLabelOf(isPaused: boolean) {\n  if (isPaused) {\n    return 'Resume';\n  }\n  return 'Pause';\n}\n\ntype StatusBadge = {\n  label: string;\n  variant: React.ComponentProps<typeof Badge>['variant'];\n};\n\nconst PAUSED_BADGE: StatusBadge = { label: 'Paused', variant: 'secondary' };\n\nconst ACTIVE_BADGE: StatusBadge = { label: 'Active', variant: 'success' };\n\nfunction statusBadgeOf(isPaused: boolean) {\n  if (isPaused) {\n    return PAUSED_BADGE;\n  }\n  return ACTIVE_BADGE;\n}\n\nfunction nextLineToneOf(isPaused: boolean) {\n  if (isPaused) {\n    return 'opacity-45';\n  }\n  return 'opacity-100';\n}\n\nexport function ScheduledAgent({\n  agent,\n  task,\n  schedule,\n  cron,\n  nextRunAt,\n  isPaused,\n  runs,\n  onPausedChange,\n  onRunNow,\n  isPausePressed = false,\n  isRunPressed = false,\n  className,\n}: ScheduledAgentProps) {\n  const pauseLabel = pauseLabelOf(isPaused);\n  const badge = statusBadgeOf(isPaused);\n  const isRunning = runs.some((run) => run.status === 'running');\n  const pauseGlyph = pauseGlyphOf(isPaused);\n\n  function togglePause() {\n    onPausedChange?.(!isPaused);\n  }\n\n  return (\n    <section\n      aria-label={`${agent.name}, scheduled`}\n      className={cn(\n        'bg-card hairline-ring ring-border @container flex flex-col gap-4 rounded-xl p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)]',\n        className\n      )}\n    >\n      <header className='flex items-start gap-3'>\n        <AgentTile name={agent.name} series={agent.series} size='lg' />\n        <div className='flex min-w-0 flex-1 flex-col'>\n          <h3 className='truncate text-sm font-medium'>{agent.name}</h3>\n          <p className='text-muted-foreground text-xs leading-5'>{task}</p>\n        </div>\n        <Swap swapKey={badge.label}>\n          <Badge variant={badge.variant}>{badge.label}</Badge>\n        </Swap>\n      </header>\n      <div className='bg-foreground/[0.04] dark:bg-foreground/[0.06] flex flex-col gap-2.5 rounded-lg p-3'>\n        <p className='flex flex-wrap items-center gap-x-2.5 gap-y-1.5 text-[13px]'>\n          <CalendarIcon className='text-muted-foreground size-4 shrink-0' />\n          <span>{schedule}</span>\n          <code className='bg-foreground/[0.06] text-muted-foreground inline-flex h-5 items-center rounded-md px-1.5 font-mono text-[11px]'>\n            {cron}\n          </code>\n        </p>\n        <p\n          className={cn(\n            'flex items-center gap-2.5 text-[13px] transition-opacity duration-200',\n            nextLineToneOf(isPaused)\n          )}\n        >\n          <ClockIcon className='text-muted-foreground size-4 shrink-0' />\n          <span className='text-muted-foreground'>Next run</span>\n          <Swap swapKey={String(isPaused)}>\n            {isPaused && <span>Paused</span>}\n            {!isPaused && <NextRunIn at={nextRunAt} />}\n          </Swap>\n        </p>\n      </div>\n      <RunMarks runs={runs} />\n      <div className='flex flex-wrap items-center gap-2'>\n        <Button\n          type='button'\n          variant='outline'\n          size='sm'\n          onClick={togglePause}\n          className={pressedQuietOf(isPausePressed)}\n        >\n          <Swap swapKey={pauseLabel}>{pauseGlyph}</Swap>\n          <Swap swapKey={pauseLabel}>{pauseLabel}</Swap>\n        </Button>\n        <Button\n          type='button'\n          size='sm'\n          disabled={isRunning}\n          focusableWhenDisabled\n          onClick={onRunNow}\n          className={pressedSolidOf(isRunPressed)}\n        >\n          <ZapIcon />\n          Run now\n        </Button>\n      </div>\n    </section>\n  );\n}\n\nconst SCHEDULE = 'Every weekday at 9:00';\n\nconst CRON = '0 9 * * 1-5';\n\nconst TASK = 'Writes the weekly digest of supplier price changes';\n\nconst NEXT_RUN_IN_MS = 3 * HOUR_MS + 12 * MINUTE_MS;\n\nconst RUN_MS = 1900;\n\nconst MAX_MARKS = 7;\n\ntype ScheduleState = {\n  isPaused: boolean;\n  runs: RunMark[];\n  nextRunNumber: number;\n};\n\ntype ScheduleAction =\n  | { type: 'paused'; isPaused: boolean }\n  | { type: 'run' }\n  | { type: 'finish' }\n  | { type: 'hold' };\n\ntype ScheduleStep = SessionStep<ScheduleState, ScheduleAction>;\n\nconst PAST_RUNS: RunMark[] = [\n  { id: 'run-1', status: 'done', when: 'Fri 30 Oct', note: 'Done in 38 s' },\n  { id: 'run-2', status: 'done', when: 'Mon 2 Nov', note: 'Done in 41 s' },\n  { id: 'run-3', status: 'done', when: 'Tue 3 Nov', note: 'Done in 36 s' },\n  {\n    id: 'run-4',\n    status: 'skipped',\n    when: 'Wed 4 Nov',\n    note: 'The run before it was still going',\n  },\n  { id: 'run-5', status: 'done', when: 'Thu 5 Nov', note: 'Done in 44 s' },\n  {\n    id: 'run-6',\n    status: 'failed',\n    when: 'Fri 6 Nov',\n    note: 'The supplier portal did not answer',\n  },\n  { id: 'run-7', status: 'done', when: 'Mon 9 Nov', note: 'Done in 39 s' },\n];\n\nconst INITIAL: ScheduleState = {\n  isPaused: false,\n  runs: PAST_RUNS,\n  nextRunNumber: 8,\n};\n\nfunction started(state: ScheduleState): ScheduleState {\n  const isBusy = state.runs.some((run) => run.status === 'running');\n  if (isBusy) {\n    return state;\n  }\n  const run: RunMark = {\n    id: `run-${state.nextRunNumber}`,\n    status: 'running',\n    when: 'Today',\n    note: 'Started with Run now',\n  };\n  const runs = [...state.runs, run].slice(-MAX_MARKS);\n  return { ...state, runs, nextRunNumber: state.nextRunNumber + 1 };\n}\n\nfunction finished(state: ScheduleState): ScheduleState {\n  const runs = state.runs.map((run) => {\n    if (run.status !== 'running') {\n      return run;\n    }\n    const status: RunMarkStatus = 'done';\n    return { ...run, status, note: 'Done in 40 s' };\n  });\n  return { ...state, runs };\n}\n\nfunction reducer(state: ScheduleState, action: ScheduleAction): ScheduleState {\n  switch (action.type) {\n    case 'paused':\n      return { ...state, isPaused: action.isPaused };\n    case 'run':\n      return started(state);\n    case 'finish':\n      return finished(state);\n    case 'hold':\n      return state;\n  }\n}\n\nconst SCRIPT: ScheduleStep[] = [\n  {\n    after: 1800,\n    by: 'demo',\n    press: 'pause',\n    action: { type: 'paused', isPaused: true },\n  },\n  {\n    after: 2000,\n    by: 'demo',\n    press: 'pause',\n    action: { type: 'paused', isPaused: false },\n  },\n  {\n    after: 1500,\n    by: 'demo',\n    press: 'run',\n    action: { type: 'run' },\n  },\n  { after: RUN_MS, action: { type: 'finish' } },\n  { after: 3800, action: { type: 'hold' } },\n];\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: restingOf(INITIAL, SCRIPT, reducer),\n  script: SCRIPT,\n  loopAfter: 3000,\n};\n\nfunction announcementOf(state: ScheduleState) {\n  const running = state.runs.some((run) => run.status === 'running');\n  if (running) {\n    return 'A run started';\n  }\n  if (state.isPaused) {\n    return 'The schedule is paused';\n  }\n  return '';\n}\n\nexport default function Agent12() {\n  const { schedule, clearAll } = useTimeouts();\n  const [nextRunAt] = useState(() => Date.now() + NEXT_RUN_IN_MS);\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n  } = useSession(SESSION);\n  const hasRunNow = state.runs.some((run) => run.when === 'Today');\n  const canReplay = hasRunNow && isFinished && !isAutoplaying;\n  const announcement = announcementOf(state);\n\n  function changePaused(isPaused: boolean) {\n    act({ type: 'paused', isPaused });\n  }\n\n  function runNow() {\n    act({ type: 'run' });\n    schedule(() => act({ type: 'finish' }), RUN_MS);\n  }\n\n  function replay() {\n    clearAll();\n    restart();\n  }\n\n  useKeptHeight(ref);\n\n  return (\n    <div\n      ref={ref}\n      className='flex min-h-[27rem] w-full max-w-[30rem] flex-col gap-2'\n    >\n      <ClockGate isActive={isInView}>\n        <ScheduledAgent\n          agent={WRITER}\n          task={TASK}\n          schedule={SCHEDULE}\n          cron={CRON}\n          nextRunAt={nextRunAt}\n          isPaused={state.isPaused}\n          runs={state.runs}\n          onPausedChange={changePaused}\n          onRunNow={runNow}\n          isPausePressed={pressed === 'pause'}\n          isRunPressed={pressed === 'run'}\n        />\n      </ClockGate>\n      <div className='flex h-7 items-center justify-end'>\n        <ReplayButton isShown={canReplay} onReplay={replay} />\n      </div>\n      <LiveRegion message={spokenUnless(isAutoplaying, announcement)} />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/agent/agent-12.tsx"
    },
    {
      "path": "registry/ndeko/components/agent/_parts/agent-tile.tsx",
      "content": "import { seriesColorOf, type SeriesSlot } from '@/registry/ndeko/lib/agent-run';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { MeshTile } from '@/registry/ndeko/ui/mesh-tile';\n\nconst SIZE_CLASS = {\n  sm: 'size-5 rounded-[5px]',\n  md: 'size-6 rounded-md',\n  lg: 'size-8 rounded-lg',\n} as const;\n\nexport type AgentTileSize = keyof typeof SIZE_CLASS;\n\ntype AgentTileProps = {\n  name: string;\n  series: SeriesSlot;\n  size?: AgentTileSize;\n  className?: string;\n};\n\n/** The picture of an agent: a gradient drawn from its name, in its series colour. Its name always sits beside it. */\nexport function AgentTile({\n  name,\n  series,\n  size = 'md',\n  className,\n}: AgentTileProps) {\n  const color = seriesColorOf(series);\n  const sizeClass = SIZE_CLASS[size];\n\n  return (\n    <MeshTile seed={name} color={color} className={cn(sizeClass, className)} />\n  );\n}\n",
      "type": "registry:component",
      "target": "components/agent/_parts/agent-tile.tsx"
    },
    {
      "path": "registry/ndeko/components/agent/_parts/crew.ts",
      "content": "import type { RunAgent } from '@/registry/ndeko/lib/agent-run';\n\nexport const RUN_TITLE = 'Q3 vendor review for Brightmoor Supply';\n\nexport const PLANNER: RunAgent = {\n  id: 'planner',\n  name: 'Planner',\n  series: 1,\n  status: 'idle',\n  role: 'Lead',\n  model: 'Claude Opus',\n};\n\nexport const RESEARCHER: RunAgent = {\n  id: 'researcher',\n  name: 'Researcher',\n  series: 2,\n  status: 'idle',\n  model: 'Claude Sonnet',\n  parentId: 'planner',\n};\n\nexport const WRITER: RunAgent = {\n  id: 'writer',\n  name: 'Writer',\n  series: 3,\n  status: 'idle',\n  model: 'Claude Haiku',\n  parentId: 'planner',\n};\n\nexport const REVIEWER: RunAgent = {\n  id: 'reviewer',\n  name: 'Reviewer',\n  series: 4,\n  status: 'idle',\n  model: 'Claude Sonnet',\n  parentId: 'planner',\n};\n\nexport const CODER: RunAgent = {\n  id: 'coder',\n  name: 'Coder',\n  series: 5,\n  status: 'idle',\n  model: 'Claude Opus',\n  parentId: 'planner',\n};\n\nexport const CREW: RunAgent[] = [PLANNER, RESEARCHER, WRITER, REVIEWER, CODER];\n\nexport const PAGE_ERROR = 'The pricing page refused the reader (403)';\n",
      "type": "registry:component",
      "target": "components/agent/_parts/crew.ts"
    }
  ],
  "categories": [
    "components",
    "agent"
  ],
  "type": "registry:component"
}