{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "run-05",
  "title": "Context window bar",
  "description": "How full a model context is, its parts on one bar with removable files: near the limit, Compact spreads a summary over the old turns and the bar folds.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/hatch.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/live-duration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/morph-button.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/theme.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/use-session.json",
    "https://ui.ndekocode.dev/r/use-timeouts.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/run/run-05.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useId, useState } from 'react';\n\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { formatTokens } from '@/registry/ndeko/lib/agent-run';\nimport { spokenUnless } from '@/registry/ndeko/lib/demonstration';\nimport { ChevronDownIcon, FileIcon, XIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Fold } from '@/registry/ndeko/ui/chat-motion';\n\nimport { CompactOffer, contextAnnouncementOf } from './_parts/compact-offer';\nimport {\n  foldableTokensOf,\n  freeTokensOf,\n  LEVEL_WORD,\n  levelOf,\n  PART_FILL,\n  percentOf,\n  RESERVE_STYLE,\n  shareOf,\n  usedTokensOf,\n  type Compaction,\n  type ContextBudget,\n  type ContextItem,\n  type ContextPart,\n  type ContextPartId,\n} from './_parts/context';\nimport { ContextHeader } from './_parts/context-header';\nimport { ClockGate } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { rowPresenceOf } from '@/registry/ndeko/lib/motion-presets';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\nimport { TokenCount } from './_parts/token-count';\nimport {\n  FILLING_SESSION,\n  useContextSession,\n  type CompactStatus,\n} from './_parts/use-context-demo';\n\nfunction chevronTurnOf(isOpen: boolean) {\n  if (isOpen) {\n    return 'rotate-180';\n  }\n  return 'rotate-0';\n}\n\ntype BarSegment = {\n  id: ContextPartId;\n  /** Where the segment starts on the bar and how much of it is its own, both from 0 to 1. */\n  start: number;\n  share: number;\n};\n\n/** The order of the parts along the bar. The summary sits where the turns it replaces were. */\nconst BAR_ORDER: ContextPartId[] = [\n  'system',\n  'tools',\n  'files',\n  'summary',\n  'conversation',\n];\n\n/** The summary is drawn last, over the conversation, so it can cover the turns it is folding. */\nconst PAINT_ORDER: ContextPartId[] = [\n  'system',\n  'tools',\n  'files',\n  'conversation',\n  'summary',\n];\n\nconst BAR_TRAVEL =\n  'transition-transform duration-500 ease-(--ease-out-strong) motion-reduce:transition-none';\n\nfunction tokensOfPart(budget: ContextBudget, id: ContextPartId) {\n  const part = budget.parts.find((candidate) => candidate.id === id);\n  return part?.tokens ?? 0;\n}\n\nfunction segmentsOf(budget: ContextBudget) {\n  const segments: BarSegment[] = [];\n  let start = 0;\n  for (const id of BAR_ORDER) {\n    const tokens = tokensOfPart(budget, id);\n    const share = shareOf(tokens, budget);\n    segments.push({ id, start, share });\n    start += share;\n  }\n  return segments;\n}\n\n/**\n * While the context is compacted, the summary spreads over the turns it folds. When the compaction\n * lands it shrinks to its own size and the turns that stay slide against it: the bar folds.\n */\nfunction withFolding(segments: BarSegment[], foldingShare: number) {\n  return segments.map((segment) => {\n    if (segment.id !== 'summary') {\n      return segment;\n    }\n    return { ...segment, share: segment.share + foldingShare };\n  });\n}\n\nfunction foldingShareOf(budget: ContextBudget, compactStatus: CompactStatus) {\n  if (compactStatus !== 'compacting') {\n    return 0;\n  }\n  const folding = foldableTokensOf(budget);\n  return shareOf(folding, budget);\n}\n\nfunction paintedSegmentsOf(segments: BarSegment[]) {\n  const painted: BarSegment[] = [];\n  for (const id of PAINT_ORDER) {\n    const segment = segments.find((candidate) => candidate.id === id);\n    if (segment) {\n      painted.push(segment);\n    }\n  }\n  return painted;\n}\n\n/** A segment is the whole bar, moved to its start and scaled to its share: no width to lay out. */\nfunction segmentStyleOf(segment: BarSegment): React.CSSProperties {\n  const offset = segment.start * 100;\n  return {\n    backgroundColor: PART_FILL[segment.id],\n    transform: `translateX(${offset}%) scaleX(${segment.share})`,\n  };\n}\n\n/** A gap after a segment: a mark of the surface behind the bar, moved to where the segment ends. */\nfunction gapStyleOf(segment: BarSegment): React.CSSProperties {\n  const end = segment.start + segment.share;\n  const offset = end * 100;\n  return { transform: `translateX(${offset}%)` };\n}\n\nfunction isFilled(segment: BarSegment) {\n  return segment.share > 0;\n}\n\nfunction spokenUsageOf(budget: ContextBudget) {\n  const used = usedTokensOf(budget);\n  const level = levelOf(budget);\n  const usedText = formatTokens(used);\n  const limitText = formatTokens(budget.limit);\n  return `${usedText} of ${limitText} tokens used, ${LEVEL_WORD[level]}`;\n}\n\nfunction PartDot({ fill }: { fill: string }) {\n  return (\n    <span\n      aria-hidden='true'\n      className='size-2 shrink-0 rounded-full'\n      style={{ backgroundColor: fill }}\n    />\n  );\n}\n\nfunction SegmentBar({\n  budget,\n  compactStatus,\n}: {\n  budget: ContextBudget;\n  compactStatus: CompactStatus;\n}) {\n  const used = usedTokensOf(budget);\n  const reservePercent = percentOf(budget.reserve, budget);\n  const spoken = spokenUsageOf(budget);\n  const foldingShare = foldingShareOf(budget, compactStatus);\n  const laidOut = segmentsOf(budget);\n  const segments = withFolding(laidOut, foldingShare);\n  const painted = paintedSegmentsOf(segments);\n  const filled = segments.filter(isFilled);\n\n  return (\n    <div\n      role='meter'\n      aria-label='Context used'\n      aria-valuemin={0}\n      aria-valuemax={budget.limit}\n      aria-valuenow={used}\n      aria-valuetext={spoken}\n      className='bg-foreground/[0.05] relative h-3 overflow-hidden rounded-full'\n    >\n      {painted.map((segment) => (\n        <span\n          key={segment.id}\n          className={cn('absolute inset-0 origin-left', BAR_TRAVEL)}\n          style={segmentStyleOf(segment)}\n        />\n      ))}\n      {filled.map((segment) => (\n        <span\n          key={segment.id}\n          className={cn('absolute inset-0', BAR_TRAVEL)}\n          style={gapStyleOf(segment)}\n        >\n          <span className='bg-card absolute inset-y-0 start-0 w-0.5' />\n        </span>\n      ))}\n      <span\n        className='border-card absolute inset-y-0 end-0 border-s-2'\n        style={{ ...RESERVE_STYLE, width: `${reservePercent}%` }}\n      />\n    </div>\n  );\n}\n\nfunction PartRow({ part }: { part: ContextPart }) {\n  return (\n    <div className='flex h-8 items-center gap-2.5 px-2 text-[13px]'>\n      <PartDot fill={PART_FILL[part.id]} />\n      <span className='min-w-0 flex-1 truncate'>{part.label}</span>\n      <TokenCount tokens={part.tokens} className='text-muted-foreground' />\n    </div>\n  );\n}\n\nfunction FileRow({\n  file,\n  onRemove,\n}: {\n  file: ContextItem;\n  onRemove?: (itemId: string) => void;\n}) {\n  const canRemove = onRemove !== undefined;\n\n  return (\n    <div className='flex h-8 items-center gap-2.5 ps-6 pe-1 text-[13px]'>\n      <FileIcon className='text-muted-foreground size-3.5 shrink-0' />\n      <span className='min-w-0 flex-1 truncate font-mono text-xs'>\n        {file.label}\n      </span>\n      <TokenCount tokens={file.tokens} className='text-muted-foreground' />\n      {canRemove && (\n        <button\n          type='button'\n          aria-label={`Remove ${file.label} from the context`}\n          onClick={() => onRemove?.(file.id)}\n          className='text-muted-foreground hover:text-foreground hover:bg-foreground/5 focus-visible:ring-ring/25 inline-flex size-6 cursor-pointer items-center justify-center rounded-md outline-none focus-visible:ring-[3px] active:scale-[0.97]'\n        >\n          <XIcon className='size-3.5' />\n        </button>\n      )}\n    </div>\n  );\n}\n\nfunction FilesRow({\n  part,\n  onRemove,\n}: {\n  part: ContextPart;\n  onRemove?: (itemId: string) => void;\n}) {\n  const [isOpen, setIsOpen] = useState(false);\n  const panelId = useId();\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const rowPresence = rowPresenceOf(shouldReduceMotion);\n  const hasFiles = part.items.length > 0;\n\n  function toggle() {\n    setIsOpen((current) => !current);\n  }\n\n  return (\n    <div>\n      <button\n        type='button'\n        aria-expanded={isOpen}\n        aria-controls={panelId}\n        onClick={toggle}\n        className='hover:bg-foreground/[0.03] focus-visible:ring-ring/25 flex h-8 w-full cursor-pointer items-center gap-2.5 rounded-md px-2 text-start text-[13px] outline-none focus-visible:ring-[3px]'\n      >\n        <PartDot fill={PART_FILL[part.id]} />\n        <span className='min-w-0 flex-1 truncate'>\n          {part.label}\n          <span className='text-muted-foreground ms-1.5 tabular-nums'>\n            {part.items.length}\n          </span>\n        </span>\n        <TokenCount tokens={part.tokens} className='text-muted-foreground' />\n        <ChevronDownIcon\n          className={cn(\n            'text-muted-foreground size-4 shrink-0 transition-transform duration-200 ease-(--ease-out-strong)',\n            chevronTurnOf(isOpen)\n          )}\n        />\n      </button>\n      <Fold open={isOpen} id={panelId}>\n        <ul aria-label='Files in the context'>\n          <AnimatePresence initial={false}>\n            {part.items.map((file) => (\n              <motion.li\n                key={file.id}\n                className='overflow-hidden'\n                {...rowPresence}\n              >\n                <FileRow file={file} onRemove={onRemove} />\n              </motion.li>\n            ))}\n          </AnimatePresence>\n        </ul>\n        {!hasFiles && (\n          <p className='text-muted-foreground ps-6 text-xs leading-8'>\n            No file left in the context\n          </p>\n        )}\n      </Fold>\n    </div>\n  );\n}\n\nfunction LegendRow({\n  part,\n  onRemoveItem,\n}: {\n  part: ContextPart;\n  onRemoveItem?: (itemId: string) => void;\n}) {\n  if (part.id === 'files') {\n    return <FilesRow part={part} onRemove={onRemoveItem} />;\n  }\n  return <PartRow part={part} />;\n}\n\nexport type ContextWindowBarProps = {\n  budget: ContextBudget;\n  onRemoveItem?: (itemId: string) => void;\n  onCompact?: () => void;\n  compactStatus?: CompactStatus;\n  canCompact?: boolean;\n  compaction?: Compaction | null;\n  /** Shows Compact held down, for a demonstration that presses it. */\n  isCompactPressed?: boolean;\n  className?: string;\n};\n\nexport function ContextWindowBar({\n  budget,\n  onRemoveItem,\n  onCompact,\n  compactStatus = 'idle',\n  canCompact = false,\n  compaction = null,\n  isCompactPressed = false,\n  className,\n}: ContextWindowBarProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const rowPresence = rowPresenceOf(shouldReduceMotion);\n  const free = freeTokensOf(budget);\n  const titleId = useId();\n\n  return (\n    <section\n      aria-labelledby={titleId}\n      className={cn(\n        'bg-card hairline-ring ring-border flex flex-col gap-4 rounded-xl p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)]',\n        className\n      )}\n    >\n      <ContextHeader budget={budget} titleId={titleId} />\n\n      <SegmentBar budget={budget} compactStatus={compactStatus} />\n\n      <ul aria-label='What fills the context' className='-mx-2 flex flex-col'>\n        <AnimatePresence initial={false}>\n          {budget.parts.map((part) => (\n            <motion.li\n              key={part.id}\n              className='overflow-hidden'\n              {...rowPresence}\n            >\n              <LegendRow part={part} onRemoveItem={onRemoveItem} />\n            </motion.li>\n          ))}\n        </AnimatePresence>\n        <li className='flex h-8 items-center gap-2.5 px-2 text-[13px]'>\n          <span\n            aria-hidden='true'\n            className='bg-foreground/[0.08] size-2 shrink-0 rounded-full'\n          />\n          <span className='min-w-0 flex-1 truncate'>Free</span>\n          <TokenCount tokens={free} className='text-muted-foreground' />\n        </li>\n        <li className='flex h-8 items-center gap-2.5 px-2 text-[13px]'>\n          <span\n            aria-hidden='true'\n            className='size-2 shrink-0 rounded-full'\n            style={RESERVE_STYLE}\n          />\n          <span className='min-w-0 flex-1 truncate'>Held for the answer</span>\n          <TokenCount\n            tokens={budget.reserve}\n            className='text-muted-foreground'\n          />\n        </li>\n      </ul>\n\n      <CompactOffer\n        budget={budget}\n        canCompact={canCompact}\n        compactStatus={compactStatus}\n        compaction={compaction}\n        onCompact={onCompact}\n        isPressed={isCompactPressed}\n      />\n    </section>\n  );\n}\n\nexport default function Run05() {\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    canReplay,\n    pressed,\n    budget,\n    compaction,\n    compactStatus,\n    canCompact,\n    removeFile,\n    compact,\n    replay,\n  } = useContextSession(FILLING_SESSION);\n  const level = levelOf(budget);\n  const announcement = contextAnnouncementOf(\n    level,\n    LEVEL_WORD[level],\n    compaction\n  );\n\n  useKeptHeight(ref);\n\n  return (\n    <div\n      ref={ref}\n      className='flex min-h-[29.5rem] w-full max-w-[26rem] flex-col gap-2'\n    >\n      <ClockGate isActive={isInView}>\n        <ContextWindowBar\n          budget={budget}\n          onRemoveItem={removeFile}\n          onCompact={compact}\n          compactStatus={compactStatus}\n          canCompact={canCompact}\n          compaction={compaction}\n          isCompactPressed={pressed === 'compact'}\n        />\n      </ClockGate>\n      <div className='flex h-7 items-center justify-end'>\n        <ReplayButton\n          isShown={canReplay}\n          onReplay={replay}\n          label='Replay the conversation'\n        />\n      </div>\n      <LiveRegion message={spokenUnless(isAutoplaying, announcement)} />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/run/run-05.tsx"
    },
    {
      "path": "registry/ndeko/components/run/_parts/compact-offer.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { formatTokens } from '@/registry/ndeko/lib/agent-run';\nimport { pressedSolidOf } from '@/registry/ndeko/lib/demonstration';\nimport { CheckIcon } from '@/registry/ndeko/lib/icons';\n\nimport {\n  compactionLineOf,\n  freeTokensOf,\n  levelOf,\n  type Compaction,\n  type ContextBudget,\n  type ContextLevel,\n} from './context';\nimport { MorphButton, type MorphState } from '@/registry/ndeko/ui/morph-button';\nimport { risePresenceOf } from '@/registry/ndeko/lib/motion-presets';\nimport type { CompactStatus } from './use-context-demo';\n\nconst COMPACT_LABELS: Record<MorphState, string> = {\n  idle: 'Compact',\n  busy: 'Compacting',\n  done: 'Compacted',\n};\n\nfunction morphStateOf(status: CompactStatus): MorphState {\n  if (status === 'compacting') {\n    return 'busy';\n  }\n  return 'idle';\n}\n\nfunction isOfferShown(\n  level: ContextLevel,\n  canCompact: boolean,\n  status: CompactStatus\n) {\n  const isCompactSoon = level === 'compact';\n  const isCompacting = status === 'compacting';\n  const isAvailable = canCompact || isCompacting;\n  return isCompactSoon && isAvailable;\n}\n\nfunction traceOf(compaction: Compaction | null, isOffered: boolean) {\n  if (isOffered) {\n    return null;\n  }\n  return compaction;\n}\n\ntype CompactOfferProps = {\n  budget: ContextBudget;\n  canCompact: boolean;\n  compactStatus: CompactStatus;\n  compaction: Compaction | null;\n  onCompact?: () => void;\n  /** Shows Compact held down, for a demonstration that presses it. */\n  isPressed?: boolean;\n};\n\nexport function CompactOffer({\n  budget,\n  canCompact,\n  compactStatus,\n  compaction,\n  onCompact,\n  isPressed = false,\n}: CompactOfferProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const risePresence = risePresenceOf(shouldReduceMotion);\n  const level = levelOf(budget);\n  const free = freeTokensOf(budget);\n  const freeText = formatTokens(free);\n  const isOffered = isOfferShown(level, canCompact, compactStatus);\n  const trace = traceOf(compaction, isOffered);\n\n  return (\n    <AnimatePresence initial={false} mode='popLayout'>\n      {isOffered && (\n        <motion.div key='offer' className='@container' {...risePresence}>\n          <div className='bg-warning/10 flex flex-col gap-2.5 rounded-lg p-3 @lg:flex-row @lg:items-center'>\n            <p className='text-warning-foreground min-w-0 flex-1 text-xs leading-5'>\n              {freeText} tokens left before the reserve. Fold the older turns\n              into a summary to keep going.\n            </p>\n            <MorphButton\n              type='button'\n              size='sm'\n              state={morphStateOf(compactStatus)}\n              labels={COMPACT_LABELS}\n              onClick={onCompact}\n              className={pressedSolidOf(isPressed)}\n            />\n          </div>\n        </motion.div>\n      )}\n      {trace && (\n        <motion.p\n          key='trace'\n          className='text-muted-foreground flex items-center gap-2 text-xs'\n          {...risePresence}\n        >\n          <CheckIcon className='text-success-foreground size-3.5' />\n          {compactionLineOf(trace)}\n        </motion.p>\n      )}\n    </AnimatePresence>\n  );\n}\n\nexport function contextAnnouncementOf(\n  level: ContextLevel,\n  levelWord: string,\n  compaction: Compaction | null\n) {\n  if (compaction) {\n    const line = compactionLineOf(compaction);\n    return `${line}. Context: ${levelWord}`;\n  }\n  if (level === 'compact') {\n    return `Context: ${levelWord}. Compact is available`;\n  }\n  return `Context: ${levelWord}`;\n}\n",
      "type": "registry:component",
      "target": "components/run/_parts/compact-offer.tsx"
    },
    {
      "path": "registry/ndeko/components/run/_parts/context-header.tsx",
      "content": "'use client';\n\nimport { WordRoll } from '@/components/core/word-roll';\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nimport {\n  LEVEL_LABELS,\n  LEVEL_TONE,\n  LEVEL_WORD,\n  levelOf,\n  usedTokensOf,\n  type ContextBudget,\n} from './context';\nimport { TokenCount } from './token-count';\n\ntype ContextHeaderProps = {\n  budget: ContextBudget;\n  titleId: string;\n  title?: string;\n};\n\nexport function ContextHeader({\n  budget,\n  titleId,\n  title = 'Context',\n}: ContextHeaderProps) {\n  const used = usedTokensOf(budget);\n  const level = levelOf(budget);\n\n  return (\n    <header className='flex items-start justify-between gap-3'>\n      <div className='min-w-0'>\n        <h3 id={titleId} className='text-sm font-medium'>\n          {title}\n        </h3>\n        <p\n          className={cn(\n            'text-xs transition-colors duration-200',\n            LEVEL_TONE[level]\n          )}\n        >\n          <WordRoll text={LEVEL_WORD[level]} labels={LEVEL_LABELS} />\n        </p>\n      </div>\n      <p className='text-[13px] tabular-nums'>\n        <TokenCount tokens={used} className='font-medium' />\n        <span className='text-muted-foreground'>\n          {' of '}\n          <TokenCount tokens={budget.limit} />\n        </span>\n      </p>\n    </header>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/run/_parts/context-header.tsx"
    },
    {
      "path": "registry/ndeko/components/run/_parts/context.ts",
      "content": "import { hatchOf } from '@/registry/ndeko/lib/hatch';\n\nexport type ContextPartId =\n  'system' | 'tools' | 'files' | 'summary' | 'conversation';\n\n/** A place in the window: one of its parts, the room left, or what is held back for the answer. */\nexport type ContextSlot = ContextPartId | 'free' | 'reserve';\n\nexport type ContextItem = {\n  id: string;\n  label: string;\n  tokens: number;\n};\n\nexport type ContextPart = {\n  id: ContextPartId;\n  label: string;\n  tokens: number;\n  items: ContextItem[];\n};\n\nexport type ContextBudget = {\n  limit: number;\n  /** Held back for the model's answer: never filled by the context. */\n  reserve: number;\n  parts: ContextPart[];\n};\n\nexport type ContextLevel = 'room' | 'filling' | 'compact';\n\nexport type Compaction = {\n  foldedTurns: number;\n  summaryTokens: number;\n};\n\nexport const CONTEXT_LIMIT = 200_000;\n\nexport const CONTEXT_RESERVE = 16_000;\n\n/** Parts are parts of one whole, not entities: they take the chart ramp and a muted fill, never the series. */\nexport const PART_FILL: Record<ContextPartId, string> = {\n  system: 'color-mix(in oklab, var(--muted-foreground) 30%, transparent)',\n  tools: 'var(--chart-3)',\n  files: 'var(--chart-2)',\n  summary: 'var(--chart-4)',\n  conversation: 'var(--chart-1)',\n};\n\nexport const RESERVE_STYLE = {\n  backgroundColor:\n    'color-mix(in oklab, var(--muted-foreground) 8%, transparent)',\n  backgroundImage: hatchOf('var(--muted-foreground)', 40),\n};\n\nexport const LEVEL_WORD: Record<ContextLevel, string> = {\n  room: 'Plenty of room',\n  filling: 'Filling up',\n  compact: 'Compact soon',\n};\n\nexport const LEVEL_LABELS = [\n  LEVEL_WORD.room,\n  LEVEL_WORD.filling,\n  LEVEL_WORD.compact,\n];\n\nexport const LEVEL_TONE: Record<ContextLevel, string> = {\n  room: 'text-muted-foreground',\n  filling: 'text-foreground',\n  compact: 'text-warning-foreground',\n};\n\nconst FILLING_FROM = 0.6;\n\nconst COMPACT_FROM = 0.85;\n\n/** The newest turns stay word for word after a compaction. */\nconst KEPT_TURNS = 2;\n\nconst SUMMARY_SHARE = 0.08;\n\nexport const SYSTEM_ITEMS: ContextItem[] = [\n  { id: 'system-prompt', label: 'System prompt', tokens: 4_100 },\n  { id: 'system-notes', label: 'Saved notes', tokens: 2_100 },\n];\n\nexport const TOOL_ITEMS: ContextItem[] = [\n  { id: 'tool-search', label: 'web_search results', tokens: 1_900 },\n  { id: 'tool-page', label: 'fetch_page result', tokens: 2_300 },\n  { id: 'tool-sheet', label: 'read_sheet rows', tokens: 2_600 },\n  { id: 'tool-script', label: 'run_script output', tokens: 1_800 },\n];\n\nexport const FILE_ITEMS: ContextItem[] = [\n  { id: 'file-invoices', label: 'q3-invoices.xlsx', tokens: 21_400 },\n  { id: 'file-contract', label: 'brightmoor-contract.pdf', tokens: 18_600 },\n  { id: 'file-pricing', label: 'pricing-page.html', tokens: 9_800 },\n  { id: 'file-notes', label: 'vendor-notes.md', tokens: 3_100 },\n];\n\nconst TURN_TOKENS = [\n  5_200, 7_400, 9_800, 6_100, 12_400, 8_300, 10_900, 7_700, 13_600, 9_200,\n  11_800, 8_600,\n];\n\nfunction turnOf(tokens: number, index: number): ContextItem {\n  const number = index + 1;\n  return { id: `turn-${number}`, label: `Turn ${number}`, tokens };\n}\n\nexport const TURNS: ContextItem[] = TURN_TOKENS.map(turnOf);\n\nexport function sumTokens(items: readonly { tokens: number }[]) {\n  let total = 0;\n  for (const item of items) {\n    total += item.tokens;\n  }\n  return total;\n}\n\n/** What the run holds before any conversation: system, tools and every file. */\nconst SYSTEM_TOKENS = sumTokens(SYSTEM_ITEMS);\n\nconst TOOL_TOKENS = sumTokens(TOOL_ITEMS);\n\nconst FILE_TOKENS = sumTokens(FILE_ITEMS);\n\nexport const BASE_TOKENS = SYSTEM_TOKENS + TOOL_TOKENS + FILE_TOKENS;\n\nexport function usedTokensOf(budget: ContextBudget) {\n  return sumTokens(budget.parts);\n}\n\nexport function freeTokensOf(budget: ContextBudget) {\n  const used = usedTokensOf(budget);\n  const free = budget.limit - budget.reserve - used;\n  return Math.max(0, free);\n}\n\nexport function shareOf(tokens: number, budget: ContextBudget) {\n  return tokens / budget.limit;\n}\n\nexport function percentOf(tokens: number, budget: ContextBudget) {\n  const share = shareOf(tokens, budget);\n  return share * 100;\n}\n\nexport function levelOf(budget: ContextBudget): ContextLevel {\n  const used = usedTokensOf(budget);\n  const share = shareOf(used, budget);\n  if (share < FILLING_FROM) {\n    return 'room';\n  }\n  if (share <= COMPACT_FROM) {\n    return 'filling';\n  }\n  return 'compact';\n}\n\nexport function turnsWithin(conversationTokens: number) {\n  const turns: ContextItem[] = [];\n  let total = 0;\n  for (const turn of TURNS) {\n    const next = total + turn.tokens;\n    if (next > conversationTokens) {\n      break;\n    }\n    turns.push(turn);\n    total = next;\n  }\n  return turns;\n}\n\n/** The tokens of the turns a compaction folds away: every turn of the conversation but the newest ones. */\nexport function foldableTokensOf(budget: ContextBudget) {\n  const conversation = budget.parts.find((part) => part.id === 'conversation');\n  if (!conversation) {\n    return 0;\n  }\n  const foldedCount = conversation.items.length - KEPT_TURNS;\n  if (foldedCount < 1) {\n    return 0;\n  }\n  const folded = conversation.items.slice(0, foldedCount);\n  return sumTokens(folded);\n}\n\nexport function compactionOf(turns: ContextItem[]): Compaction | null {\n  const foldedTurns = turns.length - KEPT_TURNS;\n  if (foldedTurns < 2) {\n    return null;\n  }\n  const folded = turns.slice(0, foldedTurns);\n  const foldedTokens = sumTokens(folded);\n  const rawSummary = foldedTokens * SUMMARY_SHARE;\n  const summaryHundreds = Math.round(rawSummary / 100);\n  const summaryTokens = summaryHundreds * 100;\n  return { foldedTurns, summaryTokens };\n}\n\nfunction partOf(\n  id: ContextPartId,\n  label: string,\n  items: ContextItem[]\n): ContextPart {\n  return { id, label, tokens: sumTokens(items), items };\n}\n\nfunction turnCountOf(count: number) {\n  if (count === 1) {\n    return '1 turn';\n  }\n  return `${count} turns`;\n}\n\ntype BudgetInput = {\n  turns: ContextItem[];\n  removedFileIds: readonly string[];\n  compaction: Compaction | null;\n};\n\nexport function budgetOf({\n  turns,\n  removedFileIds,\n  compaction,\n}: BudgetInput): ContextBudget {\n  const files = FILE_ITEMS.filter((file) => !removedFileIds.includes(file.id));\n  const foldedCount = compaction?.foldedTurns ?? 0;\n  const liveTurns = turns.slice(foldedCount);\n  const parts: ContextPart[] = [\n    partOf('system', 'System', SYSTEM_ITEMS),\n    partOf('tools', 'Tools', TOOL_ITEMS),\n    partOf('files', 'Files', files),\n  ];\n  if (compaction) {\n    const summaryLabel = `Summary of ${turnCountOf(compaction.foldedTurns)}`;\n    const summary = {\n      id: 'summary',\n      label: summaryLabel,\n      tokens: compaction.summaryTokens,\n    };\n    parts.push(partOf('summary', 'Summary', [summary]));\n  }\n  parts.push(partOf('conversation', 'Conversation', liveTurns));\n  return { limit: CONTEXT_LIMIT, reserve: CONTEXT_RESERVE, parts };\n}\n\nexport function compactionLineOf(compaction: Compaction) {\n  const turns = turnCountOf(compaction.foldedTurns);\n  const thousands = compaction.summaryTokens / 1000;\n  const summary = `${thousands.toFixed(1)}k`;\n  return `Folded ${turns} into a ${summary} summary`;\n}\n",
      "type": "registry:component",
      "target": "components/run/_parts/context.ts"
    },
    {
      "path": "registry/ndeko/components/run/_parts/token-count.tsx",
      "content": "'use client';\n\nimport { MotionNumber } from '@/components/core/motion-number';\n\nconst THOUSANDS: Intl.NumberFormatOptions = { maximumFractionDigits: 1 };\n\ntype TokenCountProps = {\n  tokens: number;\n  className?: string;\n};\n\nexport function TokenCount({ tokens, className }: TokenCountProps) {\n  const thousands = tokens / 1000;\n  return (\n    <MotionNumber\n      value={thousands}\n      format={THOUSANDS}\n      suffix='k'\n      className={className}\n    />\n  );\n}\n",
      "type": "registry:component",
      "target": "components/run/_parts/token-count.tsx"
    },
    {
      "path": "registry/ndeko/components/run/_parts/use-context-demo.ts",
      "content": "'use client';\n\nimport {\n  useSession,\n  type SessionConfig,\n  type SessionStep,\n} from '@/registry/ndeko/hooks/use-session';\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\n\nimport {\n  budgetOf,\n  compactionOf,\n  TURNS,\n  type Compaction,\n  type ContextSlot,\n} from './context';\n\nexport type CompactStatus = 'idle' | 'compacting';\n\nconst COMPACT_MS = 900;\n\n/** An offer that waits on a person is taken by the demonstration after this long. */\nconst COMPACT_AFTER_MS = 2500;\n\nexport type ContextState = {\n  /** How many turns of the conversation the context holds. */\n  turnCount: number;\n  removedFileIds: string[];\n  compaction: Compaction | null;\n  compactStatus: CompactStatus;\n  /** The part a demonstration points at, in the views that light one part. */\n  spotlight: ContextSlot | null;\n  /** Whether the breakdown is open, in the views that fold it. */\n  isBreakdownOpen: boolean;\n};\n\nexport type ContextAction =\n  | { type: 'turn' }\n  | { type: 'removeFile'; fileId: string }\n  | { type: 'compact' }\n  | { type: 'compacted' }\n  | { type: 'spotlight'; slot: ContextSlot | null }\n  | { type: 'breakdown'; isOpen: boolean };\n\nexport type ContextStep = SessionStep<ContextState, ContextAction>;\n\nexport type ContextSession = SessionConfig<ContextState, ContextAction>;\n\nexport function contextStateAt(turnCount: number): ContextState {\n  return {\n    turnCount,\n    removedFileIds: [],\n    compaction: null,\n    compactStatus: 'idle',\n    spotlight: null,\n    isBreakdownOpen: false,\n  };\n}\n\nfunction turnsIn(state: ContextState) {\n  return TURNS.slice(0, state.turnCount);\n}\n\n/** Compact is offered again only once new turns can be folded into the summary. */\nfunction canCompactIn(state: ContextState) {\n  const turns = turnsIn(state);\n  const next = compactionOf(turns);\n  const foldedNow = state.compaction?.foldedTurns ?? 0;\n  const foldableNext = next?.foldedTurns ?? 0;\n  const hasNewTurnsToFold = foldableNext > foldedNow;\n  const isIdle = state.compactStatus === 'idle';\n  return hasNewTurnsToFold && isIdle;\n}\n\nfunction withTurn(state: ContextState): ContextState {\n  const hasMore = state.turnCount < TURNS.length;\n  if (!hasMore) {\n    return state;\n  }\n  return { ...state, turnCount: state.turnCount + 1 };\n}\n\nfunction withFileRemoved(state: ContextState, fileId: string): ContextState {\n  const removedFileIds = [...state.removedFileIds, fileId];\n  return { ...state, removedFileIds };\n}\n\nfunction withCompactStarted(state: ContextState): ContextState {\n  if (!canCompactIn(state)) {\n    return state;\n  }\n  return { ...state, compactStatus: 'compacting' };\n}\n\n/** The script and the hand of a person may both land the same compaction: only the first one counts. */\nfunction withCompactLanded(state: ContextState): ContextState {\n  if (state.compactStatus !== 'compacting') {\n    return state;\n  }\n  const turns = turnsIn(state);\n  const compaction = compactionOf(turns);\n  return { ...state, compaction, compactStatus: 'idle' };\n}\n\nexport function reduceContext(\n  state: ContextState,\n  action: ContextAction\n): ContextState {\n  switch (action.type) {\n    case 'turn':\n      return withTurn(state);\n    case 'removeFile':\n      return withFileRemoved(state, action.fileId);\n    case 'compact':\n      return withCompactStarted(state);\n    case 'compacted':\n      return withCompactLanded(state);\n    case 'spotlight':\n      return { ...state, spotlight: action.slot };\n    case 'breakdown':\n      return { ...state, isBreakdownOpen: action.isOpen };\n  }\n}\n\nfunction hasCompacted(state: ContextState) {\n  const isCompacting = state.compactStatus === 'compacting';\n  const isCompacted = state.compaction !== null;\n  return isCompacting || isCompacted;\n}\n\n/** A turn that arrives on its own: the conversation going on, which always plays. */\nexport function turnStep(after: number): ContextStep {\n  return { after, action: { type: 'turn' } };\n}\n\n/** A message a person sends: the demonstration presses Send for them until they take over. */\nexport function sendStep(after: number, turnCount: number): ContextStep {\n  return {\n    after,\n    by: 'person',\n    press: 'send',\n    action: { type: 'turn' },\n    isAnswered: (state) => state.turnCount >= turnCount,\n  };\n}\n\n/** Compact pressed by the demonstration once it is offered, then the summary landing. */\nexport const COMPACT_STEPS: ContextStep[] = [\n  {\n    after: COMPACT_AFTER_MS,\n    by: 'person',\n    press: 'compact',\n    action: { type: 'compact' },\n    isAnswered: hasCompacted,\n  },\n  { after: COMPACT_MS, action: { type: 'compacted' } },\n];\n\n/** The demos open on a conversation already under way and fill it one turn at a time. */\nconst OPENING_TURNS = 5;\n\nconst TURN_EVERY_MS = 900;\n\nfunction arrivingTurns(): ContextStep[] {\n  const count = TURNS.length - OPENING_TURNS;\n  return Array.from({ length: count }, () => turnStep(TURN_EVERY_MS));\n}\n\n/** The conversation fills until Compact is offered, the demonstration takes it and the summary lands. */\nexport const FILLING_SCRIPT: ContextStep[] = [\n  ...arrivingTurns(),\n  ...COMPACT_STEPS,\n];\n\n/**\n * Under reduced motion nothing plays: the context rests full, with Compact on offer, which a person\n * can still take.\n */\nexport const FILLING_SESSION: ContextSession = {\n  reducer: reduceContext,\n  initial: contextStateAt(OPENING_TURNS),\n  resting: contextStateAt(TURNS.length),\n  script: FILLING_SCRIPT,\n  loopAfter: 3400,\n};\n\n/** A context that fills turn by turn, played as a session: turns arrive, a person removes files and compacts. */\nexport function useContextSession(session: ContextSession) {\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n  } = useSession(session);\n  const { schedule, clearAll } = useTimeouts();\n  const turns = turnsIn(state);\n  const { removedFileIds, compaction } = state;\n  const budget = budgetOf({ turns, removedFileIds, compaction });\n  const budgetBefore = budgetOf({ turns, removedFileIds, compaction: null });\n  const canCompact = canCompactIn(state);\n  const canReplay = isFinished && !isAutoplaying;\n\n  function removeFile(fileId: string) {\n    act({ type: 'removeFile', fileId });\n  }\n\n  function compact() {\n    if (!canCompact) {\n      return;\n    }\n    act({ type: 'compact' });\n    schedule(() => act({ type: 'compacted' }), COMPACT_MS);\n  }\n\n  function send() {\n    act({ type: 'turn' });\n  }\n\n  function setBreakdownOpen(isOpen: boolean) {\n    act({ type: 'breakdown', isOpen });\n  }\n\n  function replay() {\n    clearAll();\n    restart();\n  }\n\n  return {\n    ref,\n    isInView,\n    isAutoplaying,\n    canReplay,\n    pressed,\n    turns,\n    budget,\n    budgetBefore,\n    compaction,\n    compactStatus: state.compactStatus,\n    canCompact,\n    spotlight: state.spotlight,\n    isBreakdownOpen: state.isBreakdownOpen,\n    removeFile,\n    compact,\n    send,\n    setBreakdownOpen,\n    replay,\n  };\n}\n",
      "type": "registry:component",
      "target": "components/run/_parts/use-context-demo.ts"
    }
  ],
  "categories": [
    "components",
    "run"
  ],
  "type": "registry:component"
}