{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "application-07",
  "title": "Agent operations",
  "description": "A Sundermere operations page on one run: a header that condenses into a slim bar as the page scrolls, a live graph where an edge draws itself and a dot travels out and back for each call, a monitor with the command that waits for Allow or Deny, a budget bar that passes its 80% mark, a fleet that makes every panel follow the agent you pick, a trace waterfall and a board whose cards travel between lanes, in three columns that fold to one by container width. Plug your backend into onApprove and onDeny.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/animated-size.json",
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/brand-logos.json",
    "https://ui.ndekocode.dev/r/brand-tile.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/company-mark.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/drawn-check.json",
    "https://ui.ndekocode.dev/r/hatch.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/kbd.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-number.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/motion-word-roll.json",
    "https://ui.ndekocode.dev/r/replay-button.json",
    "https://ui.ndekocode.dev/r/run-session.json",
    "https://ui.ndekocode.dev/r/spinner.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-agent-run.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/use-session.json",
    "https://ui.ndekocode.dev/r/utils.json",
    "https://ui.ndekocode.dev/r/wash.json",
    "https://ui.ndekocode.dev/r/words.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/templates/agent-operations/application-07/index.tsx",
      "content": "'use client';\n\nimport { useEffect, useRef } from 'react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { useSession } from '@/registry/ndeko/hooks/use-session';\nimport {\n  pendingApprovalsOf,\n  type RunSnapshot,\n} from '@/registry/ndeko/lib/agent-run';\nimport { spokenUnless } from '@/registry/ndeko/lib/demonstration';\nimport { ClockGate } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\n\nimport { Board } from './board';\nimport { Budget } from './budget';\nimport { DECLINED_LINE, POSTED_LINE } from './data';\nimport { Fleet } from './fleet';\nimport { Graph } from './graph';\nimport { Monitor } from './monitor';\nimport { PageHeader, SlimBar, useCondensedHeader } from './page-header';\nimport {\n  INITIAL,\n  LOOP_AFTER_MS,\n  reducer,\n  RESTING,\n  SCRIPT,\n  type Decision,\n  type ScrollTarget,\n} from './session';\nimport { Waterfall } from './waterfall';\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: RESTING,\n  script: SCRIPT,\n  loopAfter: LOOP_AFTER_MS,\n};\n\n/** The slim bar covers the top of the page once it has condensed: a panel brought into view stops below it. */\nconst SCROLL_MARGIN_PX = 64;\n\n/**\n * One column under 48rem, two from there, three from 64rem. The grid names the places of the panels,\n * so their order in the page stays the order a phone reads them in.\n */\nconst PANELS =\n  \"grid grid-cols-1 gap-4 @3xl:grid-cols-2 @3xl:[grid-template-areas:'monitor_budget'_'graph_graph'_'fleet_fleet'_'waterfall_waterfall'_'board_board'] @5xl:grid-cols-3 @5xl:[grid-template-areas:'monitor_graph_graph'_'budget_waterfall_waterfall'_'fleet_board_board']\";\n\nfunction scrollTopOf(scroller: HTMLElement, target: ScrollTarget) {\n  if (target === 'top') {\n    return 0;\n  }\n  const panel = scroller.querySelector<HTMLElement>('[data-panel=\"fleet\"]');\n  if (!panel) {\n    return 0;\n  }\n  const panelTop = panel.getBoundingClientRect().top;\n  const scrollerTop = scroller.getBoundingClientRect().top;\n  const offset = panelTop - scrollerTop + scroller.scrollTop;\n  return Math.max(0, offset - SCROLL_MARGIN_PX);\n}\n\nfunction scrollBehaviorOf(shouldReduceMotion: boolean): ScrollBehavior {\n  if (shouldReduceMotion) {\n    return 'auto';\n  }\n  return 'smooth';\n}\n\nfunction announcementOf(run: RunSnapshot) {\n  const pending = pendingApprovalsOf(run)[0];\n  if (pending) {\n    return `${pending.title}. Allow or deny it`;\n  }\n  if (run.status === 'done') {\n    return `The run is done. ${POSTED_LINE}`;\n  }\n  if (run.status === 'cancelled') {\n    return DECLINED_LINE;\n  }\n  return '';\n}\n\n/** Nothing calls a network. A real backend plugs in here: the answer of a person to the request that waits on them. */\nexport type Application07Props = {\n  onApprove?: () => void;\n  onDeny?: () => void;\n};\n\nexport default function Application07({\n  onApprove,\n  onDeny,\n}: Application07Props) {\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n    takeOver,\n  } = useSession(SESSION);\n  const scrollerRef = useRef<HTMLDivElement>(null);\n  const { sentinelRef, isCondensed } = useCondensedHeader(scrollerRef);\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const { run, focusAgentId, scrollTarget } = state;\n  const canReplay = isFinished && !isAutoplaying;\n  const message = spokenUnless(isAutoplaying, announcementOf(run));\n\n  useEffect(() => {\n    const scroller = scrollerRef.current;\n    if (!scroller) {\n      return;\n    }\n    const top = scrollTopOf(scroller, scrollTarget);\n    const behavior = scrollBehaviorOf(shouldReduceMotion);\n    scroller.scrollTo({ top, behavior });\n  }, [scrollTarget, shouldReduceMotion]);\n\n  function focusLater(selector: string) {\n    requestAnimationFrame(() => {\n      const target = ref.current?.querySelector<HTMLElement>(selector);\n      target?.focus();\n    });\n  }\n\n  /** The two buttons leave with the request, so the focus goes to what replaces them: the line that says what was decided. */\n  function decide(decision: Decision) {\n    act({ type: 'decided', decision });\n    focusLater('[data-request]');\n    if (decision === 'denied') {\n      onDeny?.();\n      return;\n    }\n    onApprove?.();\n  }\n\n  function pickAgent(id: string) {\n    if (focusAgentId === id) {\n      act({ type: 'focused', id: null });\n      return;\n    }\n    act({ type: 'focused', id });\n  }\n\n  function review() {\n    focusLater('[data-approval]');\n  }\n\n  return (\n    <ClockGate isActive={isInView}>\n      <div\n        ref={ref}\n        className='bg-background text-foreground @container min-h-dvh w-full'\n      >\n        <div className='relative h-dvh min-h-[40rem] overflow-hidden'>\n          <div\n            ref={scrollerRef}\n            onWheel={takeOver}\n            className='relative h-full overflow-y-auto'\n          >\n            <SlimBar\n              run={run}\n              isCondensed={isCondensed}\n              canReplay={canReplay}\n              onReplay={restart}\n            />\n            <div className='mx-auto flex w-full max-w-[90rem] flex-col gap-5 px-3 pb-8 @xl:px-5'>\n              <PageHeader\n                run={run}\n                sentinelRef={sentinelRef}\n                canReplay={canReplay}\n                onReplay={restart}\n              />\n              <div className={PANELS}>\n                <Monitor\n                  run={run}\n                  focusAgentId={focusAgentId}\n                  pressed={pressed}\n                  onDecide={decide}\n                  className='@3xl:[grid-area:monitor]'\n                />\n                <Budget\n                  run={run}\n                  focusAgentId={focusAgentId}\n                  className='@3xl:[grid-area:budget]'\n                />\n                <Graph\n                  run={run}\n                  focusAgentId={focusAgentId}\n                  onFocusAgent={pickAgent}\n                  className='@3xl:[grid-area:graph]'\n                />\n                <Fleet\n                  run={run}\n                  focusAgentId={focusAgentId}\n                  pressed={pressed}\n                  onFocusAgent={pickAgent}\n                  className='@3xl:[grid-area:fleet]'\n                />\n                <Waterfall\n                  run={run}\n                  focusAgentId={focusAgentId}\n                  className='@3xl:[grid-area:waterfall]'\n                />\n                <Board\n                  run={run}\n                  focusAgentId={focusAgentId}\n                  onReview={review}\n                  className='@3xl:[grid-area:board]'\n                />\n              </div>\n            </div>\n          </div>\n          <LiveRegion message={message} />\n        </div>\n      </div>\n    </ClockGate>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-07/index.tsx"
    },
    {
      "path": "registry/ndeko/templates/agent-operations/application-07/agent-parts.tsx",
      "content": "'use client';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport {\n  seriesColorOf,\n  type AgentStatus,\n  type RunAgent,\n} from '@/registry/ndeko/lib/agent-run';\nimport { BookIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { BrandTile } from '@/registry/ndeko/ui/brand-tile';\nimport { MeshTile, type MeshTileSize } from '@/registry/ndeko/ui/mesh-tile';\n\nimport { toolMetaOf } from './data';\n\nexport const AGENT_STATUS_WORD: Record<AgentStatus, string> = {\n  idle: 'Idle',\n  running: 'Running',\n  waiting: 'Waiting on you',\n  failed: 'Failed',\n  done: 'Done',\n};\n\nexport const AGENT_STATUS_WORDS = Object.values(AGENT_STATUS_WORD);\n\nconst DOT_TONE: Record<AgentStatus, string> = {\n  idle: 'bg-muted-foreground/45',\n  running: 'bg-info',\n  waiting: 'bg-warning',\n  failed: 'bg-destructive',\n  done: 'bg-success',\n};\n\ntype StatusDotProps = {\n  status: AgentStatus;\n  isPulsing?: boolean;\n  className?: string;\n};\n\n/** A dot only breathes while its agent really runs, and the page lets a few of them do it at a time. */\nexport function StatusDot({\n  status,\n  isPulsing = false,\n  className,\n}: StatusDotProps) {\n  const isLive = status === 'running' && isPulsing;\n\n  return (\n    <span\n      aria-hidden='true'\n      className={cn(\n        'size-1.5 shrink-0 rounded-full transition-colors duration-200',\n        DOT_TONE[status],\n        isLive && 'animate-pulse',\n        className\n      )}\n    />\n  );\n}\n\ntype AgentTileProps = {\n  agent: Pick<RunAgent, 'name' | 'series'>;\n  size?: MeshTileSize;\n  className?: string;\n};\n\nexport function AgentTile({ agent, size = 'lg', className }: AgentTileProps) {\n  const color = seriesColorOf(agent.series);\n\n  return (\n    <MeshTile\n      seed={agent.name}\n      color={color}\n      size={size}\n      className={className}\n    />\n  );\n}\n\ntype ToolTileProps = {\n  toolId: string;\n  className?: string;\n};\n\n/** A known tool wears its real mark. The ledger has none, so it wears a key cap with a book. */\nexport function ToolTile({ toolId, className }: ToolTileProps) {\n  const tool = toolMetaOf(toolId);\n  if (tool.brand) {\n    return (\n      <BrandTile\n        brand={tool.brand}\n        size='lg'\n        title={tool.name}\n        className={className}\n      />\n    );\n  }\n\n  return (\n    <span\n      title={tool.name}\n      className={cn(\n        'keycap-3d text-muted-foreground inline-flex size-7 shrink-0 items-center justify-center rounded-md',\n        className\n      )}\n    >\n      <BookIcon className='size-3.5' />\n      <span className='sr-only'>{tool.name}</span>\n    </span>\n  );\n}\n\nconst SMALL_COST: Intl.NumberFormatOptions = {\n  style: 'currency',\n  currency: 'USD',\n  minimumFractionDigits: 3,\n  maximumFractionDigits: 3,\n};\n\nconst LARGE_COST: Intl.NumberFormatOptions = {\n  style: 'currency',\n  currency: 'USD',\n  minimumFractionDigits: 2,\n  maximumFractionDigits: 2,\n};\n\n/** Matches `formatCost`: three decimals under a dollar, two above. */\nfunction costFormatOf(usd: number) {\n  if (usd < 1) {\n    return SMALL_COST;\n  }\n  return LARGE_COST;\n}\n\ntype CostFigureProps = {\n  usd: number;\n  className?: string;\n};\n\nexport function CostFigure({ usd, className }: CostFigureProps) {\n  return (\n    <MotionNumber\n      value={usd}\n      format={costFormatOf(usd)}\n      className={cn('tabular-nums', className)}\n    />\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-07/agent-parts.tsx"
    },
    {
      "path": "registry/ndeko/templates/agent-operations/application-07/approval-block.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useId } from 'react';\n\nimport {\n  pendingApprovalsOf,\n  type ApprovalRequest,\n  type RunSnapshot,\n} from '@/registry/ndeko/lib/agent-run';\nimport { pressedSolidOf } from '@/registry/ndeko/lib/demonstration';\nimport { CircleXIcon } from '@/registry/ndeko/lib/icons';\nimport { fadePresence } from '@/registry/ndeko/lib/motion-presets';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Badge, type BadgeProps } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { DrawnCheck } from '@/registry/ndeko/ui/drawn-check';\nimport { Kbd } from '@/registry/ndeko/ui/kbd';\nimport { Spinner } from '@/registry/ndeko/ui/spinner';\n\nimport { DECLINED_LINE, POSTED_LINE } from './data';\nimport type { Decision } from './session';\n\nexport type ApprovalView = 'none' | 'asking' | 'posting' | 'posted' | 'denied';\n\nexport function approvalViewOf(run: RunSnapshot): ApprovalView {\n  const approval = run.approvals[0];\n  if (!approval) {\n    return 'none';\n  }\n  if (approval.status === 'pending') {\n    return 'asking';\n  }\n  if (approval.status === 'denied') {\n    return 'denied';\n  }\n  const call = run.calls.find((candidate) => candidate.id === 'c7');\n  if (call?.status === 'done') {\n    return 'posted';\n  }\n  return 'posting';\n}\n\nconst RISK_WORD: Record<ApprovalRequest['risk'], string> = {\n  low: 'Low risk',\n  medium: 'Medium risk',\n  high: 'High risk',\n};\n\nconst RISK_VARIANT: Record<ApprovalRequest['risk'], BadgeProps['variant']> = {\n  low: 'success',\n  medium: 'warning',\n  high: 'destructive',\n};\n\ntype RequestBodyProps = {\n  approval: ApprovalRequest;\n  pressed: string | null;\n  onDecide: (decision: Decision) => void;\n};\n\nfunction RequestBody({ approval, pressed, onDecide }: RequestBodyProps) {\n  const titleId = useId();\n  const keysId = useId();\n\n  function allow() {\n    onDecide('approved');\n  }\n\n  function deny() {\n    onDecide('denied');\n  }\n\n  function decideFromKeys(event: React.KeyboardEvent<HTMLDivElement>) {\n    if (event.key === 'Escape') {\n      event.preventDefault();\n      deny();\n      return;\n    }\n    const isOnCard = event.target === event.currentTarget;\n    const isEnter = event.key === 'Enter';\n    if (isEnter && isOnCard) {\n      event.preventDefault();\n      allow();\n    }\n  }\n\n  return (\n    <div\n      role='group'\n      tabIndex={0}\n      data-approval\n      aria-labelledby={titleId}\n      aria-describedby={keysId}\n      onKeyDown={decideFromKeys}\n      className='focus-visible:ring-ring/25 flex flex-col gap-3 rounded-xl p-3 outline-none focus-visible:ring-[3px] focus-visible:ring-inset'\n    >\n      <div className='flex items-start gap-2'>\n        <h3 id={titleId} className='min-w-0 flex-1 text-[13px] font-medium'>\n          {approval.title}\n        </h3>\n        <Badge variant={RISK_VARIANT[approval.risk]}>\n          {RISK_WORD[approval.risk]}\n        </Badge>\n      </div>\n      <p className='text-muted-foreground text-xs leading-5'>\n        {approval.detail}\n      </p>\n      <pre className='bg-foreground/[0.04] overflow-x-auto rounded-lg p-2.5 font-mono text-xs leading-relaxed whitespace-pre-wrap'>\n        {approval.command}\n      </pre>\n      <div className='flex flex-wrap items-center gap-2'>\n        <Button\n          type='button'\n          size='sm'\n          onClick={allow}\n          className={pressedSolidOf(pressed === 'allow')}\n        >\n          Allow\n          <Kbd className='ms-0.5'>Enter</Kbd>\n        </Button>\n        <Button type='button' size='sm' variant='outline' onClick={deny}>\n          Deny\n          <Kbd className='ms-0.5'>Esc</Kbd>\n        </Button>\n        <Badge variant='secondary' className='ms-auto'>\n          Illustrative\n        </Badge>\n        <span id={keysId} className='sr-only'>\n          Enter allows, Escape denies\n        </span>\n      </div>\n    </div>\n  );\n}\n\nfunction ResultGlyph({ view }: { view: ApprovalView }) {\n  if (view === 'posting') {\n    return <Spinner aria-hidden='true' />;\n  }\n  if (view === 'denied') {\n    return <CircleXIcon className='text-muted-foreground size-4 shrink-0' />;\n  }\n  return <DrawnCheck tone='success' entrance='draw' />;\n}\n\nfunction resultLineOf(view: ApprovalView) {\n  if (view === 'posting') {\n    return 'Posting the entries';\n  }\n  if (view === 'denied') {\n    return DECLINED_LINE;\n  }\n  return POSTED_LINE;\n}\n\nfunction ResultLine({ view }: { view: ApprovalView }) {\n  return (\n    <div className='flex min-h-11 items-start gap-2.5 p-3 text-[13px] leading-5'>\n      <Swap swapKey={view} className='mt-px'>\n        <ResultGlyph view={view} />\n      </Swap>\n      <p\n        key={view}\n        className='min-w-0 transition-opacity duration-300 starting:opacity-0'\n      >\n        {resultLineOf(view)}\n      </p>\n    </div>\n  );\n}\n\nfunction viewKeyOf(isAsking: boolean) {\n  if (isAsking) {\n    return 'request';\n  }\n  return 'result';\n}\n\ntype ApprovalBlockProps = {\n  run: RunSnapshot;\n  pressed: string | null;\n  onDecide: (decision: Decision) => void;\n};\n\nexport function ApprovalBlock({ run, pressed, onDecide }: ApprovalBlockProps) {\n  const fade = fadePresence();\n  const view = approvalViewOf(run);\n  const pending = pendingApprovalsOf(run)[0];\n  const approval = pending ?? run.approvals[0];\n  if (!approval || view === 'none') {\n    return null;\n  }\n  const isAsking = view === 'asking';\n\n  return (\n    <section\n      data-request\n      tabIndex={-1}\n      aria-label='Request waiting for an answer'\n      className='bg-card hairline-ring ring-border dark:bg-foreground/[0.04] overflow-hidden rounded-xl shadow-[0_1px_2px_rgb(0_0_0/0.04)] transition-opacity duration-300 outline-none starting:opacity-0'\n    >\n      <AnimatedSize>\n        <AnimatePresence initial={false} mode='popLayout'>\n          <motion.div key={viewKeyOf(isAsking)} {...fade}>\n            {isAsking && (\n              <RequestBody\n                approval={approval}\n                pressed={pressed}\n                onDecide={onDecide}\n              />\n            )}\n            {!isAsking && <ResultLine view={view} />}\n          </motion.div>\n        </AnimatePresence>\n      </AnimatedSize>\n    </section>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-07/approval-block.tsx"
    },
    {
      "path": "registry/ndeko/templates/agent-operations/application-07/board.tsx",
      "content": "'use client';\n\nimport { LayoutGroup, motion, type Transition } from 'motion/react';\nimport { useId } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport {\n  elapsedOf,\n  formatDuration,\n  type PlanStep,\n  type RunSnapshot,\n} from '@/registry/ndeko/lib/agent-run';\nimport { springOf } from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { LiveDuration } from '@/registry/ndeko/ui/live-duration';\n\nimport { AgentTile } from './agent-parts';\nimport {\n  agentOf,\n  boardOf,\n  placementOf,\n  type BoardTask,\n  type LaneId,\n} from './model';\nimport { Panel } from './panel';\n\ntype Lane = {\n  id: LaneId;\n  label: string;\n  emptyLine: string;\n};\n\nconst LANES: Lane[] = [\n  { id: 'queued', label: 'Queued', emptyLine: 'Nothing waits' },\n  { id: 'running', label: 'Running', emptyLine: 'Nothing runs' },\n  { id: 'needs', label: 'Needs you', emptyLine: 'Nothing needs you' },\n  { id: 'done', label: 'Done', emptyLine: 'Nothing is done yet' },\n];\n\nfunction dimOf(isDimmed: boolean) {\n  if (isDimmed) {\n    return 'opacity-40';\n  }\n  return undefined;\n}\n\nfunction stepOf(run: RunSnapshot, task: BoardTask): PlanStep | undefined {\n  return run.plan.find((step) => step.id === task.id);\n}\n\nfunction TaskClock({\n  step,\n  lane,\n}: {\n  step: PlanStep | undefined;\n  lane: LaneId;\n}) {\n  if (!step) {\n    return null;\n  }\n  if (lane === 'running') {\n    return (\n      <LiveDuration\n        item={step}\n        isRunning\n        className='text-muted-foreground text-xs'\n      />\n    );\n  }\n  if (lane === 'done') {\n    const elapsed = elapsedOf(step, step.endedAt ?? 0);\n    return (\n      <span className='text-muted-foreground text-xs tabular-nums'>\n        {formatDuration(elapsed)}\n      </span>\n    );\n  }\n  return null;\n}\n\ntype TaskCardProps = {\n  run: RunSnapshot;\n  task: BoardTask;\n  placement: string;\n  travel: Transition;\n  isDimmed: boolean;\n  onReview: () => void;\n};\n\nfunction TaskCard({\n  run,\n  task,\n  placement,\n  travel,\n  isDimmed,\n  onReview,\n}: TaskCardProps) {\n  const owner = agentOf(run, task.ownerId);\n  const step = stepOf(run, task);\n  const isSkipped = task.status === 'skipped';\n\n  return (\n    <motion.li\n      layout='position'\n      layoutId={task.id}\n      layoutDependency={placement}\n      transition={{ layout: travel }}\n    >\n      <div\n        className={cn(\n          'bg-card hairline-ring ring-border dark:bg-foreground/[0.06] flex flex-col gap-2 rounded-lg p-2.5 shadow-[0_1px_2px_rgb(0_0_0/0.04)] transition-opacity duration-200',\n          dimOf(isDimmed)\n        )}\n      >\n        <p\n          className={cn(\n            'text-[13px] leading-snug font-medium',\n            isSkipped && 'text-muted-foreground line-through'\n          )}\n        >\n          {task.title}\n        </p>\n        <div className='flex items-center gap-2 text-xs'>\n          {owner && <AgentTile agent={owner} size='sm' />}\n          <span className='text-muted-foreground min-w-0 flex-1 truncate'>\n            {owner?.name}\n          </span>\n          <TaskClock step={step} lane={task.lane} />\n          {isSkipped && <Badge variant='secondary'>Skipped</Badge>}\n        </div>\n        {task.lane === 'needs' && (\n          <div className='flex items-center gap-2'>\n            <Badge variant='warning'>Waiting on you</Badge>\n            <Button\n              type='button'\n              size='sm'\n              variant='outline'\n              onClick={onReview}\n              className='ms-auto'\n            >\n              Review\n            </Button>\n          </div>\n        )}\n      </div>\n    </motion.li>\n  );\n}\n\ntype BoardProps = {\n  run: RunSnapshot;\n  focusAgentId: string | null;\n  onReview: () => void;\n  className?: string;\n};\n\nexport function Board({ run, focusAgentId, onReview, className }: BoardProps) {\n  const groupId = useId();\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const travel = springOf(shouldReduceMotion);\n  const tasks = boardOf(run);\n  const placement = placementOf(tasks);\n  const hasFocus = focusAgentId !== null;\n  const isEmpty = tasks.length === 0;\n\n  return (\n    <Panel panel='board' title='Board' className={cn('@container', className)}>\n      {isEmpty && (\n        <p className='text-muted-foreground py-6 text-center text-xs'>\n          The plan shows here as soon as the coordinator has made it.\n        </p>\n      )}\n      {!isEmpty && (\n        <LayoutGroup id={groupId}>\n          <div className='grid grid-cols-1 gap-2 @lg:grid-cols-2 @3xl:grid-cols-4'>\n            {LANES.map((lane) => {\n              const inLane = tasks.filter((task) => task.lane === lane.id);\n              const isLaneEmpty = inLane.length === 0;\n              return (\n                <section\n                  key={lane.id}\n                  className='bg-foreground/[0.03] dark:bg-foreground/[0.05] flex min-w-0 flex-col gap-1.5 rounded-lg p-1.5'\n                >\n                  <h3 className='text-muted-foreground flex h-6 items-center gap-1.5 px-1.5 text-xs font-medium'>\n                    {lane.label}\n                    <LayoutGroup inherit={false}>\n                      <MotionNumber value={inLane.length} />\n                    </LayoutGroup>\n                  </h3>\n                  <ul className='flex flex-col gap-1.5'>\n                    {inLane.map((task) => (\n                      <TaskCard\n                        key={task.id}\n                        run={run}\n                        task={task}\n                        placement={placement}\n                        travel={travel}\n                        isDimmed={hasFocus && focusAgentId !== task.ownerId}\n                        onReview={onReview}\n                      />\n                    ))}\n                  </ul>\n                  {isLaneEmpty && (\n                    <p className='text-muted-foreground px-1.5 pb-1 text-xs'>\n                      {lane.emptyLine}\n                    </p>\n                  )}\n                </section>\n              );\n            })}\n          </div>\n        </LayoutGroup>\n      )}\n    </Panel>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-07/board.tsx"
    },
    {
      "path": "registry/ndeko/templates/agent-operations/application-07/budget.tsx",
      "content": "'use client';\n\nimport type { CSSProperties } from 'react';\n\nimport {\n  formatCost,\n  seriesColorOf,\n  type RunAgent,\n  type RunSnapshot,\n} from '@/registry/ndeko/lib/agent-run';\nimport { TriangleAlertIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Fold } from '@/registry/ndeko/ui/chat-motion';\n\nimport { AgentTile, CostFigure } from './agent-parts';\nimport { ALERT_SHARE, BUDGET_USD } from './data';\nimport { Panel } from './panel';\n\nconst PERCENT = new Intl.NumberFormat('en-US', {\n  style: 'percent',\n  maximumFractionDigits: 0,\n});\n\nfunction shareOf(usd: number) {\n  return Math.min(1, usd / BUDGET_USD);\n}\n\ntype Slice = {\n  agent: RunAgent;\n  start: number;\n  share: number;\n};\n\nfunction slicesOf(agents: RunAgent[]): Slice[] {\n  const slices: Slice[] = [];\n  let start = 0;\n  for (const agent of agents) {\n    const share = shareOf(agent.costUsd ?? 0);\n    slices.push({ agent, start, share });\n    start += share;\n  }\n  return slices;\n}\n\nfunction sliceStyleOf(slice: Slice): CSSProperties {\n  const offset = slice.start * 100;\n  return {\n    backgroundColor: seriesColorOf(slice.agent.series),\n    transform: `translateX(${offset}%) scaleX(${slice.share})`,\n  };\n}\n\nfunction dimOf(isDimmed: boolean) {\n  if (isDimmed) {\n    return 'opacity-40';\n  }\n  return undefined;\n}\n\ntype BudgetProps = {\n  run: RunSnapshot;\n  focusAgentId: string | null;\n  className?: string;\n};\n\nexport function Budget({ run, focusAgentId, className }: BudgetProps) {\n  const total = run.usage.costUsd;\n  const slices = slicesOf(run.agents);\n  const share = shareOf(total);\n  const isOver = share >= ALERT_SHARE;\n  const left = Math.max(0, BUDGET_USD - total);\n  const hasFocus = focusAgentId !== null;\n\n  return (\n    <Panel\n      panel='budget'\n      title='Budget'\n      className={className}\n      meta={<Badge variant='secondary'>Illustrative</Badge>}\n    >\n      <div className='flex items-baseline gap-2'>\n        <CostFigure usd={total} className='text-2xl leading-8 font-semibold' />\n        <span className='text-muted-foreground text-xs tabular-nums'>\n          of {formatCost(BUDGET_USD)}\n        </span>\n      </div>\n      <div className='flex flex-col gap-1.5'>\n        <div\n          role='img'\n          aria-label={`${PERCENT.format(share)} of the budget spent`}\n          className='bg-foreground/10 relative h-2 overflow-hidden rounded-full [direction:ltr]'\n        >\n          {slices.map((slice) => (\n            <span\n              key={slice.agent.id}\n              style={sliceStyleOf(slice)}\n              className='absolute inset-0 origin-left transition-transform duration-500 ease-(--ease-out-strong)'\n            />\n          ))}\n          <span\n            aria-hidden='true'\n            style={{ left: `${ALERT_SHARE * 100}%` }}\n            className='bg-foreground/40 absolute inset-y-0 w-px'\n          />\n        </div>\n        <p className='text-muted-foreground flex justify-between text-xs tabular-nums'>\n          <span>{PERCENT.format(share)} spent</span>\n          <span>Alert at {PERCENT.format(ALERT_SHARE)}</span>\n        </p>\n      </div>\n      <Fold open={isOver}>\n        <p className='bg-warning/10 text-warning-foreground flex items-start gap-2 rounded-lg p-2.5 text-xs leading-5'>\n          <TriangleAlertIcon className='mt-0.5 size-3.5 shrink-0' />\n          Past 80% of the budget. {formatCost(left)} is left for this run.\n        </p>\n      </Fold>\n      <ul aria-label='Spend by agent' className='flex flex-col gap-1'>\n        {run.agents.map((agent) => {\n          const isDimmed = hasFocus && focusAgentId !== agent.id;\n          return (\n            <li\n              key={agent.id}\n              className={cn(\n                'flex h-7 items-center gap-2.5 text-[13px] transition-opacity duration-200',\n                dimOf(isDimmed)\n              )}\n            >\n              <AgentTile agent={agent} size='sm' />\n              <span className='min-w-0 flex-1 truncate'>{agent.name}</span>\n              <CostFigure\n                usd={agent.costUsd ?? 0}\n                className='text-muted-foreground text-xs'\n              />\n            </li>\n          );\n        })}\n      </ul>\n    </Panel>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-07/budget.tsx"
    },
    {
      "path": "registry/ndeko/templates/agent-operations/application-07/data.ts",
      "content": "import type {\n  ApprovalRequest,\n  PlanStep,\n  RunAgent,\n  SeriesSlot,\n} from '@/registry/ndeko/lib/agent-run';\nimport type { BrandSlug } from '@/registry/ndeko/lib/brand-logos';\n\nexport const BRAND = { name: 'Sundermere' };\n\nexport const RUN_ID = 'SM-0412';\n\nexport const RUN_TITLE = 'March close, three depots';\n\nexport const RUN_NOTE = 'Kinshasa, Lubumbashi and Goma';\n\n/** The money the run may spend. The figure is illustrative. */\nexport const BUDGET_USD = 1;\n\nexport const ALERT_SHARE = 0.8;\n\n/** The time axis of the waterfall: the demonstration run ends well inside it. */\nexport const WINDOW_MS = 30_000;\n\nexport type AgentId =\n  'coordinator' | 'collector' | 'matcher' | 'writer' | 'reviewer';\n\nexport const AGENT_ORDER: AgentId[] = [\n  'coordinator',\n  'collector',\n  'matcher',\n  'writer',\n  'reviewer',\n];\n\nconst LEAD: AgentId = 'coordinator';\n\nfunction workerOf(\n  id: AgentId,\n  name: string,\n  series: SeriesSlot,\n  role: string,\n  model: string\n): RunAgent {\n  return {\n    id,\n    name,\n    series,\n    status: 'idle',\n    role,\n    model,\n    parentId: LEAD,\n    costUsd: 0,\n  };\n}\n\nexport const AGENTS: RunAgent[] = [\n  {\n    id: 'coordinator',\n    name: 'Coordinator',\n    series: 1,\n    status: 'idle',\n    role: 'Leads the run',\n    model: 'Claude Opus',\n    costUsd: 0,\n  },\n  workerOf('collector', 'Collector', 2, 'Reads the exports', 'Claude Haiku'),\n  workerOf('matcher', 'Matcher', 4, 'Matches payments', 'Claude Sonnet'),\n  workerOf('writer', 'Writer', 3, 'Drafts the note', 'Claude Sonnet'),\n  workerOf('reviewer', 'Reviewer', 5, 'Checks the figures', 'Claude Opus'),\n];\n\nexport type StepId = 'collect' | 'match' | 'draft' | 'review' | 'post';\n\nexport type PlanSeed = {\n  id: StepId;\n  title: string;\n  ownerId: AgentId;\n  /** How long a step usually takes: its part of the time strip fills over this long. */\n  expectedMs: number;\n};\n\nexport const PLAN_SEEDS: PlanSeed[] = [\n  {\n    id: 'collect',\n    title: 'Collect the depot exports',\n    ownerId: 'collector',\n    expectedMs: 4000,\n  },\n  {\n    id: 'match',\n    title: 'Match payments to invoices',\n    ownerId: 'matcher',\n    expectedMs: 5000,\n  },\n  {\n    id: 'draft',\n    title: 'Draft the close note',\n    ownerId: 'writer',\n    expectedMs: 3600,\n  },\n  {\n    id: 'review',\n    title: 'Review the figures',\n    ownerId: 'reviewer',\n    expectedMs: 2600,\n  },\n  {\n    id: 'post',\n    title: 'Post the journal entries',\n    ownerId: 'coordinator',\n    expectedMs: 3200,\n  },\n];\n\nexport const PLAN_STEPS: PlanStep[] = PLAN_SEEDS.map((seed) => ({\n  id: seed.id,\n  title: seed.title,\n  status: 'upcoming',\n}));\n\nconst FALLBACK_SEED = PLAN_SEEDS[0];\n\nexport function planSeedOf(id: string) {\n  const seed = PLAN_SEEDS.find((candidate) => candidate.id === id);\n  return seed ?? FALLBACK_SEED;\n}\n\nexport const AGENT_TASK: Record<string, string> = {\n  coordinator: 'Planning the close',\n  collector: 'Reading the three depot exports',\n  matcher: 'Matching 412 payments to invoices',\n  writer: 'Drafting the close note',\n  reviewer: 'Checking totals against the checklist',\n};\n\nexport const POSTING_TASK = 'Posting the journal entries';\n\nexport type ToolId = 'drive' | 'postgres' | 'notion' | 'linear' | 'ledger';\n\nexport type ToolMeta = {\n  id: ToolId;\n  name: string;\n  /** A tool with no known mark wears a plain key cap. */\n  brand?: BrandSlug;\n};\n\nexport const TOOL_META: ToolMeta[] = [\n  { id: 'drive', name: 'Google Drive', brand: 'googledrive' },\n  { id: 'postgres', name: 'PostgreSQL', brand: 'postgresql' },\n  { id: 'notion', name: 'Notion', brand: 'notion' },\n  { id: 'linear', name: 'Linear', brand: 'linear' },\n  { id: 'ledger', name: 'Ledger' },\n];\n\nconst FALLBACK_TOOL = TOOL_META[0];\n\nexport function toolMetaOf(id: string) {\n  const tool = TOOL_META.find((candidate) => candidate.id === id);\n  return tool ?? FALLBACK_TOOL;\n}\n\nexport type CallSeed = {\n  id: string;\n  toolId: ToolId;\n  label: string;\n  agentId: AgentId;\n  stepId: StepId;\n  inputTokens: number;\n  outputTokens: number;\n  costUsd: number;\n};\n\n/** Invented exports, counts and costs. The figures are illustrative. */\nexport const CALLS: CallSeed[] = [\n  {\n    id: 'c1',\n    toolId: 'drive',\n    label: 'Read the Kinshasa export',\n    agentId: 'collector',\n    stepId: 'collect',\n    inputTokens: 9800,\n    outputTokens: 700,\n    costUsd: 0.021,\n  },\n  {\n    id: 'c2',\n    toolId: 'drive',\n    label: 'Read the Lubumbashi export',\n    agentId: 'collector',\n    stepId: 'collect',\n    inputTokens: 8900,\n    outputTokens: 650,\n    costUsd: 0.019,\n  },\n  {\n    id: 'c3',\n    toolId: 'drive',\n    label: 'Read the Goma export',\n    agentId: 'collector',\n    stepId: 'collect',\n    inputTokens: 8100,\n    outputTokens: 600,\n    costUsd: 0.017,\n  },\n  {\n    id: 'c4',\n    toolId: 'postgres',\n    label: 'Match 412 payments',\n    agentId: 'matcher',\n    stepId: 'match',\n    inputTokens: 21500,\n    outputTokens: 2200,\n    costUsd: 0.214,\n  },\n  {\n    id: 'c5',\n    toolId: 'notion',\n    label: 'Write the close note',\n    agentId: 'writer',\n    stepId: 'draft',\n    inputTokens: 12400,\n    outputTokens: 3100,\n    costUsd: 0.131,\n  },\n  {\n    id: 'c6',\n    toolId: 'linear',\n    label: 'Read the close checklist',\n    agentId: 'reviewer',\n    stepId: 'review',\n    inputTokens: 15200,\n    outputTokens: 1200,\n    costUsd: 0.158,\n  },\n  {\n    id: 'c7',\n    toolId: 'ledger',\n    label: 'Post 3 journal entries',\n    agentId: 'coordinator',\n    stepId: 'post',\n    inputTokens: 6800,\n    outputTokens: 900,\n    costUsd: 0.152,\n  },\n];\n\nconst FALLBACK_CALL = CALLS[0];\n\nexport function callSeedOf(id: string) {\n  const seed = CALLS.find((candidate) => candidate.id === id);\n  return seed ?? FALLBACK_CALL;\n}\n\nexport const PLAN_USAGE = {\n  inputTokens: 5400,\n  outputTokens: 1100,\n  costUsd: 0.118,\n};\n\n/** What an agent has spent once a call of the run ends: the running sum, worked out once. */\nfunction agentCostsAfterCalls() {\n  const spent: Record<string, number> = { coordinator: PLAN_USAGE.costUsd };\n  const after: Record<string, number> = {};\n  for (const call of CALLS) {\n    const before = spent[call.agentId] ?? 0;\n    const total = before + call.costUsd;\n    spent[call.agentId] = total;\n    after[call.id] = total;\n  }\n  return after;\n}\n\nexport const AGENT_COST_AFTER = agentCostsAfterCalls();\n\nexport const JOURNAL_REQUEST: ApprovalRequest = {\n  id: 'journal',\n  title: 'Post 3 journal entries to the ledger',\n  risk: 'medium',\n  status: 'pending',\n  agentId: 'coordinator',\n  detail:\n    'Changes the books of March in all three depots. A credit entry can reverse it.',\n  command: 'ledger post --period 2026-03 --depots kin,lub,goma --entries 3',\n  scope: 'once',\n};\n\nexport type NodePlace = {\n  x: number;\n  y: number;\n};\n\n/** Places on the graph, as a share of its width and of its height. */\nexport const AGENT_PLACE: Record<AgentId, NodePlace> = {\n  coordinator: { x: 50, y: 14 },\n  collector: { x: 14, y: 52 },\n  matcher: { x: 38, y: 52 },\n  writer: { x: 62, y: 52 },\n  reviewer: { x: 86, y: 52 },\n};\n\nexport const TOOL_PLACE: Record<ToolId, NodePlace> = {\n  drive: { x: 14, y: 85 },\n  postgres: { x: 38, y: 85 },\n  notion: { x: 62, y: 85 },\n  linear: { x: 86, y: 85 },\n  ledger: { x: 86, y: 14 },\n};\n\n/** The agent each tool belongs to on the graph: the edge to it starts there. */\nexport const TOOL_OWNER: Record<ToolId, AgentId> = {\n  drive: 'collector',\n  postgres: 'matcher',\n  notion: 'writer',\n  linear: 'reviewer',\n  ledger: 'coordinator',\n};\n\nexport const BUS_Y = 33;\n\nexport const DECLINED_LINE =\n  'Not posted. The entries stay in draft and the run stopped here';\n\nexport const POSTED_LINE = '3 journal entries posted to the ledger';\n",
      "type": "registry:component",
      "target": "components/templates/application-07/data.ts"
    },
    {
      "path": "registry/ndeko/templates/agent-operations/application-07/fleet.tsx",
      "content": "'use client';\n\nimport { WordRoll } from '@/components/core/word-roll';\nimport {\n  elapsedOf,\n  formatDuration,\n  type RunAgent,\n  type RunSnapshot,\n} from '@/registry/ndeko/lib/agent-run';\nimport { pressedQuietOf } from '@/registry/ndeko/lib/demonstration';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { countOf } from '@/registry/ndeko/lib/words';\nimport { LiveDuration } from '@/registry/ndeko/ui/live-duration';\n\nimport {\n  AGENT_STATUS_WORD,\n  AGENT_STATUS_WORDS,\n  AgentTile,\n  CostFigure,\n  StatusDot,\n} from './agent-parts';\nimport { Panel } from './panel';\n\n/** A page lets this many dots pulse at once. Past it, a running agent is told by its colour and its word. */\nconst MAX_PULSING = 3;\n\nfunction pulsingIdsOf(agents: RunAgent[]) {\n  const running = agents.filter((agent) => agent.status === 'running');\n  const pulsing = running.slice(0, MAX_PULSING);\n  const ids = pulsing.map((agent) => agent.id);\n  return new Set(ids);\n}\n\nfunction rowToneOf(isPicked: boolean) {\n  if (isPicked) {\n    return 'bg-foreground/[0.07]';\n  }\n  return 'hover:bg-foreground/[0.04]';\n}\n\nfunction dimOf(isDimmed: boolean) {\n  if (isDimmed) {\n    return 'opacity-40';\n  }\n  return undefined;\n}\n\nfunction AgentClock({ agent }: { agent: RunAgent }) {\n  if (agent.status === 'running') {\n    return <LiveDuration item={agent} isRunning className='w-10 text-end' />;\n  }\n  if (agent.status === 'done') {\n    const elapsed = elapsedOf(agent, agent.endedAt ?? 0);\n    return (\n      <span className='w-10 text-end tabular-nums'>\n        {formatDuration(elapsed)}\n      </span>\n    );\n  }\n  return <span className='w-10' />;\n}\n\ntype FleetRowProps = {\n  agent: RunAgent;\n  isPicked: boolean;\n  isDimmed: boolean;\n  isPulsing: boolean;\n  isPressed: boolean;\n  onPick: (id: string) => void;\n};\n\nfunction FleetRow({\n  agent,\n  isPicked,\n  isDimmed,\n  isPulsing,\n  isPressed,\n  onPick,\n}: FleetRowProps) {\n  const task = agent.task ?? 'Not started';\n\n  function pick() {\n    onPick(agent.id);\n  }\n\n  return (\n    <li>\n      <button\n        type='button'\n        aria-pressed={isPicked}\n        onClick={pick}\n        className={cn(\n          'focus-visible:ring-ring/25 flex w-full cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-start transition-[background-color,opacity,scale] duration-150 outline-none focus-visible:ring-[3px]',\n          rowToneOf(isPicked),\n          dimOf(isDimmed),\n          pressedQuietOf(isPressed)\n        )}\n      >\n        <AgentTile agent={agent} />\n        <span className='flex min-w-0 flex-1 flex-col leading-tight'>\n          <span className='flex min-w-0 items-baseline gap-1.5 text-[13px]'>\n            <span className='truncate font-medium'>{agent.name}</span>\n            <span className='text-muted-foreground hidden truncate text-xs @md:inline'>\n              {agent.role}\n            </span>\n          </span>\n          <span\n            key={task}\n            className='text-muted-foreground truncate text-xs transition-opacity duration-300 starting:opacity-0'\n          >\n            {task}\n          </span>\n        </span>\n        <span className='flex shrink-0 flex-col items-end gap-0.5 text-xs'>\n          <span className='flex items-center gap-1.5'>\n            <StatusDot status={agent.status} isPulsing={isPulsing} />\n            <WordRoll\n              text={AGENT_STATUS_WORD[agent.status]}\n              labels={AGENT_STATUS_WORDS}\n            />\n          </span>\n          <span className='text-muted-foreground flex items-center gap-1.5 tabular-nums'>\n            <AgentClock agent={agent} />\n            <CostFigure usd={agent.costUsd ?? 0} />\n          </span>\n        </span>\n      </button>\n    </li>\n  );\n}\n\ntype FleetProps = {\n  run: RunSnapshot;\n  focusAgentId: string | null;\n  pressed: string | null;\n  onFocusAgent: (id: string) => void;\n  className?: string;\n};\n\nexport function Fleet({\n  run,\n  focusAgentId,\n  pressed,\n  onFocusAgent,\n  className,\n}: FleetProps) {\n  const pulsing = pulsingIdsOf(run.agents);\n  const hasFocus = focusAgentId !== null;\n  const working = run.agents.filter((agent) => agent.status === 'running');\n\n  return (\n    <Panel\n      panel='fleet'\n      title='Fleet'\n      className={cn('@container', className)}\n      meta={\n        <span className='text-muted-foreground text-xs tabular-nums'>\n          {countOf(run.agents.length, 'agent')}, {working.length} at work\n        </span>\n      }\n    >\n      <ul aria-label='Agents of this run' className='-mx-2 flex flex-col'>\n        {run.agents.map((agent) => (\n          <FleetRow\n            key={agent.id}\n            agent={agent}\n            isPicked={focusAgentId === agent.id}\n            isDimmed={hasFocus && focusAgentId !== agent.id}\n            isPulsing={pulsing.has(agent.id)}\n            isPressed={pressed === `fleet-${agent.id}`}\n            onPick={onFocusAgent}\n          />\n        ))}\n      </ul>\n    </Panel>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-07/fleet.tsx"
    },
    {
      "path": "registry/ndeko/templates/agent-operations/application-07/graph.tsx",
      "content": "'use client';\n\nimport type { CSSProperties } from 'react';\n\nimport type { RunSnapshot, ToolCall } from '@/registry/ndeko/lib/agent-run';\nimport {\n  CircleCheckIcon,\n  CircleXIcon,\n  HandIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { countOf } from '@/registry/ndeko/lib/words';\n\nimport { AGENT_STATUS_WORD, AgentTile, ToolTile } from './agent-parts';\nimport {\n  AGENT_ORDER,\n  AGENT_PLACE,\n  BUS_Y,\n  TOOL_META,\n  TOOL_OWNER,\n  TOOL_PLACE,\n  toolMetaOf,\n  type AgentId,\n  type NodePlace,\n  type ToolId,\n} from './data';\nimport { callsOfAgent } from './model';\nimport { Panel } from './panel';\n\ntype Axis = 'vertical' | 'horizontal';\n\ntype EdgeSpec = {\n  axis: Axis;\n  style: CSSProperties;\n};\n\nconst LEAD: AgentId = 'coordinator';\n\nconst WORKERS = AGENT_ORDER.filter((id) => id !== LEAD);\n\nconst LEFTMOST = AGENT_PLACE[WORKERS[0]].x;\n\nconst RIGHTMOST = AGENT_PLACE[WORKERS[WORKERS.length - 1]].x;\n\nfunction percent(value: number) {\n  return `${value}%`;\n}\n\nfunction verticalEdge(x: number, from: number, to: number): EdgeSpec {\n  return {\n    axis: 'vertical',\n    style: { left: percent(x), top: percent(from), height: percent(to - from) },\n  };\n}\n\nfunction horizontalEdge(y: number, from: number, to: number): EdgeSpec {\n  return {\n    axis: 'horizontal',\n    style: { top: percent(y), left: percent(from), width: percent(to - from) },\n  };\n}\n\nconst LEAD_PLACE = AGENT_PLACE[LEAD];\n\nconst SPINE = verticalEdge(LEAD_PLACE.x, LEAD_PLACE.y, BUS_Y);\n\nconst BUS = horizontalEdge(BUS_Y, LEFTMOST, RIGHTMOST);\n\nconst DROPS = WORKERS.map((id) => {\n  const place = AGENT_PLACE[id];\n  return verticalEdge(place.x, BUS_Y, place.y);\n});\n\nfunction branchOf(toolId: ToolId): EdgeSpec {\n  const from = AGENT_PLACE[TOOL_OWNER[toolId]];\n  const to = TOOL_PLACE[toolId];\n  if (from.x === to.x) {\n    return verticalEdge(from.x, from.y, to.y);\n  }\n  return horizontalEdge(from.y, from.x, to.x);\n}\n\nconst EDGE_AXIS: Record<Axis, string> = {\n  vertical: 'w-px origin-top -translate-x-1/2',\n  horizontal: 'h-px origin-left -translate-y-1/2',\n};\n\nconst EDGE_HIDDEN: Record<Axis, string> = {\n  vertical: 'scale-y-0',\n  horizontal: 'scale-x-0',\n};\n\nfunction edgeScaleOf(axis: Axis, isShown: boolean) {\n  if (isShown) {\n    return 'scale-100';\n  }\n  return EDGE_HIDDEN[axis];\n}\n\nfunction edgeToneOf(isActive: boolean) {\n  if (isActive) {\n    return 'bg-foreground/35';\n  }\n  return 'bg-border';\n}\n\ntype EdgeProps = {\n  spec: EdgeSpec;\n  isShown: boolean;\n  isActive?: boolean;\n};\n\nfunction Edge({ spec, isShown, isActive = false }: EdgeProps) {\n  return (\n    <span\n      aria-hidden='true'\n      style={spec.style}\n      className={cn(\n        'absolute transition-[scale,background-color] duration-500 ease-(--ease-out-strong)',\n        EDGE_AXIS[spec.axis],\n        edgeScaleOf(spec.axis, isShown),\n        edgeToneOf(isActive)\n      )}\n    />\n  );\n}\n\nfunction isLiveCall(call: ToolCall) {\n  return call.status === 'running' || call.status === 'waiting';\n}\n\nfunction callsOfTool(run: RunSnapshot, toolId: ToolId) {\n  return run.calls.filter((call) => call.tool === toolId);\n}\n\n/** Calls to the same tool that start together leave one after the other, not on top of each other. */\nfunction orderOf(run: RunSnapshot, call: ToolCall, toolId: ToolId) {\n  const sameTool = callsOfTool(run, toolId);\n  return sameTool.findIndex((candidate) => candidate.id === call.id);\n}\n\ntype DotStyle = CSSProperties & { '--dx': string; '--dy': string };\n\ntype DotWay = 'out' | 'back';\n\nconst DOT =\n  'bg-primary pointer-events-none absolute -ml-0.75 -mt-0.75 size-1.5 rounded-full transition-[translate] duration-700 ease-linear';\n\nconst DOT_WAY: Record<DotWay, string> = {\n  out: '[translate:var(--dx)_var(--dy)] starting:[translate:0_0]',\n  back: '[translate:0_0] starting:[translate:var(--dx)_var(--dy)]',\n};\n\nfunction dotStyleOf(toolId: ToolId, order: number): DotStyle {\n  const from = AGENT_PLACE[TOOL_OWNER[toolId]];\n  const to = TOOL_PLACE[toolId];\n  const delay = `${order * 120}ms`;\n  return {\n    left: percent(from.x),\n    top: percent(from.y),\n    '--dx': `${to.x - from.x}cqw`,\n    '--dy': `${to.y - from.y}cqh`,\n    transitionDelay: delay,\n  };\n}\n\ntype CallDotProps = {\n  toolId: ToolId;\n  order: number;\n  way: DotWay;\n};\n\n/** A dot goes out along the edge when a call starts and comes back when it ends. Both stop under a node, so nothing is left to clean. */\nfunction CallDot({ toolId, order, way }: CallDotProps) {\n  return (\n    <span\n      aria-hidden='true'\n      style={dotStyleOf(toolId, order)}\n      className={cn(DOT, DOT_WAY[way])}\n    />\n  );\n}\n\nfunction StatusMark({ status }: { status: string }) {\n  const corner = 'bg-card absolute -end-1 -bottom-1 rounded-full';\n  if (status === 'done') {\n    return (\n      <span className={corner}>\n        <CircleCheckIcon className='text-success-foreground size-3.5' />\n      </span>\n    );\n  }\n  if (status === 'waiting') {\n    return (\n      <span className={corner}>\n        <HandIcon className='text-warning-foreground size-3.5' />\n      </span>\n    );\n  }\n  if (status === 'failed') {\n    return (\n      <span className={corner}>\n        <CircleXIcon className='text-destructive-ink size-3.5' />\n      </span>\n    );\n  }\n  return null;\n}\n\nfunction ringOf(status: string) {\n  if (status === 'running') {\n    return 'ring-info/40 ring-2';\n  }\n  if (status === 'waiting') {\n    return 'ring-warning/60 ring-2';\n  }\n  return undefined;\n}\n\nfunction dimOf(isDimmed: boolean) {\n  if (isDimmed) {\n    return 'opacity-40';\n  }\n  return undefined;\n}\n\nfunction pickedRingOf(isPicked: boolean) {\n  if (isPicked) {\n    return 'ring-primary/50 ring-2';\n  }\n  return undefined;\n}\n\nconst NODE =\n  'absolute z-10 flex -translate-x-1/2 -translate-y-1/2 flex-col items-center gap-1 rounded-lg outline-none transition-opacity duration-200';\n\nfunction placeStyleOf(place: NodePlace): CSSProperties {\n  return { left: percent(place.x), top: percent(place.y) };\n}\n\ntype AgentNodeProps = {\n  id: AgentId;\n  run: RunSnapshot;\n  focusAgentId: string | null;\n  onFocusAgent: (id: string) => void;\n};\n\nfunction AgentNode({ id, run, focusAgentId, onFocusAgent }: AgentNodeProps) {\n  const agent = run.agents.find((candidate) => candidate.id === id);\n  if (!agent) {\n    return null;\n  }\n  const isPicked = focusAgentId === id;\n  const hasPick = focusAgentId !== null;\n  const isOtherPicked = hasPick && !isPicked;\n  const isIdleRun = run.status === 'idle';\n  const isDimmed = isOtherPicked || isIdleRun;\n  const calls = countOf(callsOfAgent(run, id).length, 'call');\n  const word = AGENT_STATUS_WORD[agent.status];\n\n  function pick() {\n    onFocusAgent(id);\n  }\n\n  return (\n    <button\n      type='button'\n      aria-pressed={isPicked}\n      aria-label={`${agent.name}, ${word}, ${calls}`}\n      onClick={pick}\n      style={placeStyleOf(AGENT_PLACE[id])}\n      className={cn(\n        NODE,\n        'focus-visible:ring-ring/25 cursor-pointer focus-visible:ring-[3px]',\n        dimOf(isDimmed)\n      )}\n    >\n      <span className='relative'>\n        <AgentTile\n          agent={agent}\n          className={cn(\n            'transition-shadow duration-200',\n            ringOf(agent.status),\n            pickedRingOf(isPicked)\n          )}\n        />\n        <StatusMark status={agent.status} />\n      </span>\n      <span className='bg-card rounded px-1 text-xs font-medium'>\n        {agent.name}\n      </span>\n    </button>\n  );\n}\n\ntype ToolNodeProps = {\n  toolId: ToolId;\n  isDimmed: boolean;\n};\n\nfunction ToolNode({ toolId, isDimmed }: ToolNodeProps) {\n  const tool = toolMetaOf(toolId);\n\n  return (\n    <div\n      style={placeStyleOf(TOOL_PLACE[toolId])}\n      className={cn(\n        NODE,\n        'transition-[opacity,scale] duration-300 starting:scale-90 starting:opacity-0',\n        dimOf(isDimmed)\n      )}\n    >\n      <ToolTile toolId={toolId} />\n      <span className='bg-card text-muted-foreground rounded px-1 text-xs'>\n        {tool.name}\n      </span>\n    </div>\n  );\n}\n\ntype GraphProps = {\n  run: RunSnapshot;\n  focusAgentId: string | null;\n  onFocusAgent: (id: string) => void;\n  className?: string;\n};\n\n/**\n * The agents and the tools they call, placed by shares of the stage, so nothing is measured and the\n * graph follows the width of its panel. An edge draws itself when it is first used.\n */\nexport function Graph({\n  run,\n  focusAgentId,\n  onFocusAgent,\n  className,\n}: GraphProps) {\n  const hasStarted = run.status !== 'idle';\n  const liveCount = run.calls.filter(isLiveCall).length;\n  const total = countOf(run.calls.length, 'call');\n\n  return (\n    <Panel\n      panel='graph'\n      title='Live graph'\n      className={className}\n      meta={\n        <span className='text-muted-foreground text-xs tabular-nums'>\n          {total}, {liveCount} live\n        </span>\n      }\n    >\n      <div className='[container-type:size] relative h-80'>\n        <Edge spec={SPINE} isShown={hasStarted} />\n        <Edge spec={BUS} isShown={hasStarted} />\n        {DROPS.map((spec, index) => (\n          <Edge key={WORKERS[index]} spec={spec} isShown={hasStarted} />\n        ))}\n        {TOOL_META.map((tool) => {\n          const calls = callsOfTool(run, tool.id);\n          const isUsed = calls.length > 0;\n          const isLive = calls.some(isLiveCall);\n          return (\n            <Edge\n              key={tool.id}\n              spec={branchOf(tool.id)}\n              isShown={isUsed}\n              isActive={isLive}\n            />\n          );\n        })}\n        {run.calls.map((call) => {\n          const toolId = toolMetaOf(call.tool).id;\n          const order = orderOf(run, call, toolId);\n          const isLive = isLiveCall(call);\n          const isDone = call.status === 'done';\n          return (\n            <span key={call.id}>\n              {isLive && <CallDot toolId={toolId} order={order} way='out' />}\n              {isDone && <CallDot toolId={toolId} order={order} way='back' />}\n            </span>\n          );\n        })}\n        {AGENT_ORDER.map((id) => (\n          <AgentNode\n            key={id}\n            id={id}\n            run={run}\n            focusAgentId={focusAgentId}\n            onFocusAgent={onFocusAgent}\n          />\n        ))}\n        {TOOL_META.map((tool) => {\n          const isUsed = callsOfTool(run, tool.id).length > 0;\n          if (!isUsed) {\n            return null;\n          }\n          const owner = TOOL_OWNER[tool.id];\n          const isOtherPicked = focusAgentId !== null && focusAgentId !== owner;\n          return (\n            <ToolNode key={tool.id} toolId={tool.id} isDimmed={isOtherPicked} />\n          );\n        })}\n      </div>\n      <p className='text-muted-foreground text-xs leading-5'>\n        A dot goes out along an edge for each call and comes back with its\n        result. Pick an agent to follow it on every panel.\n      </p>\n    </Panel>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-07/graph.tsx"
    },
    {
      "path": "registry/ndeko/templates/agent-operations/application-07/model.ts",
      "content": "import type {\n  RunAgent,\n  RunSnapshot,\n  ToolCall,\n} from '@/registry/ndeko/lib/agent-run';\n\nimport { planSeedOf } from './data';\n\nexport type LaneId = 'queued' | 'running' | 'needs' | 'done';\n\nexport type BoardTask = {\n  id: string;\n  title: string;\n  ownerId: string;\n  lane: LaneId;\n  status: string;\n};\n\nexport function agentOf(run: RunSnapshot, id: string) {\n  return run.agents.find((agent) => agent.id === id);\n}\n\nexport function callsOfAgent(run: RunSnapshot, agentId: string) {\n  return run.calls.filter((call) => call.agentId === agentId);\n}\n\nfunction laneOf(status: string, isOwnerWaiting: boolean): LaneId {\n  if (status === 'upcoming') {\n    return 'queued';\n  }\n  if (status === 'running') {\n    if (isOwnerWaiting) {\n      return 'needs';\n    }\n    return 'running';\n  }\n  return 'done';\n}\n\nexport function boardOf(run: RunSnapshot): BoardTask[] {\n  return run.plan.map((step) => {\n    const ownerId = planSeedOf(step.id).ownerId;\n    const owner = agentOf(run, ownerId);\n    const isOwnerWaiting = owner?.status === 'waiting';\n    const lane = laneOf(step.status, isOwnerWaiting);\n    return {\n      id: step.id,\n      title: step.title,\n      ownerId,\n      lane,\n      status: step.status,\n    };\n  });\n}\n\nexport function placementOf(tasks: BoardTask[]) {\n  const places = tasks.map((task) => `${task.id}:${task.lane}`);\n  return places.join(' ');\n}\n\nfunction startedAtOf(agent: RunAgent) {\n  return agent.startedAt ?? 0;\n}\n\nfunction latestFirst(first: RunAgent, second: RunAgent) {\n  return startedAtOf(second) - startedAtOf(first);\n}\n\n/**\n * The agent the monitor follows: the one a person picked, else the one that waits on a person, else\n * the one that started last among those at work, else the one that finished last.\n */\nexport function monitoredAgentOf(run: RunSnapshot, focusId: string | null) {\n  if (focusId !== null) {\n    return agentOf(run, focusId);\n  }\n  const waiting = run.agents.find((agent) => agent.status === 'waiting');\n  if (waiting) {\n    return waiting;\n  }\n  const working = run.agents.filter((agent) => agent.status === 'running');\n  const latestWorking = [...working].sort(latestFirst)[0];\n  if (latestWorking) {\n    return latestWorking;\n  }\n  const finished = run.agents.filter((agent) => agent.status === 'done');\n  const lastFinished = [...finished].sort(latestFirst)[0];\n  if (lastFinished) {\n    return lastFinished;\n  }\n  return agentOf(run, 'coordinator');\n}\n\nfunction maxOf(values: Array<number | undefined>) {\n  let largest = 0;\n  for (const value of values) {\n    if (value !== undefined && value > largest) {\n      largest = value;\n    }\n  }\n  return largest;\n}\n\nfunction stampsOfCall(call: ToolCall) {\n  return [call.startedAt, call.endedAt];\n}\n\n/** The latest moment the run has recorded. A clock never reads earlier than it. */\nexport function latestStampOf(run: RunSnapshot) {\n  const stamps: Array<number | undefined> = [run.startedAt, run.endedAt];\n  for (const agent of run.agents) {\n    stamps.push(agent.startedAt, agent.endedAt);\n  }\n  for (const step of run.plan) {\n    stamps.push(step.startedAt, step.endedAt);\n  }\n  for (const call of run.calls) {\n    stamps.push(...stampsOfCall(call));\n  }\n  for (const approval of run.approvals) {\n    stamps.push(approval.requestedAt, approval.resolvedAt);\n  }\n  return maxOf(stamps);\n}\n\n/** What time it is for a run: the clock of the page, but never before what the run already recorded. */\nexport function runNowOf(run: RunSnapshot, now: number) {\n  return Math.max(now, latestStampOf(run));\n}\n\nexport function isRunLive(run: RunSnapshot) {\n  return run.status === 'running' || run.status === 'waiting';\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-07/model.ts"
    },
    {
      "path": "registry/ndeko/templates/agent-operations/application-07/monitor.tsx",
      "content": "'use client';\n\nimport { useId, useState, type CSSProperties } from 'react';\n\nimport { WordRoll } from '@/components/core/word-roll';\nimport {\n  elapsedOf,\n  formatDuration,\n  type PlanStep,\n  type RunAgent,\n  type RunSnapshot,\n} from '@/registry/ndeko/lib/agent-run';\nimport { hatchOf } from '@/registry/ndeko/lib/hatch';\nimport { ChevronDownIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Fold } from '@/registry/ndeko/ui/chat-motion';\nimport { LiveDuration } from '@/registry/ndeko/ui/live-duration';\nimport { Wash } from '@/registry/ndeko/ui/wash';\n\nimport {\n  AGENT_STATUS_WORD,\n  AGENT_STATUS_WORDS,\n  AgentTile,\n  CostFigure,\n  StatusDot,\n} from './agent-parts';\nimport { ApprovalBlock } from './approval-block';\nimport { planSeedOf } from './data';\nimport { agentOf, monitoredAgentOf } from './model';\nimport { Panel } from './panel';\nimport type { Decision } from './session';\n\nconst WASH_HUE: Record<string, string> = {\n  running: 'var(--info)',\n  waiting: 'var(--warning)',\n  done: 'var(--success)',\n};\n\nfunction washHueOf(status: string) {\n  return WASH_HUE[status] ?? 'var(--info)';\n}\n\nfunction isWashShown(status: string) {\n  return WASH_HUE[status] !== undefined;\n}\n\nfunction chevronTurnOf(isOpen: boolean) {\n  if (isOpen) {\n    return 'rotate-180';\n  }\n  return 'rotate-0';\n}\n\nfunction stepOfAgent(run: RunSnapshot, agent: RunAgent) {\n  const owned = run.plan.filter(\n    (step) => planSeedOf(step.id).ownerId === agent.id\n  );\n  const live = owned.find((step) => step.status === 'running');\n  return live ?? owned[0];\n}\n\nfunction stepLineOf(run: RunSnapshot, step: PlanStep | undefined) {\n  if (!step) {\n    return 'No step of the plan is its own';\n  }\n  const position = run.plan.findIndex((candidate) => candidate.id === step.id);\n  return `Step ${position + 1} of ${run.plan.length}: ${step.title}`;\n}\n\nfunction AgentClock({ agent }: { agent: RunAgent }) {\n  if (agent.status === 'running') {\n    return (\n      <LiveDuration\n        item={agent}\n        isRunning\n        className='text-muted-foreground text-xs'\n      />\n    );\n  }\n  if (agent.status === 'done') {\n    const elapsed = elapsedOf(agent, agent.endedAt ?? 0);\n    return (\n      <span className='text-muted-foreground text-xs tabular-nums'>\n        {formatDuration(elapsed)}\n      </span>\n    );\n  }\n  return null;\n}\n\ntype Fill = {\n  key: string;\n  className: string;\n  style?: CSSProperties;\n};\n\nconst FILL_TONE: Record<string, string> = {\n  running: 'bg-primary/70',\n  done: 'bg-primary',\n};\n\n/** A running segment fills over the time its step usually takes, in one transition on the compositor. */\nfunction fillOf(\n  step: PlanStep,\n  isWaiting: boolean,\n  expectedMs: number\n): Fill | null {\n  if (step.status === 'upcoming') {\n    return null;\n  }\n  if (isWaiting) {\n    const style = { backgroundImage: hatchOf('var(--warning)') };\n    return { key: 'waiting', className: 'bg-warning/10', style };\n  }\n  if (step.status === 'skipped') {\n    return { key: 'skipped', className: 'bg-foreground/15' };\n  }\n  const style = { transitionDuration: `${expectedMs}ms` };\n  const tone = FILL_TONE[step.status];\n  const className = cn(\n    'origin-left scale-x-100 transition-[scale,background-color] ease-linear starting:scale-x-0',\n    tone\n  );\n  return { key: 'fill', className, style };\n}\n\ntype SegmentProps = {\n  step: PlanStep;\n  isWaiting: boolean;\n};\n\nfunction Segment({ step, isWaiting }: SegmentProps) {\n  const seed = planSeedOf(step.id);\n  const fill = fillOf(step, isWaiting, seed.expectedMs);\n\n  return (\n    <li className='bg-foreground/10 relative h-1.5 min-w-0 flex-1 overflow-hidden rounded-full'>\n      {fill && (\n        <span\n          key={fill.key}\n          style={fill.style}\n          className={cn('absolute inset-0', fill.className)}\n        />\n      )}\n      <span className='sr-only'>\n        {seed.title}, {step.status}\n      </span>\n    </li>\n  );\n}\n\nfunction TimeStrip({ run }: { run: RunSnapshot }) {\n  const isEmpty = run.plan.length === 0;\n\n  return (\n    <div className='flex flex-col gap-1.5'>\n      <ol aria-label='Steps of the plan' className='flex gap-1'>\n        {run.plan.map((step) => {\n          const ownerId = planSeedOf(step.id).ownerId;\n          const owner = agentOf(run, ownerId);\n          const isOwnerWaiting = owner?.status === 'waiting';\n          const isWaiting = isOwnerWaiting && step.status === 'running';\n          return <Segment key={step.id} step={step} isWaiting={isWaiting} />;\n        })}\n        {isEmpty && (\n          <li className='bg-foreground/10 h-1.5 flex-1 rounded-full'>\n            <span className='sr-only'>No plan yet</span>\n          </li>\n        )}\n      </ol>\n    </div>\n  );\n}\n\ntype MonitorBodyProps = {\n  run: RunSnapshot;\n  agent: RunAgent | undefined;\n};\n\nfunction MonitorBody({ run, agent }: MonitorBodyProps) {\n  if (!agent) {\n    return null;\n  }\n  const step = stepOfAgent(run, agent);\n  const hasTask = agent.task !== undefined;\n  const task = agent.task ?? 'Waiting for its turn';\n\n  return (\n    <div className='flex flex-col gap-4'>\n      <div className='flex items-center gap-2.5'>\n        <AgentTile agent={agent} />\n        <div className='flex min-w-0 flex-1 flex-col leading-tight'>\n          <span className='truncate text-[13px] font-medium'>{agent.name}</span>\n          <span className='text-muted-foreground truncate text-xs'>\n            {agent.model}\n          </span>\n        </div>\n        <span className='flex shrink-0 items-center gap-1.5 text-xs'>\n          <StatusDot status={agent.status} />\n          <WordRoll\n            text={AGENT_STATUS_WORD[agent.status]}\n            labels={AGENT_STATUS_WORDS}\n          />\n        </span>\n      </div>\n      <div className='bg-foreground/[0.04] flex flex-col gap-1.5 rounded-lg p-3'>\n        <p\n          key={task}\n          className='min-h-5 text-[13px] leading-5 font-medium transition-opacity duration-300 starting:opacity-0'\n        >\n          {task}\n        </p>\n        <div className='text-muted-foreground flex items-center justify-between gap-3 text-xs'>\n          <span className='min-w-0 truncate'>\n            {hasTask && stepLineOf(run, step)}\n            {!hasTask && 'Nothing assigned yet'}\n          </span>\n          <span className='w-10 shrink-0 text-end'>\n            <AgentClock agent={agent} />\n          </span>\n        </div>\n      </div>\n      <TimeStrip run={run} />\n      <div className='flex items-end justify-between gap-3'>\n        <div className='flex min-w-0 flex-col gap-0.5'>\n          <span className='text-muted-foreground text-xs'>\n            Spent by {agent.name}\n          </span>\n          <CostFigure\n            usd={agent.costUsd ?? 0}\n            className='text-2xl leading-8 font-semibold'\n          />\n        </div>\n      </div>\n    </div>\n  );\n}\n\ntype MonitorProps = {\n  run: RunSnapshot;\n  focusAgentId: string | null;\n  pressed: string | null;\n  onDecide: (decision: Decision) => void;\n  className?: string;\n};\n\nexport function Monitor({\n  run,\n  focusAgentId,\n  pressed,\n  onDecide,\n  className,\n}: MonitorProps) {\n  const [isFolded, setIsFolded] = useState(false);\n  const bodyId = useId();\n  const agent = monitoredAgentOf(run, focusAgentId);\n  const hue = washHueOf(run.status);\n  const isShown = isWashShown(run.status);\n\n  function toggle() {\n    setIsFolded((current) => !current);\n  }\n\n  return (\n    <Panel\n      panel='monitor'\n      title='Monitor'\n      className={className}\n      wash={<Wash color={hue} isShown={isShown} />}\n      meta={\n        <Button\n          type='button'\n          variant='ghost'\n          size='icon-sm'\n          aria-expanded={!isFolded}\n          aria-controls={bodyId}\n          aria-label='Fold the monitor'\n          onClick={toggle}\n          className='text-muted-foreground -me-1'\n        >\n          <ChevronDownIcon\n            className={cn(\n              'transition-transform duration-200 ease-(--ease-out-strong)',\n              chevronTurnOf(!isFolded)\n            )}\n          />\n        </Button>\n      }\n    >\n      <Fold open={!isFolded} id={bodyId}>\n        <MonitorBody run={run} agent={agent} />\n      </Fold>\n      <ApprovalBlock run={run} pressed={pressed} onDecide={onDecide} />\n    </Panel>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-07/monitor.tsx"
    },
    {
      "path": "registry/ndeko/templates/agent-operations/application-07/page-header.tsx",
      "content": "'use client';\n\nimport { useEffect, useRef, useState, type RefObject } from 'react';\n\nimport { WordRoll } from '@/components/core/word-roll';\nimport { useNow } from '@/registry/ndeko/hooks/use-agent-run';\nimport {\n  formatDuration,\n  formatTokens,\n  type RunSnapshot,\n  type RunStatus,\n} from '@/registry/ndeko/lib/agent-run';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { countOf } from '@/registry/ndeko/lib/words';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { CompanyMark } from '@/registry/ndeko/ui/company-mark';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\n\nimport { CostFigure } from './agent-parts';\nimport { BRAND, RUN_ID, RUN_NOTE, RUN_TITLE } from './data';\nimport { isRunLive, runNowOf } from './model';\n\nconst STATUS_WORD: Record<RunStatus, string> = {\n  idle: 'Ready',\n  running: 'Running',\n  waiting: 'Waiting on you',\n  done: 'Done',\n  failed: 'Failed',\n  cancelled: 'Stopped',\n};\n\nconst STATUS_WORDS = Object.values(STATUS_WORD);\n\nconst STATUS_DOT: Record<RunStatus, string> = {\n  idle: 'bg-muted-foreground/45',\n  running: 'bg-info',\n  waiting: 'bg-warning',\n  done: 'bg-success',\n  failed: 'bg-destructive',\n  cancelled: 'bg-muted-foreground/45',\n};\n\nconst CLOCK_MS = 250;\n\n/** The slim bar takes over once the page has scrolled this far. */\nconst CONDENSE_AFTER_PX = 48;\n\nfunction slimToneOf(isCondensed: boolean) {\n  if (isCondensed) {\n    return 'translate-y-0 opacity-100';\n  }\n  return '-translate-y-full opacity-0';\n}\n\n/** The only text that ticks: the time the run has taken, which stops with the run. */\nfunction RunElapsed({\n  run,\n  className,\n}: {\n  run: RunSnapshot;\n  className?: string;\n}) {\n  const now = useNow(CLOCK_MS, isRunLive(run));\n  if (run.startedAt === undefined) {\n    return <span className={cn('tabular-nums', className)}>0.0s</span>;\n  }\n  const end = run.endedAt ?? runNowOf(run, now);\n  const elapsed = Math.max(0, end - run.startedAt);\n\n  return (\n    <span className={cn('tabular-nums', className)}>\n      {formatDuration(elapsed)}\n    </span>\n  );\n}\n\nfunction StatusPill({ status }: { status: RunStatus }) {\n  return (\n    <span className='bg-foreground/[0.05] flex h-7 items-center gap-2 rounded-full px-3 text-xs'>\n      <span\n        aria-hidden='true'\n        className={cn(\n          'size-1.5 shrink-0 rounded-full transition-colors duration-200',\n          STATUS_DOT[status]\n        )}\n      />\n      <WordRoll text={STATUS_WORD[status]} labels={STATUS_WORDS} />\n    </span>\n  );\n}\n\nfunction callsDoneOf(run: RunSnapshot) {\n  return run.calls.filter((call) => call.status === 'done').length;\n}\n\ntype FigureProps = {\n  label: string;\n  children: React.ReactNode;\n};\n\nfunction Figure({ label, children }: FigureProps) {\n  return (\n    <div className='flex min-w-0 flex-col gap-0.5'>\n      <dt className='text-muted-foreground text-xs'>{label}</dt>\n      <dd className='text-lg leading-7 font-semibold tabular-nums'>\n        {children}\n      </dd>\n    </div>\n  );\n}\n\nexport type SlimBarProps = {\n  run: RunSnapshot;\n  isCondensed: boolean;\n  canReplay: boolean;\n  onReplay: () => void;\n};\n\n/** What the page header becomes once it scrolls away: one line that stays in view, drawn over the content with no change of layout. */\nexport function SlimBar({\n  run,\n  isCondensed,\n  canReplay,\n  onReplay,\n}: SlimBarProps) {\n  return (\n    <div className='sticky top-0 z-10 h-0'>\n      <div\n        inert={!isCondensed}\n        className={cn(\n          'bg-card hairline-b border-border absolute inset-x-0 top-0 transition-[translate,opacity] duration-200 ease-(--ease-out-strong)',\n          slimToneOf(isCondensed)\n        )}\n      >\n        <div className='mx-auto flex h-12 w-full max-w-[90rem] items-center gap-3 px-3 @xl:px-5'>\n          <span\n            aria-hidden='true'\n            className={cn(\n              'size-1.5 shrink-0 rounded-full transition-colors duration-200',\n              STATUS_DOT[run.status]\n            )}\n          />\n          <span className='min-w-0 flex-1 truncate text-[13px] font-medium'>\n            {RUN_TITLE}\n          </span>\n          {isCondensed && (\n            <span className='text-muted-foreground hidden items-center gap-1.5 text-xs @md:flex'>\n              <RunElapsed run={run} />\n              <span aria-hidden='true'>·</span>\n              <CostFigure usd={run.usage.costUsd} />\n            </span>\n          )}\n          <ReplayButton\n            isShown={canReplay}\n            onReplay={onReplay}\n            label='Replay'\n          />\n        </div>\n      </div>\n    </div>\n  );\n}\n\n/**\n * Tells when the page has scrolled past the header: a sentinel near its top leaves the scroller, so\n * nothing listens to scrolling.\n */\nexport function useCondensedHeader(\n  scrollerRef: RefObject<HTMLDivElement | null>\n) {\n  const sentinelRef = useRef<HTMLSpanElement>(null);\n  const [isCondensed, setIsCondensed] = useState(false);\n\n  useEffect(() => {\n    const sentinel = sentinelRef.current;\n    const scroller = scrollerRef.current;\n    if (!sentinel || !scroller) {\n      return;\n    }\n    const observer = new IntersectionObserver(\n      ([entry]) => setIsCondensed(!entry.isIntersecting),\n      { root: scroller }\n    );\n    observer.observe(sentinel);\n    return () => observer.disconnect();\n  }, [scrollerRef]);\n\n  return { sentinelRef, isCondensed };\n}\n\ntype PageHeaderProps = {\n  run: RunSnapshot;\n  sentinelRef: RefObject<HTMLSpanElement | null>;\n  canReplay: boolean;\n  onReplay: () => void;\n};\n\nexport function PageHeader({\n  run,\n  sentinelRef,\n  canReplay,\n  onReplay,\n}: PageHeaderProps) {\n  const tokens = run.usage.inputTokens + run.usage.outputTokens;\n\n  return (\n    <header className='relative flex flex-col gap-5 pt-5 @3xl:pt-8'>\n      <span\n        ref={sentinelRef}\n        aria-hidden='true'\n        style={{ top: CONDENSE_AFTER_PX }}\n        className='pointer-events-none absolute h-px w-full'\n      />\n      <div className='flex flex-wrap items-start justify-between gap-x-4 gap-y-3'>\n        <div className='flex min-w-0 flex-col gap-1.5'>\n          <p className='text-muted-foreground flex items-center gap-2 text-xs'>\n            <CompanyMark seed={BRAND.name} size='sm' />\n            {BRAND.name}\n            <span aria-hidden='true'>/</span>\n            Agent operations\n          </p>\n          <h1 className='text-xl font-semibold text-balance @3xl:text-2xl'>\n            {RUN_TITLE}\n          </h1>\n          <p className='text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-1 text-xs'>\n            <span className='font-mono'>{RUN_ID}</span>\n            <span>{RUN_NOTE}</span>\n            <Badge variant='secondary'>Illustrative</Badge>\n          </p>\n        </div>\n        <div className='flex items-center gap-2'>\n          <ReplayButton\n            isShown={canReplay}\n            onReplay={onReplay}\n            label='Replay'\n          />\n          <StatusPill status={run.status} />\n        </div>\n      </div>\n      <dl className='grid grid-cols-2 gap-x-6 gap-y-3 @xl:grid-cols-4'>\n        <Figure label='Elapsed'>\n          <RunElapsed run={run} />\n        </Figure>\n        <Figure label='Spent'>\n          <CostFigure usd={run.usage.costUsd} />\n        </Figure>\n        <Figure label='Tokens'>{formatTokens(tokens)}</Figure>\n        <Figure label='Calls'>\n          {callsDoneOf(run)} of {countOf(run.calls.length, 'call')}\n        </Figure>\n      </dl>\n    </header>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-07/page-header.tsx"
    },
    {
      "path": "registry/ndeko/templates/agent-operations/application-07/panel.tsx",
      "content": "'use client';\n\nimport { useId } from 'react';\n\nimport { cn } from '@/registry/ndeko/lib/utils';\n\ntype PanelProps = {\n  /** Names the panel for the page: the demonstration scrolls to it. */\n  panel: string;\n  title: string;\n  meta?: React.ReactNode;\n  /** The grain wash of the surface, when it is the one that says what is live: it has to come first. */\n  wash?: React.ReactNode;\n  className?: string;\n  children: React.ReactNode;\n};\n\n/** One surface of the page. Its place in the grid comes from `className`, so the layout stays in one file. */\nexport function Panel({\n  panel,\n  title,\n  meta,\n  wash,\n  className,\n  children,\n}: PanelProps) {\n  const titleId = useId();\n\n  return (\n    <section\n      data-panel={panel}\n      aria-labelledby={titleId}\n      className={cn(\n        'bg-card hairline-ring ring-border dark:bg-foreground/[0.03] relative isolate flex min-w-0 flex-col gap-3 rounded-xl p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)]',\n        className\n      )}\n    >\n      {wash}\n      <header className='flex min-h-6 items-center gap-2'>\n        <h2\n          id={titleId}\n          className='min-w-0 flex-1 truncate text-sm font-medium'\n        >\n          {title}\n        </h2>\n        {meta}\n      </header>\n      {children}\n    </section>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-07/panel.tsx"
    },
    {
      "path": "registry/ndeko/templates/agent-operations/application-07/session.ts",
      "content": "import type { SessionStep } from '@/registry/ndeko/hooks/use-session';\nimport {\n  emptyRun,\n  pendingApprovalsOf,\n  reduceRun,\n  type AgentStatus,\n  type RunAgent,\n  type RunEvent,\n  type RunSnapshot,\n  type ToolCall,\n} from '@/registry/ndeko/lib/agent-run';\nimport { restingOf } from '@/registry/ndeko/lib/run-session';\n\nimport {\n  AGENT_COST_AFTER,\n  AGENT_TASK,\n  AGENTS,\n  callSeedOf,\n  JOURNAL_REQUEST,\n  PLAN_STEPS,\n  PLAN_USAGE,\n  POSTING_TASK,\n  RUN_ID,\n  RUN_TITLE,\n  type AgentId,\n  type StepId,\n} from './data';\n\nexport type Decision = 'approved' | 'denied';\n\nexport type ScrollTarget = 'top' | 'fleet';\n\nexport type OpsState = {\n  run: RunSnapshot;\n  focusAgentId: string | null;\n  scrollTarget: ScrollTarget;\n  isStopped: boolean;\n};\n\nexport type OpsAction =\n  | { type: 'events'; events: RunEvent[] }\n  | { type: 'decided'; decision: Decision }\n  | { type: 'focused'; id: string | null }\n  | { type: 'scrolled'; target: ScrollTarget };\n\ntype Step = SessionStep<OpsState, OpsAction>;\n\nexport const INITIAL: OpsState = {\n  run: emptyRun({ id: RUN_ID, title: RUN_TITLE, agents: AGENTS }),\n  focusAgentId: null,\n  scrollTarget: 'top',\n  isStopped: false,\n};\n\nfunction appliedEvents(run: RunSnapshot, events: RunEvent[], now: number) {\n  let next = run;\n  for (const event of events) {\n    next = reduceRun(next, event, now);\n  }\n  return next;\n}\n\nfunction patchedCall(\n  run: RunSnapshot,\n  id: string,\n  patch: Partial<ToolCall>\n): RunSnapshot {\n  const calls = run.calls.map((call) => {\n    if (call.id !== id) {\n      return call;\n    }\n    return { ...call, ...patch };\n  });\n  return { ...run, calls };\n}\n\nfunction patchedAgent(\n  run: RunSnapshot,\n  id: string,\n  patch: Partial<RunAgent>\n): RunSnapshot {\n  const agents = run.agents.map((agent) => {\n    if (agent.id !== id) {\n      return agent;\n    }\n    return { ...agent, ...patch };\n  });\n  return { ...run, agents };\n}\n\nfunction patchedStep(\n  run: RunSnapshot,\n  id: string,\n  status: 'skipped',\n  endedAt: number\n): RunSnapshot {\n  const plan = run.plan.map((step) => {\n    if (step.id !== id) {\n      return step;\n    }\n    return { ...step, status, endedAt };\n  });\n  return { ...run, plan };\n}\n\n/**\n * Once a person answers, the call and its agent carry on from where they waited: a patch that\n * went through `reduceRun` would stamp their start again and lose the time spent waiting.\n */\nfunction resumed(run: RunSnapshot): RunSnapshot {\n  const call = patchedCall(run, 'c7', { status: 'running' });\n  return patchedAgent(call, 'coordinator', { status: 'running' });\n}\n\nfunction stopped(run: RunSnapshot, now: number): RunSnapshot {\n  const call = patchedCall(run, 'c7', {\n    status: 'failed',\n    error: 'Denied by you',\n    endedAt: now,\n  });\n  const step = patchedStep(call, 'post', 'skipped', now);\n  const agent = patchedAgent(step, 'coordinator', {\n    status: 'done',\n    task: 'Stopped, nothing was posted',\n    endedAt: now,\n  });\n  return { ...agent, status: 'cancelled', endedAt: now };\n}\n\nfunction decided(state: OpsState, decision: Decision, now: number): OpsState {\n  const pending = pendingApprovalsOf(state.run)[0];\n  if (!pending || state.isStopped) {\n    return state;\n  }\n  const resolved = reduceRun(\n    state.run,\n    { type: 'approval.resolved', id: pending.id, decision },\n    now\n  );\n  if (decision === 'approved') {\n    return { ...state, run: resumed(resolved) };\n  }\n  return { ...state, run: stopped(resolved, now), isStopped: true };\n}\n\nexport function applyAt(\n  state: OpsState,\n  action: OpsAction,\n  now: number\n): OpsState {\n  switch (action.type) {\n    case 'events': {\n      if (state.isStopped) {\n        return state;\n      }\n      const run = appliedEvents(state.run, action.events, now);\n      return { ...state, run };\n    }\n    case 'decided':\n      return decided(state, action.decision, now);\n    case 'focused':\n      return { ...state, focusAgentId: action.id };\n    case 'scrolled':\n      return { ...state, scrollTarget: action.target };\n  }\n}\n\nexport function reducer(state: OpsState, action: OpsAction) {\n  return applyAt(state, action, Date.now());\n}\n\nfunction hasDecided(state: OpsState) {\n  if (state.isStopped) {\n    return true;\n  }\n  return pendingApprovalsOf(state.run).length === 0;\n}\n\nfunction events(after: number, ...list: RunEvent[]): Step {\n  return { after, action: { type: 'events', events: list } };\n}\n\n/** A patch without a task keeps the one the agent had: an explicit undefined would clear it. */\nfunction agentStatus(\n  id: AgentId,\n  status: AgentStatus,\n  task?: string\n): RunEvent {\n  if (task === undefined) {\n    return { type: 'agent.updated', id, patch: { status } };\n  }\n  return { type: 'agent.updated', id, patch: { status, task } };\n}\n\nfunction agentRunning(id: AgentId): RunEvent {\n  return agentStatus(id, 'running', AGENT_TASK[id]);\n}\n\nfunction stepStatus(id: StepId, status: 'running' | 'done'): RunEvent {\n  return { type: 'step.updated', id, patch: { status } };\n}\n\nfunction startCall(id: string): RunEvent {\n  const seed = callSeedOf(id);\n  return {\n    type: 'call.started',\n    call: {\n      id,\n      tool: seed.toolId,\n      label: seed.label,\n      status: 'running',\n      agentId: seed.agentId,\n    },\n  };\n}\n\nfunction finishCall(id: string): RunEvent[] {\n  const seed = callSeedOf(id);\n  const spent = AGENT_COST_AFTER[id];\n  return [\n    { type: 'call.updated', id, patch: { status: 'done' } },\n    {\n      type: 'usage.added',\n      inputTokens: seed.inputTokens,\n      outputTokens: seed.outputTokens,\n      costUsd: seed.costUsd,\n      contextTokens: seed.inputTokens + seed.outputTokens,\n    },\n    { type: 'agent.updated', id: seed.agentId, patch: { costUsd: spent } },\n  ];\n}\n\nfunction demoScroll(after: number, target: ScrollTarget): Step {\n  return { after, by: 'demo', action: { type: 'scrolled', target } };\n}\n\nfunction demoFocus(after: number, id: string | null, press: string): Step {\n  return { after, by: 'demo', press, action: { type: 'focused', id } };\n}\n\nconst DEMO_DECIDES_AFTER_MS = 2500;\n\nconst OPENING: Step[] = [\n  events(1000, { type: 'run.started' }),\n  events(\n    600,\n    { type: 'plan.set', steps: PLAN_STEPS },\n    agentRunning('coordinator'),\n    {\n      type: 'usage.added',\n      inputTokens: PLAN_USAGE.inputTokens,\n      outputTokens: PLAN_USAGE.outputTokens,\n      costUsd: PLAN_USAGE.costUsd,\n      contextTokens: PLAN_USAGE.inputTokens + PLAN_USAGE.outputTokens,\n    },\n    {\n      type: 'agent.updated',\n      id: 'coordinator',\n      patch: { costUsd: PLAN_USAGE.costUsd },\n    }\n  ),\n  events(\n    1000,\n    agentStatus('coordinator', 'idle', 'Waiting for the workers'),\n    stepStatus('collect', 'running'),\n    agentRunning('collector'),\n    startCall('c1'),\n    startCall('c2')\n  ),\n  events(1100, startCall('c3')),\n  events(1400, ...finishCall('c1')),\n  events(900, ...finishCall('c2')),\n  events(\n    1000,\n    ...finishCall('c3'),\n    stepStatus('collect', 'done'),\n    agentStatus('collector', 'done')\n  ),\n  events(\n    500,\n    stepStatus('match', 'running'),\n    agentRunning('matcher'),\n    startCall('c4')\n  ),\n  demoScroll(700, 'fleet'),\n  demoFocus(1100, 'matcher', 'fleet-matcher'),\n  demoFocus(1500, null, 'fleet-matcher'),\n  demoScroll(900, 'top'),\n  events(\n    300,\n    ...finishCall('c4'),\n    stepStatus('match', 'done'),\n    agentStatus('matcher', 'done')\n  ),\n  events(\n    500,\n    stepStatus('draft', 'running'),\n    agentRunning('writer'),\n    startCall('c5')\n  ),\n  events(\n    3000,\n    ...finishCall('c5'),\n    stepStatus('draft', 'done'),\n    agentStatus('writer', 'done')\n  ),\n  events(\n    500,\n    stepStatus('review', 'running'),\n    agentRunning('reviewer'),\n    startCall('c6')\n  ),\n  events(\n    2200,\n    ...finishCall('c6'),\n    stepStatus('review', 'done'),\n    agentStatus('reviewer', 'done')\n  ),\n  events(\n    600,\n    stepStatus('post', 'running'),\n    agentStatus('coordinator', 'running', POSTING_TASK),\n    startCall('c7'),\n    { type: 'call.updated', id: 'c7', patch: { status: 'waiting' } },\n    { type: 'approval.requested', approval: JOURNAL_REQUEST },\n    agentStatus('coordinator', 'waiting', POSTING_TASK)\n  ),\n];\n\nconst CLOSING: Step[] = [\n  {\n    after: DEMO_DECIDES_AFTER_MS,\n    by: 'person',\n    press: 'allow',\n    action: { type: 'decided', decision: 'approved' },\n    isAnswered: hasDecided,\n  },\n  events(\n    2200,\n    ...finishCall('c7'),\n    stepStatus('post', 'done'),\n    agentStatus('coordinator', 'done'),\n    { type: 'run.finished', status: 'done' }\n  ),\n];\n\nexport const SCRIPT: Step[] = [...OPENING, ...CLOSING];\n\nconst LOADED_AT = Date.now();\n\nconst ASKED = restingOf(INITIAL, OPENING, (state, action, sinceStart) =>\n  applyAt(state, action, LOADED_AT + sinceStart)\n);\n\n/** Under reduced motion the run waits on its request: every step before it is done, the command to post shows. */\nexport const RESTING: OpsState = {\n  ...ASKED,\n  focusAgentId: null,\n  scrollTarget: 'top',\n};\n\nexport const LOOP_AFTER_MS = 3600;\n",
      "type": "registry:component",
      "target": "components/templates/application-07/session.ts"
    },
    {
      "path": "registry/ndeko/templates/agent-operations/application-07/waterfall.tsx",
      "content": "'use client';\n\nimport type { CSSProperties } from 'react';\n\nimport { useNow } from '@/registry/ndeko/hooks/use-agent-run';\nimport {\n  elapsedOf,\n  formatDuration,\n  seriesColorOf,\n  type RunAgent,\n  type RunSnapshot,\n  type ToolCall,\n} from '@/registry/ndeko/lib/agent-run';\nimport { hatchOf } from '@/registry/ndeko/lib/hatch';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { countOf } from '@/registry/ndeko/lib/words';\nimport { LiveDuration } from '@/registry/ndeko/ui/live-duration';\n\nimport { AgentTile } from './agent-parts';\nimport { AGENT_ORDER, toolMetaOf, WINDOW_MS } from './data';\nimport { callsOfAgent, isRunLive, runNowOf } from './model';\nimport { Panel } from './panel';\n\nconst THIRD_MS = WINDOW_MS / 3;\n\nconst TICKS = [0, THIRD_MS, THIRD_MS * 2];\n\nconst END_LABEL = `${WINDOW_MS / 1000}s`;\n\n/** A call too short to see still shows: its bar is never thinner than this share of the window. */\nconst MIN_SHARE = 0.012;\n\nconst CLOCK_MS = 250;\n\nconst LABEL_WIDTH = 'w-36 @2xl:w-44';\n\nfunction percent(value: number) {\n  return `${value}%`;\n}\n\nfunction isLiveCall(call: ToolCall) {\n  return call.status === 'running' || call.status === 'waiting';\n}\n\nfunction startOf(run: RunSnapshot) {\n  return run.startedAt ?? 0;\n}\n\ntype Span = {\n  startShare: number;\n  endAt: number;\n};\n\nfunction spanOf(run: RunSnapshot, call: ToolCall, runNow: number): Span {\n  const callStart = call.startedAt ?? startOf(run);\n  const sinceStart = Math.max(0, callStart - startOf(run));\n  const startShare = Math.min(1, sinceStart / WINDOW_MS);\n  if (isLiveCall(call)) {\n    return { startShare, endAt: runNow };\n  }\n  return { startShare, endAt: call.endedAt ?? callStart };\n}\n\nfunction barStyleOf(\n  call: ToolCall,\n  span: Span,\n  color: string,\n  isWaiting: boolean\n): CSSProperties {\n  const callStart = call.startedAt ?? 0;\n  const maxShare = 1 - span.startShare;\n  const wanted = Math.max(MIN_SHARE, (span.endAt - callStart) / WINDOW_MS);\n  let ratio = 0;\n  if (maxShare > 0) {\n    ratio = Math.min(1, wanted / maxShare);\n  }\n  const style: CSSProperties = {\n    left: percent(span.startShare * 100),\n    width: percent(maxShare * 100),\n    transform: `scaleX(${ratio})`,\n    backgroundColor: color,\n  };\n  if (isWaiting) {\n    style.backgroundColor = 'transparent';\n    style.backgroundImage = hatchOf(color, 70);\n  }\n  return style;\n}\n\ntype CallBarProps = {\n  run: RunSnapshot;\n  call: ToolCall;\n  color: string;\n};\n\n/** The only leaf that ticks: a bar of a live call grows with the clock, and a finished one holds its width. */\nfunction CallBar({ run, call, color }: CallBarProps) {\n  const isLive = isLiveCall(call);\n  const now = useNow(CLOCK_MS, isLive);\n  const runNow = runNowOf(run, now);\n  const span = spanOf(run, call, runNow);\n  const isWaiting = call.status === 'waiting';\n  const isFailed = call.status === 'failed';\n  const style = barStyleOf(call, span, color, isWaiting);\n\n  return (\n    <span\n      style={style}\n      className={cn(\n        'absolute top-1.5 h-4 origin-left rounded-[3px] transition-transform duration-[250ms] ease-linear',\n        isFailed && 'opacity-40'\n      )}\n    />\n  );\n}\n\ntype SpanBarProps = {\n  run: RunSnapshot;\n  calls: ToolCall[];\n  color: string;\n};\n\nfunction SpanBar({ run, calls, color }: SpanBarProps) {\n  const hasLiveCall = calls.some(isLiveCall);\n  const now = useNow(CLOCK_MS, hasLiveCall);\n  const runNow = runNowOf(run, now);\n  const starts = calls.map((call) => call.startedAt ?? startOf(run));\n  const first = Math.min(...starts);\n  const ends = calls.map((call) => {\n    if (isLiveCall(call)) {\n      return runNow;\n    }\n    return call.endedAt ?? first;\n  });\n  const last = Math.max(...ends);\n  const startShare = Math.min(1, Math.max(0, first - startOf(run)) / WINDOW_MS);\n  const maxShare = 1 - startShare;\n  const wanted = Math.max(MIN_SHARE, (last - first) / WINDOW_MS);\n  let ratio = 0;\n  if (maxShare > 0) {\n    ratio = Math.min(1, wanted / maxShare);\n  }\n  const style: CSSProperties = {\n    left: percent(startShare * 100),\n    width: percent(maxShare * 100),\n    transform: `scaleX(${ratio})`,\n    backgroundColor: `color-mix(in oklab, ${color} 22%, transparent)`,\n  };\n\n  return (\n    <span\n      style={style}\n      className='absolute top-2.5 h-2 origin-left rounded-[3px] transition-transform duration-[250ms] ease-linear'\n    />\n  );\n}\n\nfunction CallClock({ call }: { call: ToolCall }) {\n  if (call.status === 'running') {\n    return <LiveDuration item={call} isRunning className='w-10 text-end' />;\n  }\n  if (call.status === 'done') {\n    const elapsed = elapsedOf(call, call.endedAt ?? 0);\n    return (\n      <span className='w-10 text-end tabular-nums'>\n        {formatDuration(elapsed)}\n      </span>\n    );\n  }\n  return <span className='w-10' />;\n}\n\nfunction dimOf(isDimmed: boolean) {\n  if (isDimmed) {\n    return 'opacity-40';\n  }\n  return undefined;\n}\n\ntype AgentRowsProps = {\n  run: RunSnapshot;\n  agent: RunAgent;\n  isDimmed: boolean;\n};\n\nfunction AgentRows({ run, agent, isDimmed }: AgentRowsProps) {\n  const calls = callsOfAgent(run, agent.id);\n  if (calls.length === 0) {\n    return null;\n  }\n  const color = seriesColorOf(agent.series);\n\n  return (\n    <li\n      className={cn(\n        'flex flex-col transition-opacity duration-200',\n        dimOf(isDimmed)\n      )}\n    >\n      <div className='flex h-7 items-center'>\n        <span\n          className={cn('flex shrink-0 items-center gap-2 pe-2', LABEL_WIDTH)}\n        >\n          <AgentTile agent={agent} size='sm' />\n          <span className='min-w-0 truncate text-[13px] font-medium'>\n            {agent.name}\n          </span>\n        </span>\n        <span className='relative h-7 min-w-0 flex-1'>\n          <SpanBar run={run} calls={calls} color={color} />\n        </span>\n      </div>\n      <ul className='flex flex-col'>\n        {calls.map((call) => (\n          <li\n            key={call.id}\n            className='flex h-7 items-center transition-opacity duration-300 starting:opacity-0'\n          >\n            <span\n              className={cn(\n                'text-muted-foreground flex shrink-0 items-center gap-2 ps-6 pe-2 text-xs',\n                LABEL_WIDTH\n              )}\n            >\n              <span className='min-w-0 flex-1 truncate'>\n                {call.label}\n                <span className='sr-only'>, {toolMetaOf(call.tool).name}</span>\n              </span>\n              <CallClock call={call} />\n            </span>\n            <span className='relative h-7 min-w-0 flex-1'>\n              <CallBar run={run} call={call} color={color} />\n            </span>\n          </li>\n        ))}\n      </ul>\n    </li>\n  );\n}\n\nfunction Playhead({ run }: { run: RunSnapshot }) {\n  const now = useNow(CLOCK_MS, isRunLive(run));\n  if (run.startedAt === undefined) {\n    return null;\n  }\n  const runNow = runNowOf(run, now);\n  const end = run.endedAt ?? runNow;\n  const elapsed = Math.max(0, end - run.startedAt);\n  const share = Math.min(1, elapsed / WINDOW_MS);\n  const style = { transform: `translateX(${share * 100}cqw)` };\n\n  return (\n    <span\n      aria-hidden='true'\n      style={style}\n      className='bg-primary absolute inset-y-0 left-0 w-px transition-transform duration-[250ms] ease-linear'\n    />\n  );\n}\n\nfunction bandToneOf(index: number) {\n  if (index % 2 === 0) {\n    return 'bg-foreground/[0.03]';\n  }\n  return undefined;\n}\n\ntype WaterfallProps = {\n  run: RunSnapshot;\n  focusAgentId: string | null;\n  className?: string;\n};\n\nexport function Waterfall({ run, focusAgentId, className }: WaterfallProps) {\n  const hasFocus = focusAgentId !== null;\n  const isEmpty = run.calls.length === 0;\n\n  return (\n    <Panel\n      panel='waterfall'\n      title='Trace'\n      className={className}\n      meta={\n        <span className='text-muted-foreground text-xs tabular-nums'>\n          {countOf(run.calls.length, 'call')}\n        </span>\n      }\n    >\n      <div className='relative -mx-1 overflow-x-auto px-1 pb-1'>\n        <div className='relative min-w-[32rem]'>\n          <div className='flex h-6 items-end'>\n            <span className={cn('shrink-0', LABEL_WIDTH)} />\n            <div className='relative h-full min-w-0 flex-1 [direction:ltr]'>\n              {TICKS.map((tick, index) => (\n                <span\n                  key={tick}\n                  style={{ left: percent((tick * 100) / WINDOW_MS) }}\n                  className='text-muted-foreground absolute bottom-0.5 text-xs tabular-nums'\n                >\n                  {index === 0 && '0s'}\n                  {index > 0 && `${tick / 1000}s`}\n                </span>\n              ))}\n              <span className='text-muted-foreground absolute right-0 bottom-0.5 text-xs tabular-nums'>\n                {END_LABEL}\n              </span>\n            </div>\n          </div>\n          <div\n            aria-hidden='true'\n            className={cn(\n              'pointer-events-none absolute top-6 right-0 bottom-0 flex [direction:ltr]',\n              'left-36 @2xl:left-44'\n            )}\n          >\n            {TICKS.map((tick, index) => (\n              <span\n                key={tick}\n                className={cn('h-full flex-1', bandToneOf(index))}\n              />\n            ))}\n          </div>\n          <div\n            className={cn(\n              '[container-type:inline-size] pointer-events-none absolute top-6 right-0 bottom-0 [direction:ltr]',\n              'left-36 @2xl:left-44'\n            )}\n          >\n            <Playhead run={run} />\n          </div>\n          <ul aria-label='Calls by agent' className='relative flex flex-col'>\n            {AGENT_ORDER.map((id) => {\n              const agent = run.agents.find((candidate) => candidate.id === id);\n              if (!agent) {\n                return null;\n              }\n              const isDimmed = hasFocus && focusAgentId !== id;\n              return (\n                <AgentRows\n                  key={id}\n                  run={run}\n                  agent={agent}\n                  isDimmed={isDimmed}\n                />\n              );\n            })}\n          </ul>\n          {isEmpty && (\n            <p className='text-muted-foreground relative py-6 text-center text-xs'>\n              No call yet. Each call shows here as a bar on the time axis.\n            </p>\n          )}\n        </div>\n      </div>\n    </Panel>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-07/waterfall.tsx"
    }
  ],
  "categories": [
    "templates",
    "agent-operations"
  ],
  "type": "registry:block"
}