{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "agent-ops-09",
  "title": "Run pivot",
  "description": "A pivot table over agent runs: a field chip flies from the list into Rows, Columns, Values or Filters and the shaded table regroups while it is still held, with subtotals, folding groups, Swap, a CSV export and a question box that fills the wells.",
  "dependencies": [
    "@dnd-kit/core",
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.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/demonstration.json",
    "https://ui.ndekocode.dev/r/dropdown-menu.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/input.json",
    "https://ui.ndekocode.dev/r/live-duration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/replay-button.json",
    "https://ui.ndekocode.dev/r/theme.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/blocks/agent-ops/agent-ops-09/index.tsx",
      "content": "'use client';\n\nimport {\n  DndContext,\n  DragOverlay,\n  MouseSensor,\n  TouchSensor,\n  pointerWithin,\n  useSensor,\n  useSensors,\n  type DragEndEvent,\n  type DragOverEvent,\n  type DragStartEvent,\n} from '@dnd-kit/core';\nimport { LayoutGroup } from 'motion/react';\nimport { useId, useState } from 'react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { useSession } from '@/registry/ndeko/hooks/use-session';\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\nimport {\n  pressedSolidOf,\n  spokenUnless,\n} from '@/registry/ndeko/lib/demonstration';\nimport {\n  CheckIcon,\n  DownloadIcon,\n  RepeatIcon,\n  XIcon,\n} from '@/registry/ndeko/lib/icons';\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 { Fold, Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { Input } from '@/registry/ndeko/ui/input';\nimport { ClockGate } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\n\nimport { ASK_EXAMPLE } from './ask';\nimport { csvRowsOf, downloadCsv } from './csv';\nimport { fieldOf, FIELDS, RECORDS, type FieldId } from './data';\nimport { CHIP_SHAPE } from './field-chip';\nimport {\n  canAccept,\n  pivotOf,\n  valueLabelOf,\n  WELL_IDS,\n  wellOf,\n  type PivotTable,\n  type WellId,\n  type Wells,\n} from './pivot';\nimport { formatValue, PivotTableView } from './pivot-table';\nimport {\n  INITIAL,\n  LOOP_AFTER_MS,\n  reducer,\n  RESTING,\n  SCRIPT,\n  shownWellsOf,\n  type PivotAction,\n  type Preview,\n} from './session';\nimport { FieldList, WellGrid } from './wells';\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: RESTING,\n  script: SCRIPT,\n  loopAfter: LOOP_AFTER_MS,\n};\n\nconst MOUSE = { activationConstraint: { distance: 4 } };\n\nconst TOUCH = { activationConstraint: { delay: 180, tolerance: 6 } };\n\nconst EXPORTED_FOR_MS = 1600;\n\nconst FILE_NAME = 'agent-runs-pivot.csv';\n\nfunction fieldOfDragId(id: unknown): FieldId | null {\n  const [, fieldId] = String(id).split(':');\n  const field = FIELDS.find((candidate) => candidate.id === fieldId);\n  return field?.id ?? null;\n}\n\nfunction wellOfDropId(id: unknown): WellId | null {\n  const well = WELL_IDS.find((candidate) => candidate === id);\n  return well ?? null;\n}\n\n/** The preview a held field gives over a well that can take it. */\nfunction previewFor(\n  field: FieldId | null,\n  well: WellId | null\n): Preview | null {\n  if (field === null || well === null) {\n    return null;\n  }\n  if (!canAccept(well, field)) {\n    return null;\n  }\n  return { field, well };\n}\n\n/** A preview only lives while something holds the field: the demonstration, or a person's pointer. */\nfunction livePreviewOf(isHeld: boolean, preview: Preview | null) {\n  if (isHeld) {\n    return preview;\n  }\n  return null;\n}\n\n/** Where every field sits. Chips only measure themselves again when it changes. */\nfunction placementOf(wells: Wells) {\n  const places = FIELDS.map((field) => {\n    const well = wellOf(wells, field.id) ?? 'list';\n    return `${field.id}:${well}`;\n  });\n  return places.join(' ');\n}\n\nfunction runsWordOf(count: number) {\n  if (count === 1) {\n    return '1 run';\n  }\n  return `${count} runs`;\n}\n\nfunction headlineOf(table: PivotTable) {\n  const [firstValue] = table.values;\n  const [firstTotal] = table.grandTotals;\n  if (!firstValue || !firstTotal) {\n    return { figure: runsWordOf(table.recordCount), label: 'in last week' };\n  }\n  return {\n    figure: formatValue(firstValue, firstTotal.value),\n    label: `${valueLabelOf(firstValue)}, ${runsWordOf(table.recordCount)}`,\n  };\n}\n\nfunction lowerLabelOf(id: FieldId) {\n  return fieldOf(id).label.toLowerCase();\n}\n\n/** Sum of cost by agent and model per day: the table said in one line. */\nfunction titleOf(table: PivotTable, wells: Wells) {\n  const valueLabels = table.values.map(valueLabelOf);\n  const rows = wells.rows.map(lowerLabelOf);\n  const columns = wells.columns.map(lowerLabelOf);\n  let title = valueLabels.join(' and ');\n  if (rows.length > 0) {\n    title = `${title} by ${rows.join(' and ')}`;\n  }\n  if (columns.length > 0) {\n    title = `${title} per ${columns.join(' and ')}`;\n  }\n  return title;\n}\n\nfunction exportWordOf(isExported: boolean) {\n  if (isExported) {\n    return 'Downloaded';\n  }\n  return 'Export CSV';\n}\n\nfunction pressedQuietOf(isPressed: boolean) {\n  if (isPressed) {\n    return 'scale-[0.94] bg-foreground/[0.07]';\n  }\n  return undefined;\n}\n\nconst ASK_FAILED_LINE =\n  'No field in that question. Name a figure and a field, like cost by model per day.';\n\nfunction spokenLineOf(hasAskFailed: boolean, title: string) {\n  if (hasAskFailed) {\n    return ASK_FAILED_LINE;\n  }\n  return `Table: ${title}`;\n}\n\nfunction describedByOf(hasAskFailed: boolean, hintId: string) {\n  if (hasAskFailed) {\n    return hintId;\n  }\n  return undefined;\n}\n\nexport default function AgentOps09() {\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n  } = useSession(SESSION);\n  const { schedule } = useTimeouts();\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const travel = springOf(shouldReduceMotion);\n  const groupId = useId();\n  const dndId = useId();\n  const askId = useId();\n  const askHintId = useId();\n  const [draggedField, setDraggedField] = useState<FieldId | null>(null);\n  const [isExported, setIsExported] = useState(false);\n  const sensors = useSensors(\n    useSensor(MouseSensor, MOUSE),\n    useSensor(TouchSensor, TOUCH)\n  );\n  const isHeld = isAutoplaying || draggedField !== null;\n  const preview = livePreviewOf(isHeld, state.preview);\n  const shownWells = shownWellsOf(state.wells, preview);\n  const table = pivotOf(RECORDS, shownWells, state.collapsed);\n  const placement = placementOf(state.wells);\n  const headline = headlineOf(table);\n  const title = titleOf(table, shownWells);\n  const hasValues = table.values.length > 0;\n  const canExport = hasValues && table.recordCount > 0;\n  const exportWord = exportWordOf(isExported);\n  const spokenLine = spokenLineOf(state.hasAskFailed, title);\n  const message = spokenUnless(isAutoplaying, spokenLine);\n  const askDescribedBy = describedByOf(state.hasAskFailed, askHintId);\n  const canReplay = isFinished && !isAutoplaying;\n  let draggedLabel: string | null = null;\n  if (draggedField) {\n    draggedLabel = fieldOf(draggedField).label;\n  }\n\n  function focusLater(selector: string) {\n    requestAnimationFrame(() => {\n      const target = ref.current?.querySelector<HTMLElement>(selector);\n      target?.focus();\n    });\n  }\n\n  /** A chip that changes place is a new element: the focus follows it to its menu button. */\n  function actOnChip(action: PivotAction) {\n    act(action);\n    const movesChip = action.type === 'placed' || action.type === 'removed';\n    if (movesChip) {\n      focusLater(`[data-chip-menu=\"${action.field}\"]`);\n    }\n  }\n\n  function startDrag({ active }: DragStartEvent) {\n    setDraggedField(fieldOfDragId(active.id));\n  }\n\n  function dragOver({ active, over }: DragOverEvent) {\n    const field = fieldOfDragId(active.id);\n    const well = wellOfDropId(over?.id);\n    act({ type: 'previewed', preview: previewFor(field, well) });\n  }\n\n  function endDrag({ active, over }: DragEndEvent) {\n    const field = fieldOfDragId(active.id);\n    const well = wellOfDropId(over?.id);\n    const drop = previewFor(field, well);\n    setDraggedField(null);\n    if (drop) {\n      act({ type: 'placed', field: drop.field, well: drop.well, isDrop: true });\n      return;\n    }\n    act({ type: 'previewed', preview: null });\n  }\n\n  function cancelDrag() {\n    setDraggedField(null);\n    act({ type: 'previewed', preview: null });\n  }\n\n  function ask(event: React.FormEvent<HTMLFormElement>) {\n    event.preventDefault();\n    act({ type: 'asked' });\n  }\n\n  function exportCsv() {\n    downloadCsv(FILE_NAME, csvRowsOf(table));\n    setIsExported(true);\n    schedule(() => setIsExported(false), EXPORTED_FOR_MS);\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='mx-auto flex max-w-6xl flex-col gap-4 p-4 @3xl:gap-5 @3xl:p-8'>\n          <header className='flex flex-wrap items-center gap-x-3 gap-y-2'>\n            <div className='flex min-w-0 flex-1 flex-col gap-0.5'>\n              <h1 className='text-lg font-semibold text-balance'>Run pivot</h1>\n              <p className='text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-1 text-xs'>\n                {runsWordOf(RECORDS.length)} last week\n                <Badge variant='secondary'>Illustrative</Badge>\n              </p>\n            </div>\n            <ReplayButton\n              isShown={canReplay}\n              onReplay={restart}\n              label='Replay the pivot'\n            />\n          </header>\n\n          <form onSubmit={ask} className='flex flex-col gap-1.5'>\n            <div className='flex items-center gap-2'>\n              <label htmlFor={askId} className='sr-only'>\n                Ask to pivot\n              </label>\n              <Input\n                id={askId}\n                autoComplete='off'\n                placeholder={`Ask to pivot: ${ASK_EXAMPLE}`}\n                value={state.question}\n                aria-invalid={state.hasAskFailed}\n                aria-describedby={askDescribedBy}\n                onChange={(event) =>\n                  act({ type: 'questionTyped', text: event.target.value })\n                }\n              />\n              <Button\n                type='submit'\n                className={cn('shrink-0', pressedSolidOf(pressed === 'ask'))}\n              >\n                Ask\n              </Button>\n            </div>\n            <Fold open={state.hasAskFailed}>\n              <p id={askHintId} className='text-destructive-ink text-xs'>\n                {ASK_FAILED_LINE}\n              </p>\n            </Fold>\n          </form>\n\n          <DndContext\n            id={dndId}\n            sensors={sensors}\n            collisionDetection={pointerWithin}\n            onDragStart={startDrag}\n            onDragOver={dragOver}\n            onDragEnd={endDrag}\n            onDragCancel={cancelDrag}\n          >\n            <LayoutGroup id={groupId}>\n              <div className='flex flex-col gap-4 @4xl:flex-row @4xl:items-start @4xl:gap-6'>\n                <div className='@4xl:w-44 @4xl:shrink-0'>\n                  <FieldList\n                    wells={state.wells}\n                    placement={placement}\n                    travel={travel}\n                    drops={state.drops}\n                    pressed={pressed}\n                    onAction={actOnChip}\n                  />\n                </div>\n                <div className='flex min-w-0 flex-1 flex-col gap-4'>\n                  <WellGrid\n                    wells={state.wells}\n                    preview={preview}\n                    draggedField={draggedField}\n                    placement={placement}\n                    travel={travel}\n                    drops={state.drops}\n                    pressed={pressed}\n                    onAction={actOnChip}\n                  />\n\n                  <div className='flex flex-wrap items-end justify-between gap-x-4 gap-y-2'>\n                    <div className='flex min-w-0 flex-col'>\n                      <p className='text-2xl leading-8 font-semibold tabular-nums'>\n                        <Swap swapKey={headline.figure}>{headline.figure}</Swap>\n                      </p>\n                      <p className='text-muted-foreground text-xs'>\n                        <Swap swapKey={headline.label}>{headline.label}</Swap>\n                      </p>\n                    </div>\n                    <div className='flex flex-wrap items-center gap-2'>\n                      <Button\n                        type='button'\n                        variant='outline'\n                        size='sm'\n                        onClick={() => act({ type: 'swapped' })}\n                        className={pressedQuietOf(pressed === 'swap')}\n                      >\n                        <RepeatIcon />\n                        Swap\n                      </Button>\n                      <Button\n                        type='button'\n                        variant='outline'\n                        size='sm'\n                        onClick={() => act({ type: 'cleared' })}\n                      >\n                        <XIcon />\n                        Clear\n                      </Button>\n                      <Button\n                        type='button'\n                        variant='outline'\n                        size='sm'\n                        disabled={!canExport}\n                        onClick={exportCsv}\n                      >\n                        <Swap swapKey={String(isExported)}>\n                          {isExported && <CheckIcon />}\n                          {!isExported && <DownloadIcon />}\n                        </Swap>\n                        <Swap swapKey={exportWord}>{exportWord}</Swap>\n                      </Button>\n                    </div>\n                  </div>\n\n                  <PivotTableView\n                    table={table}\n                    title={title}\n                    collapsed={state.collapsed}\n                    pressed={pressed}\n                    onAction={act}\n                  />\n                </div>\n              </div>\n            </LayoutGroup>\n            <DragOverlay dropAnimation={null}>\n              {draggedLabel && (\n                <span\n                  className={cn(\n                    CHIP_SHAPE,\n                    'surface-raised cursor-grabbing pe-2'\n                  )}\n                >\n                  {draggedLabel}\n                </span>\n              )}\n            </DragOverlay>\n          </DndContext>\n        </div>\n        <LiveRegion message={message} />\n      </div>\n    </ClockGate>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/agent-ops-09/index.tsx"
    },
    {
      "path": "registry/ndeko/blocks/agent-ops/agent-ops-09/wells.tsx",
      "content": "'use client';\n\nimport { useDroppable } from '@dnd-kit/core';\nimport type { Transition } from 'motion/react';\n\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\n\nimport { fieldOf, FIELDS, type Field, type FieldId } from './data';\nimport { CHIP_SHAPE, FieldChip } from './field-chip';\nimport {\n  canAccept,\n  filterLabelOf,\n  valueLabelOf,\n  WELL_IDS,\n  WELL_LABEL,\n  wellOf,\n  type WellId,\n  type Wells,\n} from './pivot';\nimport type { PivotAction, Preview } from './session';\n\nconst WELL_HINT: Record<WellId, string> = {\n  filters: 'Keep only some runs',\n  columns: 'One field across the top',\n  rows: 'Up to two fields down the side',\n  values: 'The figures in the cells',\n};\n\nconst REFUSAL: Record<WellId, string> = {\n  filters: 'Takes a field to group by, not a figure',\n  columns: 'Takes a field to group by, not a figure',\n  rows: 'Takes a field to group by, not a figure',\n  values: 'Takes a figure: runs, cost, tokens or duration',\n};\n\ntype ChipEntry = {\n  field: Field;\n  label: string;\n};\n\nfunction entriesOf(wells: Wells, well: WellId): ChipEntry[] {\n  if (well === 'filters') {\n    return wells.filters.map((filter) => ({\n      field: fieldOf(filter.field),\n      label: filterLabelOf(filter),\n    }));\n  }\n  if (well === 'values') {\n    return wells.values.map((value) => ({\n      field: fieldOf(value.measure),\n      label: valueLabelOf(value),\n    }));\n  }\n  return wells[well].map((dimension) => {\n    const field = fieldOf(dimension);\n    return { field, label: field.label };\n  });\n}\n\ntype WellTone = 'rest' | 'taking' | 'refusing';\n\nconst TONE_CLASS: Record<WellTone, string> = {\n  rest: 'bg-foreground/[0.03] ring-transparent dark:bg-foreground/[0.05]',\n  taking: 'bg-primary/[0.07] ring-primary/30',\n  refusing: 'bg-destructive/[0.06] ring-destructive/25',\n};\n\nfunction toneOf(isTaking: boolean, isRefusing: boolean): WellTone {\n  if (isTaking) {\n    return 'taking';\n  }\n  if (isRefusing) {\n    return 'refusing';\n  }\n  return 'rest';\n}\n\nfunction hintOf(well: WellId, isRefusing: boolean) {\n  if (isRefusing) {\n    return REFUSAL[well];\n  }\n  return WELL_HINT[well];\n}\n\nexport type ChipSharedProps = {\n  /** The committed wells: chips sit where they were dropped, whatever is being previewed. */\n  wells: Wells;\n  placement: string;\n  travel: Transition;\n  drops: Partial<Record<FieldId, number>>;\n  pressed: string | null;\n  onAction: (action: PivotAction) => void;\n};\n\n/** A well refuses the held field when it is a figure over a grouping well, or the reverse. */\nfunction refusesField(\n  well: WellId,\n  isOver: boolean,\n  draggedField: FieldId | null\n) {\n  if (!isOver || draggedField === null) {\n    return false;\n  }\n  return !canAccept(well, draggedField);\n}\n\n/** The field held over this well, unless it already sits there. */\nfunction previewFieldOf(preview: Preview | null, well: WellId, wells: Wells) {\n  if (preview?.well !== well) {\n    return null;\n  }\n  const isAlreadyThere = wellOf(wells, preview.field) === well;\n  if (isAlreadyThere) {\n    return null;\n  }\n  return fieldOf(preview.field);\n}\n\nfunction layoutIdOf(field: FieldId, drops: Partial<Record<FieldId, number>>) {\n  const dropCount = drops[field] ?? 0;\n  return `${field}:${dropCount}`;\n}\n\ntype WellProps = ChipSharedProps & {\n  well: WellId;\n  preview: Preview | null;\n  draggedField: FieldId | null;\n};\n\nfunction Well({\n  well,\n  preview,\n  draggedField,\n  wells,\n  placement,\n  travel,\n  drops,\n  onAction,\n}: WellProps) {\n  const { setNodeRef, isOver } = useDroppable({ id: well });\n  const entries = entriesOf(wells, well);\n  const isTaking = preview?.well === well;\n  const isRefusing = refusesField(well, isOver, draggedField);\n  const tone = toneOf(isTaking, isRefusing);\n  const hint = hintOf(well, isRefusing);\n  const previewField = previewFieldOf(preview, well, wells);\n  const hasChips = entries.length > 0 || previewField !== null;\n\n  return (\n    <div\n      ref={setNodeRef}\n      className={cn(\n        'hairline-ring flex min-h-11 flex-col gap-1.5 rounded-lg p-2 transition-[background-color,box-shadow] duration-150',\n        TONE_CLASS[tone]\n      )}\n    >\n      <h3 className='text-muted-foreground flex items-baseline gap-2 text-xs'>\n        <span className='text-foreground font-medium'>{WELL_LABEL[well]}</span>\n        <span className='min-w-0 truncate'>\n          <Swap swapKey={hint}>{hint}</Swap>\n        </span>\n      </h3>\n      {hasChips && (\n        <ul className='flex flex-wrap items-center gap-1.5'>\n          {entries.map((entry) => (\n            <li key={entry.field.id} className='max-w-full'>\n              <FieldChip\n                field={entry.field}\n                origin='well'\n                label={entry.label}\n                wells={wells}\n                layoutId={layoutIdOf(entry.field.id, drops)}\n                placement={placement}\n                travel={travel}\n                onAction={onAction}\n              />\n            </li>\n          ))}\n          {previewField && (\n            <li\n              aria-hidden='true'\n              className={cn(\n                CHIP_SHAPE,\n                'hairline-border border-primary/50 text-primary-ink border-dashed pe-2 transition-opacity duration-150 starting:opacity-0'\n              )}\n            >\n              {previewField.label}\n            </li>\n          )}\n        </ul>\n      )}\n    </div>\n  );\n}\n\ntype WellGridProps = ChipSharedProps & {\n  preview: Preview | null;\n  draggedField: FieldId | null;\n};\n\nexport function WellGrid({ preview, draggedField, ...shared }: WellGridProps) {\n  return (\n    <section\n      aria-label='Layout of the table'\n      className='grid grid-cols-1 gap-2 @lg:grid-cols-2'\n    >\n      {WELL_IDS.map((well) => (\n        <Well\n          key={well}\n          well={well}\n          preview={preview}\n          draggedField={draggedField}\n          {...shared}\n        />\n      ))}\n    </section>\n  );\n}\n\nexport function FieldList({\n  wells,\n  placement,\n  travel,\n  drops,\n  pressed,\n  onAction,\n}: ChipSharedProps) {\n  return (\n    <section aria-label='Fields' className='flex flex-col gap-2'>\n      <h2 className='text-muted-foreground text-xs'>Fields</h2>\n      <ul className='flex flex-wrap gap-1.5 @4xl:flex-col @4xl:items-start'>\n        {FIELDS.map((field) => {\n          const well = wellOf(wells, field.id);\n          return (\n            <li key={field.id} className='flex min-h-7 max-w-full'>\n              {well === null && (\n                <FieldChip\n                  field={field}\n                  origin='list'\n                  label={field.label}\n                  wells={wells}\n                  layoutId={layoutIdOf(field.id, drops)}\n                  placement={placement}\n                  travel={travel}\n                  isPressed={pressed === `field-${field.id}`}\n                  onAction={onAction}\n                />\n              )}\n              {well !== null && (\n                <span\n                  className={cn(\n                    CHIP_SHAPE,\n                    'hairline-border border-foreground/20 text-muted-foreground gap-1.5 border-dashed pe-2 font-normal'\n                  )}\n                >\n                  {field.label}\n                  <span className='text-muted-foreground/70'>\n                    in {WELL_LABEL[well]}\n                  </span>\n                </span>\n              )}\n            </li>\n          );\n        })}\n      </ul>\n    </section>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/agent-ops-09/wells.tsx"
    },
    {
      "path": "registry/ndeko/blocks/agent-ops/agent-ops-09/field-chip.tsx",
      "content": "'use client';\n\nimport { useDraggable } from '@dnd-kit/core';\nimport { motion, type Transition } from 'motion/react';\n\nimport { ChevronDownIcon, HashIcon, XIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport {\n  DropdownMenu,\n  DropdownMenuCheckboxItem,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuLabel,\n  DropdownMenuRadioGroup,\n  DropdownMenuRadioItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n} from '@/registry/ndeko/ui/dropdown-menu';\n\nimport { DIMENSION_VALUES, isMeasure, type Field } from './data';\nimport {\n  AGGREGATION_WORD,\n  AGGREGATIONS,\n  canAccept,\n  WELL_IDS,\n  WELL_LABEL,\n  wellOf,\n  type Wells,\n} from './pivot';\nimport type { PivotAction } from './session';\n\nexport type ChipOrigin = 'list' | 'well';\n\n/** Unplaced fields are plain pills; a field placed in a well wears the brand chip of an assigned value. */\nconst SURFACE: Record<ChipOrigin, string> = {\n  list: 'bg-card hairline-ring ring-foreground/12 text-foreground shadow-[0_1px_2px_rgb(0_0_0/0.05)] dark:bg-foreground/[0.04] dark:ring-foreground/15',\n  well: 'chip-3d [--chip:var(--primary)]',\n};\n\nexport const CHIP_SHAPE =\n  'inline-flex h-7 max-w-full items-center gap-1 rounded-md ps-2 text-xs font-medium whitespace-nowrap';\n\nconst CHIP_BUTTON =\n  'focus-visible:ring-ring/25 flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-sm opacity-70 transition-[opacity,background-color] duration-150 outline-none hover:bg-foreground/[0.08] hover:opacity-100 focus-visible:opacity-100 focus-visible:ring-[3px]';\n\nfunction pressedOf(isPressed: boolean) {\n  if (isPressed) {\n    return 'scale-[0.94] bg-foreground/[0.07]';\n  }\n  return undefined;\n}\n\nfunction moveWordOf(isPlaced: boolean) {\n  if (isPlaced) {\n    return 'Move to';\n  }\n  return 'Add to';\n}\n\ntype ChipMenuProps = {\n  field: Field;\n  wells: Wells;\n  onAction: (action: PivotAction) => void;\n};\n\n/** The keyboard path of a chip: every well it can go to, then what its own well lets it change. */\nfunction ChipMenu({ field, wells, onAction }: ChipMenuProps) {\n  const current = wellOf(wells, field.id);\n  const isPlaced = current !== null;\n  const moveWord = moveWordOf(isPlaced);\n  const targets = WELL_IDS.filter((well) => {\n    const isOpen = canAccept(well, field.id);\n    const isElsewhere = well !== current;\n    return isOpen && isElsewhere;\n  });\n  const valueSpec = wells.values.find((value) => value.measure === field.id);\n  const filter = wells.filters.find((entry) => entry.field === field.id);\n\n  function changeAggregation(next: unknown) {\n    const aggregation = AGGREGATIONS.find((candidate) => candidate === next);\n    if (aggregation && isMeasure(field.id)) {\n      onAction({ type: 'aggregation', measure: field.id, aggregation });\n    }\n  }\n\n  return (\n    <DropdownMenuContent align='start' className='min-w-44'>\n      {targets.map((well) => (\n        <DropdownMenuItem\n          key={well}\n          onClick={() => onAction({ type: 'placed', field: field.id, well })}\n        >\n          {moveWord} {WELL_LABEL[well]}\n        </DropdownMenuItem>\n      ))}\n      {valueSpec && (\n        <>\n          <DropdownMenuSeparator />\n          <DropdownMenuLabel>Summarise by</DropdownMenuLabel>\n          <DropdownMenuRadioGroup\n            value={valueSpec.aggregation}\n            onValueChange={changeAggregation}\n          >\n            {AGGREGATIONS.map((aggregation) => (\n              <DropdownMenuRadioItem key={aggregation} value={aggregation}>\n                {AGGREGATION_WORD[aggregation]}\n              </DropdownMenuRadioItem>\n            ))}\n          </DropdownMenuRadioGroup>\n        </>\n      )}\n      {filter && (\n        <>\n          <DropdownMenuSeparator />\n          <DropdownMenuLabel>Keep</DropdownMenuLabel>\n          {DIMENSION_VALUES[filter.field].map((value) => (\n            <DropdownMenuCheckboxItem\n              key={value}\n              checked={filter.values.includes(value)}\n              onCheckedChange={() =>\n                onAction({ type: 'filterValue', field: filter.field, value })\n              }\n            >\n              {value}\n            </DropdownMenuCheckboxItem>\n          ))}\n        </>\n      )}\n      {current !== null && (\n        <>\n          <DropdownMenuSeparator />\n          <DropdownMenuItem\n            onClick={() => onAction({ type: 'removed', field: field.id })}\n          >\n            Remove from {WELL_LABEL[current]}\n          </DropdownMenuItem>\n        </>\n      )}\n    </DropdownMenuContent>\n  );\n}\n\nexport type FieldChipProps = {\n  field: Field;\n  origin: ChipOrigin;\n  /** What the chip says: the field in the list, the field with its setting in a well. */\n  label: string;\n  wells: Wells;\n  layoutId: string;\n  /** Where every field sits: the chip measures itself again when it changes. */\n  placement: string;\n  travel: Transition;\n  isPressed?: boolean;\n  onAction: (action: PivotAction) => void;\n};\n\nexport function FieldChip({\n  field,\n  origin,\n  label,\n  wells,\n  layoutId,\n  placement,\n  travel,\n  isPressed = false,\n  onAction,\n}: FieldChipProps) {\n  const { setNodeRef, listeners, isDragging } = useDraggable({\n    id: `${origin}:${field.id}`,\n  });\n  const isInWell = origin === 'well';\n  const isMeasureField = field.kind === 'measure';\n\n  return (\n    <motion.div\n      layout='position'\n      layoutId={layoutId}\n      layoutDependency={placement}\n      transition={{ layout: travel }}\n      className='inline-flex max-w-full'\n    >\n      <div\n        ref={setNodeRef}\n        {...listeners}\n        className={cn(\n          CHIP_SHAPE,\n          SURFACE[origin],\n          'cursor-grab touch-manipulation transition-[scale,opacity,background-color] duration-150 select-none active:cursor-grabbing',\n          isDragging && 'opacity-40',\n          pressedOf(isPressed)\n        )}\n      >\n        {isMeasureField && (\n          <HashIcon aria-hidden='true' className='size-3 shrink-0 opacity-60' />\n        )}\n        <span className='min-w-0 truncate'>{label}</span>\n        <DropdownMenu>\n          <DropdownMenuTrigger\n            data-chip-menu={field.id}\n            aria-label={`${label}: where it goes`}\n            className={CHIP_BUTTON}\n          >\n            <ChevronDownIcon className='size-3.5' />\n          </DropdownMenuTrigger>\n          <ChipMenu field={field} wells={wells} onAction={onAction} />\n        </DropdownMenu>\n        {isInWell && (\n          <button\n            type='button'\n            aria-label={`Remove ${label}`}\n            onClick={() => onAction({ type: 'removed', field: field.id })}\n            className={cn(CHIP_BUTTON, '-ms-1')}\n          >\n            <XIcon className='size-3.5' />\n          </button>\n        )}\n        {!isInWell && <span aria-hidden='true' className='w-0.5' />}\n      </div>\n    </motion.div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/agent-ops-09/field-chip.tsx"
    },
    {
      "path": "registry/ndeko/blocks/agent-ops/agent-ops-09/pivot-table.tsx",
      "content": "'use client';\n\nimport {\n  formatCost,\n  formatDuration,\n  formatTokens,\n} from '@/registry/ndeko/lib/agent-run';\nimport { ChevronRightIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { BrandTile } from '@/registry/ndeko/ui/brand-tile';\nimport { Button } from '@/registry/ndeko/ui/button';\n\nimport { VALUE_BRAND } from './data';\nimport {\n  valueLabelOf,\n  type PivotCell,\n  type PivotRow,\n  type PivotTable,\n  type ValueSpec,\n} from './pivot';\nimport type { PivotAction } from './session';\n\n/** One hue from pale to full, low to high. */\nconst HEAT_CLASS = [\n  'bg-chart-4/45 dark:bg-chart-4/10',\n  'bg-chart-3/55 dark:bg-chart-3/15',\n  'bg-chart-2/55 dark:bg-chart-2/25',\n  'bg-chart-1/55 dark:bg-chart-1/35',\n];\n\nconst COUNT_FORMAT = new Intl.NumberFormat('en-US', {\n  maximumFractionDigits: 1,\n});\n\nconst SURFACE =\n  'bg-card hairline-ring ring-border rounded-xl shadow-[0_1px_2px_rgb(0_0_0/0.04)]';\n\nconst HEAD_CELL =\n  'text-muted-foreground h-8 px-2.5 text-end text-xs font-medium whitespace-nowrap';\n\nconst ROW_HEAD =\n  'bg-card sticky left-0 z-10 h-8 max-w-44 ps-2.5 pe-3 text-start text-xs whitespace-nowrap';\n\n/** 12, $4.20, 48k, 1m 34s: each figure in the format of its measure. */\nexport function formatValue(spec: ValueSpec, value: number | null) {\n  if (value === null) {\n    return '';\n  }\n  if (spec.aggregation === 'count') {\n    return COUNT_FORMAT.format(value);\n  }\n  if (spec.measure === 'cost') {\n    return formatCost(value);\n  }\n  if (spec.measure === 'tokens') {\n    return formatTokens(value);\n  }\n  if (spec.measure === 'duration') {\n    return formatDuration(value);\n  }\n  return COUNT_FORMAT.format(value);\n}\n\nfunction heatClassOf(cell: PivotCell) {\n  if (cell.heat === null) {\n    return undefined;\n  }\n  return HEAT_CLASS[cell.heat];\n}\n\nfunction chevronTurnOf(isOpen: boolean) {\n  if (isOpen) {\n    return 'rotate-90';\n  }\n  return 'rotate-0';\n}\n\nfunction indentOf(depth: number) {\n  if (depth > 0) {\n    return 'ps-9';\n  }\n  return undefined;\n}\n\nfunction pressedOf(isPressed: boolean) {\n  if (isPressed) {\n    return 'scale-[0.97] bg-foreground/[0.07]';\n  }\n  return undefined;\n}\n\nfunction ValueLabel({ label }: { label: string }) {\n  const brand = VALUE_BRAND[label];\n\n  return (\n    <span className='flex min-w-0 items-center gap-1.5'>\n      {brand && <BrandTile brand={brand} size='sm' />}\n      <span className='truncate'>{label}</span>\n    </span>\n  );\n}\n\ntype FigureCellProps = {\n  cell: PivotCell;\n  spec: ValueSpec;\n  isStrong?: boolean;\n};\n\nfunction FigureCell({ cell, spec, isStrong = false }: FigureCellProps) {\n  const text = formatValue(spec, cell.value);\n  const isEmpty = cell.value === null;\n\n  return (\n    <td className='p-px'>\n      <span\n        className={cn(\n          'flex h-7 min-w-14 items-center justify-end rounded-[5px] px-2 text-xs tabular-nums transition-colors duration-300',\n          heatClassOf(cell),\n          isStrong && 'font-medium'\n        )}\n      >\n        {text}\n        {isEmpty && <span className='sr-only'>No run</span>}\n      </span>\n    </td>\n  );\n}\n\ntype BodyRowProps = {\n  row: PivotRow;\n  table: PivotTable;\n  isFolded: boolean;\n  isPressed: boolean;\n  onToggleGroup: (key: string) => void;\n};\n\nfunction BodyRow({\n  row,\n  table,\n  isFolded,\n  isPressed,\n  onToggleGroup,\n}: BodyRowProps) {\n  const valueCount = table.values.length;\n\n  return (\n    <tr className='transition-opacity duration-300 starting:opacity-0'>\n      <th\n        scope='row'\n        className={cn(\n          ROW_HEAD,\n          indentOf(row.depth),\n          !row.isGroup && 'font-normal'\n        )}\n      >\n        {row.isGroup && (\n          <button\n            type='button'\n            aria-expanded={!isFolded}\n            onClick={() => onToggleGroup(row.key)}\n            className={cn(\n              'focus-visible:ring-ring/25 hover:bg-foreground/[0.05] -ms-1.5 flex h-7 max-w-full cursor-pointer items-center gap-1 rounded-md ps-1 pe-2 font-medium transition-[background-color,scale] duration-150 outline-none focus-visible:ring-[3px]',\n              pressedOf(isPressed)\n            )}\n          >\n            <ChevronRightIcon\n              className={cn(\n                'text-muted-foreground size-3.5 shrink-0 transition-transform duration-200 ease-(--ease-out-strong)',\n                chevronTurnOf(!isFolded)\n              )}\n            />\n            <ValueLabel label={row.label} />\n          </button>\n        )}\n        {!row.isGroup && <ValueLabel label={row.label} />}\n      </th>\n      {row.cells.map((cell, index) => (\n        <FigureCell\n          key={index}\n          cell={cell}\n          spec={table.values[index % valueCount]}\n          isStrong={row.isGroup}\n        />\n      ))}\n      {table.hasColumns &&\n        row.totals.map((cell, index) => (\n          <FigureCell\n            key={`total-${index}`}\n            cell={cell}\n            spec={table.values[index]}\n            isStrong\n          />\n        ))}\n    </tr>\n  );\n}\n\nfunction HeadRows({ table }: { table: PivotTable }) {\n  const valueCount = table.values.length;\n  const hasValueRow = table.hasColumns && valueCount > 1;\n  const valueLabels = table.values.map(valueLabelOf);\n  let rowSpan = 1;\n  if (hasValueRow) {\n    rowSpan = 2;\n  }\n\n  return (\n    <thead>\n      <tr>\n        <th\n          scope='col'\n          rowSpan={rowSpan}\n          className={cn(\n            ROW_HEAD,\n            'text-muted-foreground align-bottom font-medium'\n          )}\n        >\n          {table.rowHeader}\n        </th>\n        {!table.hasColumns &&\n          valueLabels.map((label) => (\n            <th key={label} scope='col' className={HEAD_CELL}>\n              {label}\n            </th>\n          ))}\n        {table.hasColumns &&\n          table.columnKeys.map((columnKey) => (\n            <th\n              key={columnKey}\n              scope='col'\n              colSpan={valueCount}\n              className={HEAD_CELL}\n            >\n              {columnKey}\n            </th>\n          ))}\n        {table.hasColumns && (\n          <th\n            scope='col'\n            colSpan={valueCount}\n            className={cn(HEAD_CELL, 'text-foreground')}\n          >\n            Total\n          </th>\n        )}\n      </tr>\n      {hasValueRow && (\n        <tr>\n          {table.columnKeys.map((columnKey) =>\n            valueLabels.map((label) => (\n              <th\n                key={`${columnKey}-${label}`}\n                scope='col'\n                className={cn(HEAD_CELL, 'font-normal')}\n              >\n                {label}\n              </th>\n            ))\n          )}\n          {valueLabels.map((label) => (\n            <th\n              key={`total-${label}`}\n              scope='col'\n              className={cn(HEAD_CELL, 'font-normal')}\n            >\n              {label}\n            </th>\n          ))}\n        </tr>\n      )}\n    </thead>\n  );\n}\n\nfunction HeatLegend() {\n  return (\n    <p className='text-muted-foreground flex items-center gap-1.5 text-[11px]'>\n      Low\n      <span aria-hidden='true' className='flex gap-0.5'>\n        {HEAT_CLASS.map((heat) => (\n          <span key={heat} className={cn('size-3 rounded-[3px]', heat)} />\n        ))}\n      </span>\n      High\n    </p>\n  );\n}\n\nexport type PivotTableViewProps = {\n  table: PivotTable;\n  title: string;\n  collapsed: string[];\n  pressed: string | null;\n  onAction: (action: PivotAction) => void;\n};\n\n/** A long table scrolls inside its own frame and its first column stays in place. */\nexport function PivotTableView({\n  table,\n  title,\n  collapsed,\n  pressed,\n  onAction,\n}: PivotTableViewProps) {\n  const hasValues = table.values.length > 0;\n  const hasRecords = table.recordCount > 0;\n\n  if (!hasValues) {\n    return (\n      <div className={cn(SURFACE, 'flex flex-col items-start gap-3 p-4')}>\n        <p className='text-muted-foreground text-[13px]'>\n          The table needs a figure. Drop Runs, Cost, Tokens or Duration in\n          Values.\n        </p>\n        <Button\n          type='button'\n          variant='outline'\n          size='sm'\n          onClick={() =>\n            onAction({ type: 'placed', field: 'runs', well: 'values' })\n          }\n        >\n          Count the runs\n        </Button>\n      </div>\n    );\n  }\n\n  if (!hasRecords) {\n    return (\n      <div className={cn(SURFACE, 'flex flex-col items-start gap-3 p-4')}>\n        <p className='text-muted-foreground text-[13px]'>\n          No run matches these filters\n        </p>\n        <Button\n          type='button'\n          variant='outline'\n          size='sm'\n          onClick={() => onAction({ type: 'filtersCleared' })}\n        >\n          Remove the filters\n        </Button>\n      </div>\n    );\n  }\n\n  return (\n    <div className='flex flex-col gap-2'>\n      <div className={cn(SURFACE, 'relative overflow-x-auto p-1.5')}>\n        <table className='w-full border-separate border-spacing-0'>\n          <caption className='sr-only'>{title}</caption>\n          <HeadRows table={table} />\n          <tbody>\n            {table.rows.map((row) => (\n              <BodyRow\n                key={row.key}\n                row={row}\n                table={table}\n                isFolded={collapsed.includes(row.key)}\n                isPressed={pressed === `group-${row.key}`}\n                onToggleGroup={(key) => onAction({ type: 'groupToggled', key })}\n              />\n            ))}\n          </tbody>\n          <tfoot>\n            <tr>\n              <th scope='row' className={cn(ROW_HEAD, 'font-medium')}>\n                Total\n              </th>\n              {table.grandCells.map((cell, index) => (\n                <FigureCell\n                  key={index}\n                  cell={cell}\n                  spec={table.values[index % table.values.length]}\n                  isStrong\n                />\n              ))}\n              {table.hasColumns &&\n                table.grandTotals.map((cell, index) => (\n                  <FigureCell\n                    key={`total-${index}`}\n                    cell={cell}\n                    spec={table.values[index]}\n                    isStrong\n                  />\n                ))}\n            </tr>\n          </tfoot>\n        </table>\n      </div>\n      <HeatLegend />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/agent-ops-09/pivot-table.tsx"
    },
    {
      "path": "registry/ndeko/blocks/agent-ops/agent-ops-09/pivot.ts",
      "content": "import {\n  DIMENSION_VALUES,\n  fieldOf,\n  isDimension,\n  isMeasure,\n  type DimensionId,\n  type FieldId,\n  type MeasureId,\n  type RunRecord,\n} from './data';\n\nexport type Aggregation = 'sum' | 'avg' | 'count';\n\nexport const AGGREGATIONS: Aggregation[] = ['sum', 'avg', 'count'];\n\nexport const AGGREGATION_WORD: Record<Aggregation, string> = {\n  sum: 'Sum',\n  avg: 'Average',\n  count: 'Count',\n};\n\nexport type ValueSpec = {\n  measure: MeasureId;\n  aggregation: Aggregation;\n};\n\nexport type FilterSpec = {\n  field: DimensionId;\n  /** The values that are kept. */\n  values: string[];\n};\n\nexport type Wells = {\n  filters: FilterSpec[];\n  columns: DimensionId[];\n  rows: DimensionId[];\n  values: ValueSpec[];\n};\n\nexport type WellId = 'filters' | 'columns' | 'rows' | 'values';\n\nexport const WELL_IDS: WellId[] = ['filters', 'columns', 'rows', 'values'];\n\nexport const WELL_LABEL: Record<WellId, string> = {\n  filters: 'Filters',\n  columns: 'Columns',\n  rows: 'Rows',\n  values: 'Values',\n};\n\n/** How many fields a well holds. One more replaces the last one. */\nconst CAPACITY: Record<WellId, number> = {\n  filters: 3,\n  columns: 1,\n  rows: 2,\n  values: 2,\n};\n\nexport const EMPTY_WELLS: Wells = {\n  filters: [],\n  columns: [],\n  rows: [],\n  values: [],\n};\n\n/** Measures are figures and go to Values; everything else groups or filters. */\nexport function canAccept(well: WellId, field: FieldId) {\n  if (well === 'values') {\n    return isMeasure(field);\n  }\n  return isDimension(field);\n}\n\nexport function wellOf(wells: Wells, field: FieldId): WellId | null {\n  if (wells.filters.some((filter) => filter.field === field)) {\n    return 'filters';\n  }\n  if (wells.columns.some((dimension) => dimension === field)) {\n    return 'columns';\n  }\n  if (wells.rows.some((dimension) => dimension === field)) {\n    return 'rows';\n  }\n  if (wells.values.some((value) => value.measure === field)) {\n    return 'values';\n  }\n  return null;\n}\n\nexport function removed(wells: Wells, field: FieldId): Wells {\n  return {\n    filters: wells.filters.filter((filter) => filter.field !== field),\n    columns: wells.columns.filter((dimension) => dimension !== field),\n    rows: wells.rows.filter((dimension) => dimension !== field),\n    values: wells.values.filter((value) => value.measure !== field),\n  };\n}\n\n/** Keeps the first entries and gives the last place to the newcomer. */\nfunction fitted<Entry>(entries: Entry[], entry: Entry, capacity: number) {\n  const kept = entries.slice(0, capacity - 1);\n  return [...kept, entry];\n}\n\n/** Only finished runs by default, the usual first question about a status. */\nfunction defaultFilterOf(field: DimensionId): FilterSpec {\n  if (field === 'status') {\n    return { field, values: ['Done'] };\n  }\n  return { field, values: DIMENSION_VALUES[field] };\n}\n\nfunction placedDimension(wells: Wells, field: DimensionId, well: WellId) {\n  if (well === 'filters') {\n    const filter = defaultFilterOf(field);\n    const filters = fitted(wells.filters, filter, CAPACITY.filters);\n    return { ...wells, filters };\n  }\n  if (well === 'columns') {\n    const columns = fitted(wells.columns, field, CAPACITY.columns);\n    return { ...wells, columns };\n  }\n  const rows = fitted(wells.rows, field, CAPACITY.rows);\n  return { ...wells, rows };\n}\n\n/** A field sits in one well at a time: placing it takes it out of the well it was in. */\nexport function placed(wells: Wells, field: FieldId, well: WellId): Wells {\n  if (!canAccept(well, field)) {\n    return wells;\n  }\n  if (wellOf(wells, field) === well) {\n    return wells;\n  }\n  const cleared = removed(wells, field);\n  if (isMeasure(field)) {\n    const spec: ValueSpec = { measure: field, aggregation: 'sum' };\n    const values = fitted(cleared.values, spec, CAPACITY.values);\n    return { ...cleared, values };\n  }\n  if (isDimension(field)) {\n    return placedDimension(cleared, field, well);\n  }\n  return wells;\n}\n\nexport function swapped(wells: Wells): Wells {\n  const columns = wells.rows.slice(0, CAPACITY.columns);\n  const rows = wells.columns.slice(0, CAPACITY.rows);\n  return { ...wells, columns, rows };\n}\n\nexport function withAggregation(\n  wells: Wells,\n  measure: MeasureId,\n  aggregation: Aggregation\n): Wells {\n  const values = wells.values.map((value) => {\n    if (value.measure === measure) {\n      return { ...value, aggregation };\n    }\n    return value;\n  });\n  return { ...wells, values };\n}\n\nexport function withFilterValue(\n  wells: Wells,\n  field: DimensionId,\n  value: string\n): Wells {\n  const filters = wells.filters.map((filter) => {\n    if (filter.field !== field) {\n      return filter;\n    }\n    const isKept = filter.values.includes(value);\n    if (isKept) {\n      const values = filter.values.filter((candidate) => candidate !== value);\n      return { ...filter, values };\n    }\n    return { ...filter, values: [...filter.values, value] };\n  });\n  return { ...wells, filters };\n}\n\nexport function valueLabelOf(spec: ValueSpec) {\n  const measure = fieldOf(spec.measure).label.toLowerCase();\n  if (spec.aggregation === 'count') {\n    return 'Count of runs';\n  }\n  return `${AGGREGATION_WORD[spec.aggregation]} of ${measure}`;\n}\n\nexport function filterLabelOf(filter: FilterSpec) {\n  const label = fieldOf(filter.field).label;\n  const all = DIMENSION_VALUES[filter.field];\n  if (filter.values.length === all.length) {\n    return `${label}: all`;\n  }\n  if (filter.values.length === 0) {\n    return `${label}: none`;\n  }\n  if (filter.values.length === 1) {\n    return `${label}: ${filter.values[0]}`;\n  }\n  return `${label}: ${filter.values.length} of ${all.length}`;\n}\n\nfunction passesFilters(record: RunRecord, filters: FilterSpec[]) {\n  return filters.every((filter) =>\n    filter.values.includes(record[filter.field])\n  );\n}\n\nfunction aggregateOf(records: RunRecord[], spec: ValueSpec) {\n  if (records.length === 0) {\n    return null;\n  }\n  if (spec.aggregation === 'count') {\n    return records.length;\n  }\n  let sum = 0;\n  for (const record of records) {\n    sum += record[spec.measure];\n  }\n  if (spec.aggregation === 'sum') {\n    return sum;\n  }\n  return sum / records.length;\n}\n\n/** The values of a dimension that the records hold, in the order of the dimension. */\nfunction presentValuesOf(records: RunRecord[], dimension: DimensionId) {\n  return DIMENSION_VALUES[dimension].filter((value) =>\n    records.some((record) => record[dimension] === value)\n  );\n}\n\nfunction recordsWith(\n  records: RunRecord[],\n  dimension: DimensionId | undefined,\n  value: string\n) {\n  if (dimension === undefined) {\n    return records;\n  }\n  return records.filter((record) => record[dimension] === value);\n}\n\nexport type PivotCell = {\n  value: number | null;\n  /** From 0 to 3 for the cells that are shaded; none for subtotals and totals. */\n  heat: number | null;\n};\n\nexport type PivotRow = {\n  key: string;\n  label: string;\n  depth: number;\n  /** A group row sums its children and can fold them. */\n  isGroup: boolean;\n  /** One cell per column and value, column by column. */\n  cells: PivotCell[];\n  /** One total per value, across the columns. */\n  totals: PivotCell[];\n};\n\nexport type PivotTable = {\n  rowHeader: string;\n  /** False without a column field: the cells then are the totals. */\n  hasColumns: boolean;\n  columnKeys: string[];\n  values: ValueSpec[];\n  rows: PivotRow[];\n  grandCells: PivotCell[];\n  grandTotals: PivotCell[];\n  recordCount: number;\n};\n\nconst ALL_COLUMNS = [''];\n\nconst HEAT_STEPS = 4;\n\nfunction plainCellsOf(\n  records: RunRecord[],\n  columnDimension: DimensionId | undefined,\n  columnKeys: string[],\n  values: ValueSpec[]\n) {\n  const cells: PivotCell[] = [];\n  for (const columnKey of columnKeys) {\n    const inColumn = recordsWith(records, columnDimension, columnKey);\n    for (const spec of values) {\n      cells.push({ value: aggregateOf(inColumn, spec), heat: null });\n    }\n  }\n  return cells;\n}\n\nfunction totalsOf(records: RunRecord[], values: ValueSpec[]) {\n  return values.map((spec): PivotCell => {\n    return { value: aggregateOf(records, spec), heat: null };\n  });\n}\n\ntype Range = { min: number; max: number };\n\n/** The range of each value over the rows that are shaded, so a cost never shades a count. */\nfunction rangesOf(rows: PivotRow[], valueCount: number) {\n  const ranges: Range[] = [];\n  for (let valueIndex = 0; valueIndex < valueCount; valueIndex += 1) {\n    ranges.push({ min: Infinity, max: -Infinity });\n  }\n  for (const row of rows) {\n    if (row.isGroup) {\n      continue;\n    }\n    row.cells.forEach((cell, index) => {\n      if (cell.value === null) {\n        return;\n      }\n      const range = ranges[index % valueCount];\n      range.min = Math.min(range.min, cell.value);\n      range.max = Math.max(range.max, cell.value);\n    });\n  }\n  return ranges;\n}\n\nfunction heatOf(value: number, range: Range) {\n  const span = range.max - range.min;\n  if (span <= 0) {\n    return 0;\n  }\n  const share = (value - range.min) / span;\n  const step = Math.floor(share * HEAT_STEPS);\n  return Math.min(HEAT_STEPS - 1, step);\n}\n\nfunction shaded(rows: PivotRow[], valueCount: number) {\n  const ranges = rangesOf(rows, valueCount);\n  return rows.map((row) => {\n    if (row.isGroup) {\n      return row;\n    }\n    const cells = row.cells.map((cell, index): PivotCell => {\n      if (cell.value === null) {\n        return cell;\n      }\n      const range = ranges[index % valueCount];\n      return { value: cell.value, heat: heatOf(cell.value, range) };\n    });\n    return { ...row, cells };\n  });\n}\n\n/** Groups the filtered runs by the rows and the column, with a subtotal per group and a grand total. */\nexport function pivotOf(\n  records: RunRecord[],\n  wells: Wells,\n  collapsed: string[]\n): PivotTable {\n  const kept = records.filter((record) => passesFilters(record, wells.filters));\n  const [columnDimension] = wells.columns;\n  const [groupDimension, leafDimension] = wells.rows;\n  const values = wells.values;\n  let columnKeys = ALL_COLUMNS;\n  if (columnDimension) {\n    columnKeys = presentValuesOf(kept, columnDimension);\n  }\n\n  function rowOf(\n    key: string,\n    label: string,\n    depth: number,\n    isGroup: boolean,\n    rowRecords: RunRecord[]\n  ): PivotRow {\n    return {\n      key,\n      label,\n      depth,\n      isGroup,\n      cells: plainCellsOf(rowRecords, columnDimension, columnKeys, values),\n      totals: totalsOf(rowRecords, values),\n    };\n  }\n\n  const rows: PivotRow[] = [];\n  if (!groupDimension) {\n    rows.push(rowOf('all', 'All runs', 0, false, kept));\n  }\n  if (groupDimension) {\n    const hasLeaves = leafDimension !== undefined;\n    for (const groupValue of presentValuesOf(kept, groupDimension)) {\n      const inGroup = recordsWith(kept, groupDimension, groupValue);\n      rows.push(rowOf(groupValue, groupValue, 0, hasLeaves, inGroup));\n      const isFolded = collapsed.includes(groupValue);\n      if (!hasLeaves || isFolded) {\n        continue;\n      }\n      for (const leafValue of presentValuesOf(inGroup, leafDimension)) {\n        const inLeaf = recordsWith(inGroup, leafDimension, leafValue);\n        const key = `${groupValue}/${leafValue}`;\n        rows.push(rowOf(key, leafValue, 1, false, inLeaf));\n      }\n    }\n  }\n\n  let rowHeader = 'Runs';\n  if (groupDimension) {\n    rowHeader = fieldOf(groupDimension).label;\n  }\n\n  return {\n    rowHeader,\n    hasColumns: columnDimension !== undefined,\n    columnKeys,\n    values,\n    rows: shaded(rows, Math.max(1, values.length)),\n    grandCells: plainCellsOf(kept, columnDimension, columnKeys, values),\n    grandTotals: totalsOf(kept, values),\n    recordCount: kept.length,\n  };\n}\n",
      "type": "registry:component",
      "target": "components/blocks/agent-ops-09/pivot.ts"
    },
    {
      "path": "registry/ndeko/blocks/agent-ops/agent-ops-09/ask.ts",
      "content": "import {\n  DIMENSION_VALUES,\n  DIMENSIONS,\n  MEASURES,\n  type DimensionId,\n  type MeasureId,\n} from './data';\nimport type { Aggregation, FilterSpec, ValueSpec, Wells } from './pivot';\n\nexport const ASK_EXAMPLE = 'average tokens by model per day';\n\nconst MEASURE_WORDS: Record<MeasureId, string[]> = {\n  runs: ['runs', 'run'],\n  cost: ['cost', 'costs', 'spend', 'spent'],\n  tokens: ['tokens', 'token'],\n  duration: ['duration', 'time', 'long'],\n};\n\nconst DIMENSION_WORDS: Record<DimensionId, string[]> = {\n  agent: ['agent', 'agents'],\n  model: ['model', 'models'],\n  day: ['day', 'days', 'daily', 'date'],\n  status: ['status', 'outcome'],\n  tool: ['tool', 'tools'],\n};\n\nconst AVERAGE_WORDS = ['average', 'avg', 'mean'];\n\nconst COUNT_WORDS = ['count', 'many', 'number'];\n\n/** After one of these the next dimensions become rows. */\nconst ROW_WORDS = ['by', 'and'];\n\n/** After one of these the next dimension becomes the column. */\nconst COLUMN_WORDS = ['per', 'across', 'each', 'over'];\n\nconst FAILED_WORDS = ['failed', 'failing', 'failures'];\n\nconst DONE_WORDS = ['done', 'finished', 'successful', 'succeeded'];\n\nconst MAX_ROWS = 2;\n\nfunction wordsOf(text: string) {\n  const lowered = text.toLowerCase();\n  const letters = lowered.replace(/[^a-z0-9\\s]/g, ' ');\n  const trimmed = letters.trim();\n  if (trimmed === '') {\n    return [];\n  }\n  return trimmed.split(/\\s+/);\n}\n\nfunction hasAny(words: string[], candidates: string[]) {\n  return words.some((word) => candidates.includes(word));\n}\n\nfunction measureOf(word: string) {\n  return MEASURES.find((measure) => MEASURE_WORDS[measure].includes(word));\n}\n\nfunction dimensionOf(word: string) {\n  return DIMENSIONS.find((dimension) =>\n    DIMENSION_WORDS[dimension].includes(word)\n  );\n}\n\nfunction aggregationOf(words: string[]): Aggregation {\n  if (hasAny(words, AVERAGE_WORDS)) {\n    return 'avg';\n  }\n  if (hasAny(words, COUNT_WORDS)) {\n    return 'count';\n  }\n  return 'sum';\n}\n\n/** A day is named in full or by its first letters: monday and mon both mean Mon. */\nfunction matchesWord(word: string, valueWord: string, dimension: DimensionId) {\n  if (dimension === 'day') {\n    return word.startsWith(valueWord);\n  }\n  return word === valueWord;\n}\n\nfunction isNamed(words: string[], value: string, dimension: DimensionId) {\n  const valueWords = wordsOf(value);\n  return valueWords.every((valueWord) =>\n    words.some((word) => matchesWord(word, valueWord, dimension))\n  );\n}\n\n/** \"claude sonnet\" or \"coder\" in the question keeps only that value of its dimension. */\nfunction namedFiltersOf(words: string[]) {\n  const filters: FilterSpec[] = [];\n  for (const dimension of DIMENSIONS) {\n    if (dimension === 'status') {\n      continue;\n    }\n    const named = DIMENSION_VALUES[dimension].filter((value) =>\n      isNamed(words, value, dimension)\n    );\n    if (named.length > 0) {\n      filters.push({ field: dimension, values: named });\n    }\n  }\n  return filters;\n}\n\nfunction statusFilterOf(words: string[]): FilterSpec | null {\n  if (hasAny(words, FAILED_WORDS)) {\n    return { field: 'status', values: ['Failed'] };\n  }\n  if (hasAny(words, DONE_WORDS)) {\n    return { field: 'status', values: ['Done'] };\n  }\n  return null;\n}\n\ntype Placement = {\n  rows: DimensionId[];\n  columns: DimensionId[];\n};\n\n/** Walks the words: \"by\" sends the next dimensions to the rows, \"per\" sends the next one to the column. */\nfunction placementOf(words: string[]) {\n  const placement: Placement = { rows: [], columns: [] };\n  let target: keyof Placement = 'rows';\n  for (const word of words) {\n    if (ROW_WORDS.includes(word)) {\n      target = 'rows';\n      continue;\n    }\n    if (COLUMN_WORDS.includes(word)) {\n      target = 'columns';\n      continue;\n    }\n    const dimension = dimensionOf(word);\n    if (!dimension) {\n      continue;\n    }\n    const isRow = placement.rows.includes(dimension);\n    const isColumn = placement.columns.includes(dimension);\n    if (isRow || isColumn) {\n      continue;\n    }\n    const wantsColumn = target === 'columns' && placement.columns.length === 0;\n    if (wantsColumn) {\n      placement.columns.push(dimension);\n      continue;\n    }\n    if (placement.rows.length < MAX_ROWS) {\n      placement.rows.push(dimension);\n    }\n  }\n  return placement;\n}\n\n/**\n * Reads a plain question into the four wells with a handful of word lists: no model is called.\n * It returns nothing when the question names no field.\n */\nexport function wellsOfQuestion(text: string): Wells | null {\n  const words = wordsOf(text);\n  const measures = words.map(measureOf);\n  const measure = measures.find((found) => found !== undefined);\n  const placement = placementOf(words);\n  const namedFilters = namedFiltersOf(words);\n  const statusFilter = statusFilterOf(words);\n  const hasMeasure = measure !== undefined;\n  const hasDimension = placement.rows.length + placement.columns.length > 0;\n  const hasFilter = namedFilters.length > 0 || statusFilter !== null;\n  const namesSomething = hasMeasure || hasDimension || hasFilter;\n  if (!namesSomething) {\n    return null;\n  }\n  const value: ValueSpec = {\n    measure: measure ?? 'runs',\n    aggregation: aggregationOf(words),\n  };\n  const filters = [...namedFilters];\n  if (statusFilter) {\n    filters.push(statusFilter);\n  }\n  const grouped = [...placement.rows, ...placement.columns];\n  const freeFilters = filters.filter(\n    (filter) => !grouped.includes(filter.field)\n  );\n  return {\n    filters: freeFilters,\n    columns: placement.columns,\n    rows: placement.rows,\n    values: [value],\n  };\n}\n",
      "type": "registry:component",
      "target": "components/blocks/agent-ops-09/ask.ts"
    },
    {
      "path": "registry/ndeko/blocks/agent-ops/agent-ops-09/csv.ts",
      "content": "import { valueLabelOf, type PivotCell, type PivotTable } from './pivot';\n\nconst FORMULA_PREFIXES = ['=', '+', '-', '@'];\n\n/** Spreadsheet apps run a cell that starts with these characters as a formula. */\nfunction neutralizedCellOf(value: string) {\n  const startsLikeFormula = FORMULA_PREFIXES.some((prefix) =>\n    value.startsWith(prefix)\n  );\n  if (startsLikeFormula) {\n    return `'${value}`;\n  }\n  return value;\n}\n\nfunction csvCellOf(value: string) {\n  const neutralized = neutralizedCellOf(value);\n  const escaped = neutralized.replaceAll('\"', '\"\"');\n  return `\"${escaped}\"`;\n}\n\nfunction csvLineOf(row: string[]) {\n  const cells = row.map(csvCellOf);\n  return cells.join(',');\n}\n\n/** Figures leave as plain numbers, three decimals at most, so a spreadsheet can add them up. */\nfunction plainOf(cell: PivotCell) {\n  if (cell.value === null) {\n    return '';\n  }\n  const rounded = Number(cell.value.toFixed(3));\n  return String(rounded);\n}\n\nfunction headingOf(columnKey: string, valueLabel: string) {\n  if (columnKey === '') {\n    return valueLabel;\n  }\n  return `${columnKey} ${valueLabel}`;\n}\n\nfunction headerOf(table: PivotTable) {\n  const valueLabels = table.values.map(valueLabelOf);\n  const header = [table.rowHeader];\n  for (const columnKey of table.columnKeys) {\n    for (const valueLabel of valueLabels) {\n      header.push(headingOf(columnKey, valueLabel));\n    }\n  }\n  if (table.hasColumns) {\n    for (const valueLabel of valueLabels) {\n      header.push(headingOf('Total', valueLabel));\n    }\n  }\n  return header;\n}\n\nfunction lineOf(\n  table: PivotTable,\n  label: string,\n  cells: PivotCell[],\n  totals: PivotCell[]\n) {\n  const figures = cells.map(plainOf);\n  if (!table.hasColumns) {\n    return [label, ...figures];\n  }\n  const totalFigures = totals.map(plainOf);\n  return [label, ...figures, ...totalFigures];\n}\n\n/** A sub-row is indented under its group, as it is on screen. */\nfunction labelOf(label: string, depth: number) {\n  const indent = '  '.repeat(depth);\n  return `${indent}${label}`;\n}\n\n/** The table as it is on screen: folded groups stay folded in the file. */\nexport function csvRowsOf(table: PivotTable) {\n  const rows = table.rows.map((row) => {\n    const label = labelOf(row.label, row.depth);\n    return lineOf(table, label, row.cells, row.totals);\n  });\n  const total = lineOf(table, 'Total', table.grandCells, table.grandTotals);\n  return [headerOf(table), ...rows, total];\n}\n\n/** Builds the file in the browser and hands it to the download bar: nothing leaves the page. */\nexport function downloadCsv(fileName: string, rows: string[][]) {\n  const lines = rows.map(csvLineOf);\n  const text = lines.join('\\n');\n  const file = new Blob([text], { type: 'text/csv;charset=utf-8' });\n  const url = URL.createObjectURL(file);\n  const link = document.createElement('a');\n  link.href = url;\n  link.download = fileName;\n  link.click();\n  window.setTimeout(() => URL.revokeObjectURL(url), 0);\n}\n",
      "type": "registry:component",
      "target": "components/blocks/agent-ops-09/csv.ts"
    },
    {
      "path": "registry/ndeko/blocks/agent-ops/agent-ops-09/session.ts",
      "content": "import type { SessionStep } from '@/registry/ndeko/hooks/use-session';\n\nimport { ASK_EXAMPLE, wellsOfQuestion } from './ask';\nimport type { DimensionId, FieldId, MeasureId } from './data';\nimport {\n  EMPTY_WELLS,\n  placed,\n  removed,\n  swapped,\n  withAggregation,\n  withFilterValue,\n  type Aggregation,\n  type WellId,\n  type Wells,\n} from './pivot';\n\n/** A field held over a well: the table already shows what dropping it there gives. */\nexport type Preview = {\n  field: FieldId;\n  well: WellId;\n};\n\nexport type PivotState = {\n  wells: Wells;\n  preview: Preview | null;\n  /** The groups whose rows are folded. */\n  collapsed: string[];\n  question: string;\n  hasAskFailed: boolean;\n  /** Counts the drops of each field: a dropped chip lands where it was let go, it does not fly from the list. */\n  drops: Partial<Record<FieldId, number>>;\n};\n\nexport type PivotAction =\n  | { type: 'previewed'; preview: Preview | null }\n  | { type: 'placed'; field: FieldId; well: WellId; isDrop?: boolean }\n  | { type: 'removed'; field: FieldId }\n  | { type: 'aggregation'; measure: MeasureId; aggregation: Aggregation }\n  | { type: 'filterValue'; field: DimensionId; value: string }\n  | { type: 'swapped' }\n  | { type: 'cleared' }\n  | { type: 'filtersCleared' }\n  | { type: 'groupToggled'; key: string }\n  | { type: 'questionTyped'; text: string }\n  | { type: 'asked' };\n\ntype Step = SessionStep<PivotState, PivotAction>;\n\nconst FIRST_WELLS: Wells = {\n  filters: [],\n  columns: [],\n  rows: ['agent'],\n  values: [{ measure: 'cost', aggregation: 'sum' }],\n};\n\nexport const INITIAL: PivotState = {\n  wells: FIRST_WELLS,\n  preview: null,\n  collapsed: [],\n  question: '',\n  hasAskFailed: false,\n  drops: {},\n};\n\n/** The wells the table is drawn from: the committed ones, or what the held field would give. */\nexport function shownWellsOf(wells: Wells, preview: Preview | null) {\n  if (!preview) {\n    return wells;\n  }\n  return placed(wells, preview.field, preview.well);\n}\n\n/** Folded groups belong to the rows they were folded in. */\nfunction withWells(state: PivotState, wells: Wells): PivotState {\n  const rowsBefore = state.wells.rows.join(' ');\n  const rowsAfter = wells.rows.join(' ');\n  if (rowsBefore === rowsAfter) {\n    return { ...state, wells, preview: null };\n  }\n  return { ...state, wells, preview: null, collapsed: [] };\n}\n\nfunction placedIn(\n  state: PivotState,\n  field: FieldId,\n  well: WellId,\n  isDrop: boolean\n): PivotState {\n  const next = withWells(state, placed(state.wells, field, well));\n  if (!isDrop) {\n    return next;\n  }\n  const dropCount = state.drops[field] ?? 0;\n  return { ...next, drops: { ...state.drops, [field]: dropCount + 1 } };\n}\n\nfunction groupToggled(state: PivotState, key: string): PivotState {\n  const isFolded = state.collapsed.includes(key);\n  if (isFolded) {\n    const collapsed = state.collapsed.filter((candidate) => candidate !== key);\n    return { ...state, collapsed };\n  }\n  return { ...state, collapsed: [...state.collapsed, key] };\n}\n\nfunction asked(state: PivotState): PivotState {\n  const wells = wellsOfQuestion(state.question);\n  if (!wells) {\n    return { ...state, hasAskFailed: true };\n  }\n  const next = withWells(state, wells);\n  return { ...next, hasAskFailed: false };\n}\n\nexport function reducer(state: PivotState, action: PivotAction): PivotState {\n  switch (action.type) {\n    case 'previewed':\n      return { ...state, preview: action.preview };\n    case 'placed':\n      return placedIn(state, action.field, action.well, action.isDrop ?? false);\n    case 'removed':\n      return withWells(state, removed(state.wells, action.field));\n    case 'aggregation':\n      return withWells(\n        state,\n        withAggregation(state.wells, action.measure, action.aggregation)\n      );\n    case 'filterValue':\n      return withWells(\n        state,\n        withFilterValue(state.wells, action.field, action.value)\n      );\n    case 'swapped':\n      return withWells(state, swapped(state.wells));\n    case 'cleared':\n      return withWells(state, EMPTY_WELLS);\n    case 'filtersCleared':\n      return withWells(state, { ...state.wells, filters: [] });\n    case 'groupToggled':\n      return groupToggled(state, action.key);\n    case 'questionTyped':\n      return { ...state, question: action.text, hasAskFailed: false };\n    case 'asked':\n      return asked(state);\n  }\n}\n\nconst CHUNK = 3;\n\nfunction delayOfChunk(index: number) {\n  if (index === 0) {\n    return 1700;\n  }\n  return 70;\n}\n\nfunction typingSteps(): Step[] {\n  const steps: Step[] = [];\n  const last = ASK_EXAMPLE.length + CHUNK;\n  for (let end = CHUNK; end < last; end += CHUNK) {\n    const text = ASK_EXAMPLE.slice(0, end);\n    const after = delayOfChunk(steps.length);\n    steps.push({\n      after,\n      by: 'demo',\n      action: { type: 'questionTyped', text },\n    });\n  }\n  return steps;\n}\n\n/** How long the demonstration holds a field over a well before it lets go. */\nconst HOLD_MS = 1000;\n\n/** Holds a field over a well, where the table already regroups, then drops it there. */\nfunction dragSteps(after: number, field: FieldId, well: WellId): Step[] {\n  return [\n    {\n      after,\n      by: 'demo',\n      press: `field-${field}`,\n      action: { type: 'previewed', preview: { field, well } },\n    },\n    { after: HOLD_MS, by: 'demo', action: { type: 'placed', field, well } },\n  ];\n}\n\nconst BUILDING: Step[] = [\n  ...dragSteps(1400, 'day', 'columns'),\n  ...dragSteps(1500, 'model', 'rows'),\n];\n\nexport const SCRIPT: Step[] = [\n  ...BUILDING,\n  {\n    after: 1700,\n    by: 'demo',\n    press: 'group-Coder',\n    action: { type: 'groupToggled', key: 'Coder' },\n  },\n  ...typingSteps(),\n  { after: 500, by: 'demo', press: 'ask', action: { type: 'asked' } },\n  { after: 2400, by: 'demo', press: 'swap', action: { type: 'swapped' } },\n];\n\n/** Under reduced motion the table rests on cost by agent and model per day, groups open. */\nfunction restingOf() {\n  let state = INITIAL;\n  for (const step of BUILDING) {\n    state = reducer(state, step.action);\n  }\n  return state;\n}\n\nexport const RESTING = restingOf();\n\nexport const LOOP_AFTER_MS = 3800;\n",
      "type": "registry:component",
      "target": "components/blocks/agent-ops-09/session.ts"
    },
    {
      "path": "registry/ndeko/blocks/agent-ops/agent-ops-09/data.ts",
      "content": "import type { BrandSlug } from '@/registry/ndeko/lib/brand-logos';\n\nexport type DimensionId = 'agent' | 'model' | 'day' | 'status' | 'tool';\n\nexport type MeasureId = 'runs' | 'cost' | 'tokens' | 'duration';\n\nexport type FieldId = DimensionId | MeasureId;\n\nexport type RunRecord = Record<DimensionId, string> & Record<MeasureId, number>;\n\nexport type Field = {\n  id: FieldId;\n  label: string;\n  kind: 'dimension' | 'measure';\n};\n\nexport const DIMENSIONS: DimensionId[] = [\n  'agent',\n  'model',\n  'day',\n  'status',\n  'tool',\n];\n\nexport const MEASURES: MeasureId[] = ['runs', 'cost', 'tokens', 'duration'];\n\nexport const FIELDS: Field[] = [\n  { id: 'agent', label: 'Agent', kind: 'dimension' },\n  { id: 'model', label: 'Model', kind: 'dimension' },\n  { id: 'day', label: 'Day', kind: 'dimension' },\n  { id: 'status', label: 'Status', kind: 'dimension' },\n  { id: 'tool', label: 'Tool', kind: 'dimension' },\n  { id: 'runs', label: 'Runs', kind: 'measure' },\n  { id: 'cost', label: 'Cost', kind: 'measure' },\n  { id: 'tokens', label: 'Tokens', kind: 'measure' },\n  { id: 'duration', label: 'Duration', kind: 'measure' },\n];\n\nexport function fieldOf(id: FieldId) {\n  const field = FIELDS.find((candidate) => candidate.id === id);\n  return field ?? FIELDS[0];\n}\n\nexport function isDimension(id: FieldId): id is DimensionId {\n  return fieldOf(id).kind === 'dimension';\n}\n\nexport function isMeasure(id: FieldId): id is MeasureId {\n  return fieldOf(id).kind === 'measure';\n}\n\n/** The values of each dimension, in the order the table lists them. */\nexport const DIMENSION_VALUES: Record<DimensionId, string[]> = {\n  agent: ['Planner', 'Researcher', 'Writer', 'Reviewer', 'Coder'],\n  model: ['Claude Sonnet', 'Claude Haiku', 'GPT mini', 'Gemini Pro'],\n  day: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],\n  status: ['Done', 'Failed'],\n  tool: ['GitHub', 'Linear', 'Notion', 'Web search'],\n};\n\n/** The marks of the model makers and of the tools, shown beside their name. */\nexport const VALUE_BRAND: Record<string, BrandSlug> = {\n  'Claude Sonnet': 'claude',\n  'Claude Haiku': 'claude',\n  'GPT mini': 'openai',\n  'Gemini Pro': 'gemini',\n  GitHub: 'github',\n  Linear: 'linear',\n  Notion: 'notion',\n};\n\ntype AgentProfile = {\n  agent: string;\n  models: string[];\n  tools: string[];\n  /** Runs on a working day. */\n  runsPerDay: number;\n  costUsd: number;\n  tokens: number;\n  durationMs: number;\n};\n\nconst PROFILES: AgentProfile[] = [\n  {\n    agent: 'Planner',\n    models: ['Gemini Pro'],\n    tools: ['Linear', 'Notion'],\n    runsPerDay: 2,\n    costUsd: 0.62,\n    tokens: 48_000,\n    durationMs: 94_000,\n  },\n  {\n    agent: 'Researcher',\n    models: ['Claude Sonnet', 'Claude Haiku'],\n    tools: ['Web search', 'Notion'],\n    runsPerDay: 4,\n    costUsd: 0.31,\n    tokens: 36_000,\n    durationMs: 141_000,\n  },\n  {\n    agent: 'Writer',\n    models: ['GPT mini'],\n    tools: ['Notion'],\n    runsPerDay: 3,\n    costUsd: 0.12,\n    tokens: 22_000,\n    durationMs: 52_000,\n  },\n  {\n    agent: 'Reviewer',\n    models: ['Claude Sonnet'],\n    tools: ['GitHub', 'Linear'],\n    runsPerDay: 3,\n    costUsd: 0.27,\n    tokens: 31_000,\n    durationMs: 77_000,\n  },\n  {\n    agent: 'Coder',\n    models: ['Claude Sonnet', 'Claude Haiku'],\n    tools: ['GitHub'],\n    runsPerDay: 5,\n    costUsd: 0.84,\n    tokens: 91_000,\n    durationMs: 228_000,\n  },\n];\n\n/** Fewer runs at the weekend. */\nconst DAY_LOAD = [1, 1, 1, 1, 1, 0.4, 0.3];\n\n/** One run in this many fails. */\nconst FAILURE_EVERY = 9;\n\n/** A fixed seed, so the page reads the same on the server and in the browser. */\nconst SEED = 20261112;\n\nconst MODULUS = 4_294_967_296;\n\nfunction createRandom(seed: number) {\n  let state = seed;\n  return () => {\n    state = (state * 1_664_525 + 1_013_904_223) % MODULUS;\n    return state / MODULUS;\n  };\n}\n\nfunction pick(values: string[], roll: number) {\n  const index = Math.floor(roll * values.length);\n  return values[index];\n}\n\n/** Between 0.6 and 1.4 times the usual figure. */\nfunction swingOf(roll: number) {\n  return 0.6 + roll * 0.8;\n}\n\nfunction statusOf(runNumber: number) {\n  if (runNumber % FAILURE_EVERY === 0) {\n    return 'Failed';\n  }\n  return 'Done';\n}\n\nfunction recordsOf() {\n  const random = createRandom(SEED);\n  const records: RunRecord[] = [];\n  const days = DIMENSION_VALUES.day;\n  days.forEach((day, dayIndex) => {\n    for (const profile of PROFILES) {\n      const load = profile.runsPerDay * DAY_LOAD[dayIndex];\n      const runCount = Math.max(1, Math.round(load));\n      for (let run = 0; run < runCount; run += 1) {\n        const swing = swingOf(random());\n        const runNumber = records.length + 1;\n        records.push({\n          agent: profile.agent,\n          model: pick(profile.models, random()),\n          day,\n          status: statusOf(runNumber),\n          tool: pick(profile.tools, random()),\n          runs: 1,\n          cost: Number((profile.costUsd * swing).toFixed(3)),\n          tokens: Math.round(profile.tokens * swing),\n          duration: Math.round(profile.durationMs * swing),\n        });\n      }\n    }\n  });\n  return records;\n}\n\n/** One record per run of last week. Invented and illustrative. */\nexport const RECORDS = recordsOf();\n",
      "type": "registry:component",
      "target": "components/blocks/agent-ops-09/data.ts"
    }
  ],
  "categories": [
    "blocks",
    "agent-ops"
  ],
  "type": "registry:block"
}