# Stream adapters (Notchset): prompt.md (v1.0.0)

- id: `stream-adapters` · version 1.0.0 · component · free
- category: AI
- build: one set of files for every shadcn style
- install: `npx shadcn@latest add https://notchset.dev/r/stream-adapters.json`
- npm dependencies: none
- registry dependencies: utils, https://notchset.dev/r/notchset-foundation.json
- docs: https://notchset.dev/components/stream-adapters
- The install command carries everything this item needs (files, CSS, tokens, npm and registry dependencies). Prefer it to copying source by hand.

The data every agentic piece takes, typed once: the AI SDK's parts verbatim, and our run, plan, approval, question, cost and change. A run has eight states; a tool call's seven read as six words. Each format's word for a run's state (AI SDK, AG-UI, A2A, MCP, OpenAI Agents, Linear) maps onto the eight in one table..

## Build it
- Stack: React 18.3 or 19, TypeScript, Tailwind CSS v4 utility classes on the foundation's roles, a components.json (imports use its aliases).
- Packages: none beyond `react` and `react-dom`.
- Files: `components/ui/notchset/stream-adapters.tsx`; shared code: `lib/notchset/ui-message.ts`, `lib/notchset/words.ts`.
- Registry dependencies, installed with it automatically: shadcn `utils` (cn), `notchset-foundation`.
- Builds: one set of files, the same for every shadcn style.
- Exports to keep: `RUN_STATUSES`, `RUN_STATUS_WORDS`, `runEnded`, `TOOL_DISPLAY`, `TOOL_DISPLAY_WORDS`, `toolDisplayOf`, `RUN_STATUS_FROM`, `runStatusFrom`, `staleAfter`, `mcp`, `runOf`, `RunAnnouncer`, and every exported type.
- CSS: the install adds the notchset foundation (its roles, keyframes and motion switch, reading your shadcn tokens for colour) to your global stylesheet once. Nothing to import by hand.
- Re-running `add` (or `--overwrite`) re-applies those rules: put overrides in your own CSS, never in the installed rules.
- Colours: every part reads the foundation's roles (`--ns-canvas`, `--ns-ink`, `--ns-line`, `--ns-signal` …), which read your shadcn tokens (`--background`, `--foreground`, `--border`, `--destructive` …), plus the optional `--success` and `--warning`. Retheme on `:root` or any container; never add Tailwind colour classes inside the component.
- Retune it (on any ancestor) with the foundation's roles and hooks: `--ns-agent-b`, `--ns-agent-c`, `--ns-agent-d`, `--ns-agent-drift`, `--ns-agent-fill`, `--ns-agent-h1`, `--ns-agent-h2`, `--ns-agent-h3`, `--ns-agent-shift`, `--ns-avatar-card`, `--ns-avatar-lg`, `--ns-avatar-md`, `--ns-avatar-sm`, `--ns-avatar-xs`, `--ns-bad`, `--ns-bad-ink`, `--ns-band`, `--ns-band-edge`, `--ns-band-grade`, `--ns-band-optimal`, `--ns-banner-beat`, `--ns-banner-radius`, `--ns-beat`, `--ns-beat-ease`, `--ns-bezel`, `--ns-bloom-close`, `--ns-bloom-open`, `--ns-bloom-rise`, `--ns-btn-bad`, `--ns-btn-bad-hover`, `--ns-btn-bad-line`, `--ns-btn-bezel`, `--ns-btn-chosen`, `--ns-btn-gone`, `--ns-btn-morph`, `--ns-btn-ok`, `--ns-btn-press`, `--ns-btn-release`, `--ns-btn-result`, `--ns-btn-roll`, `--ns-btn-stagger`, `--ns-btn-stagger-step`, `--ns-btn-tick`, `--ns-btn-tonal`, `--ns-btn-tonal-edge`, `--ns-btn-tonal-hover`, `--ns-bulk-clear`, `--ns-button`, `--ns-button-field-inset`, `--ns-button-lg`, `--ns-button-sm`, `--ns-canvas`, `--ns-card-tilt`, `--ns-cat-1`, `--ns-cat-2`, `--ns-cat-3`, `--ns-cat-4`, `--ns-cat-5`, `--ns-cat-6`, `--ns-check`, `--ns-check-round`, `--ns-cheer-1`, `--ns-cheer-2`, `--ns-cheer-3`, `--ns-cheer-edge`, `--ns-cheer-fold`, `--ns-cheer-glow`, `--ns-cheer-lift`, `--ns-chip`, `--ns-chip-pick`, `--ns-control`, `--ns-control-lg`, `--ns-control-pad`, `--ns-control-sm`, `--ns-corner`, `--ns-danger`, `--ns-deep`, `--ns-deep-ink`, `--ns-deep-ink-2`, `--ns-deep-line`, `--ns-depth-card`, `--ns-depth-lift`, `--ns-depth-surface`, `--ns-dialog`, `--ns-dialog-grow`, `--ns-dialog-lg`, `--ns-dialog-max`, `--ns-dialog-shrink`, `--ns-dialog-sm`, `--ns-dialog-top`, `--ns-dock-bottom`, `--ns-drop`, `--ns-ease`, `--ns-ease-arrive`, `--ns-ease-breathe`, `--ns-ease-drum`, `--ns-ease-exit`, `--ns-ease-fling`, `--ns-ease-glide`, `--ns-ease-grow`, `--ns-ease-move`, `--ns-ease-panel`, `--ns-ease-pop`, `--ns-ease-press`, `--ns-ease-spring`, `--ns-ebg-arm`, `--ns-ebg-lit`, `--ns-emoji`, `--ns-emoji-md`, `--ns-emoji-sm`, `--ns-field`, `--ns-field-edge`, `--ns-field-h`, `--ns-fill`, `--ns-fill-time`, `--ns-flood-arc`, `--ns-flood-aurora`, `--ns-flood-behind-1`, `--ns-flood-behind-2`, `--ns-flood-bloom`, `--ns-flood-deep`, `--ns-flood-dial-bloom`, `--ns-flood-glass`, `--ns-flood-grain`, `--ns-flood-image`, `--ns-flood-ink`, `--ns-flood-ink-low`, `--ns-flood-light`, `--ns-flood-mid`, `--ns-flood-pale`, `--ns-flood-pane`, `--ns-flood-pane-edge`, `--ns-flood-pill-ink`, `--ns-flood-ribbon`, `--ns-flood-ribbon-core`, `--ns-flood-shadow`, `--ns-flood-sheen`, `--ns-flood-wash`, `--ns-font-body`, `--ns-font-display`, `--ns-font-mono`, `--ns-font-script`, `--ns-glass`, `--ns-glass-blur`, `--ns-glass-shadow`, `--ns-glow`, `--ns-glyph-pad`, `--ns-grain`, `--ns-gutter`, `--ns-header`, `--ns-help-max`, `--ns-hit`, `--ns-hover`, `--ns-icon`, `--ns-icon-lg`, `--ns-icon-sm`, `--ns-icon-stroke`, `--ns-info`, `--ns-info-ink`, `--ns-ink`, `--ns-ink-2`, `--ns-ink-3`, `--ns-ink-4`, `--ns-layer-bar`, `--ns-layer-modal`, `--ns-layer-panel`, `--ns-layer-popup`, `--ns-layer-sticky`, `--ns-layer-tip`, `--ns-layer-toast`, `--ns-layer-zoom`, `--ns-lead-body`, `--ns-lead-figure`, `--ns-lead-large`, `--ns-lead-meta`, `--ns-lead-small`, `--ns-lead-sub`, `--ns-lead-title`, `--ns-leading`, `--ns-leading-prose`, `--ns-leading-title`, `--ns-lift`, `--ns-light-1`, `--ns-light-2`, `--ns-light-3`, `--ns-light-spread`, `--ns-light-strength`, `--ns-line`, `--ns-line-soft`, `--ns-lit-edge`, `--ns-map-grass`, `--ns-map-water`, `--ns-mark-edge`, `--ns-mark-lifted`, `--ns-mark-rest`, `--ns-mark-swap`, `--ns-marker`, `--ns-marker-ink`, `--ns-mc-place`, `--ns-mc-roll`, `--ns-measure`, `--ns-menu-dy`, `--ns-menu-lit`, `--ns-menu-pad`, `--ns-menu-row`, `--ns-menu-rule`, `--ns-mesh`, `--ns-mesh-frost`, `--ns-nest-inset`, `--ns-nest-outer`, `--ns-nest-r`, `--ns-notch-ease`, `--ns-ok`, `--ns-ok-ink`, `--ns-on-fill`, `--ns-orb-body`, `--ns-orb-cool`, `--ns-orb-core`, `--ns-orb-dawn`, `--ns-orb-deep`, `--ns-orb-edge`, `--ns-orb-grain`, `--ns-orb-ground`, `--ns-orb-halo`, `--ns-orb-inner`, `--ns-orb-key`, `--ns-orb-lift`, `--ns-orb-limb`, `--ns-orb-limb-from`, `--ns-orb-rim`, `--ns-orb-skin-hi`, `--ns-orb-skin-lo`, `--ns-orb-skin-mid`, `--ns-orb-warm`, `--ns-palette-min`, `--ns-panel`, `--ns-panel-room`, `--ns-panel-w`, `--ns-panel-w-lg`, `--ns-pick-slot`, `--ns-pill-prop`, `--ns-play-fill`, `--ns-play-fill-color`, `--ns-play-lift`, `--ns-play-lift-y`, `--ns-play-open`, `--ns-play-open-content`, `--ns-play-press`, `--ns-play-press-box`, `--ns-play-reduced`, `--ns-play-ring`, `--ns-play-roll`, `--ns-play-shake`, `--ns-play-spring`, `--ns-play-swap`, `--ns-play-swap-blur`, `--ns-press-min`, `--ns-press-scale`, `--ns-press-x`, `--ns-press-y`, `--ns-primary-hover`, `--ns-primary-press`, `--ns-prism-edge`, `--ns-prism-glint`, `--ns-prism-sheen`, `--ns-prism-tint`, `--ns-pulse`, `--ns-radius`, `--ns-radius-2xl`, `--ns-radius-button`, `--ns-radius-button-lg`, `--ns-radius-button-sm`, `--ns-radius-card`, `--ns-radius-check`, `--ns-radius-control`, `--ns-radius-control-sm`, `--ns-radius-float`, `--ns-radius-full`, `--ns-radius-lg`, `--ns-radius-mark`, `--ns-radius-menu-row`, `--ns-radius-modal`, `--ns-radius-pill`, `--ns-radius-sm`, `--ns-radius-xl`, `--ns-radius-xs`, `--ns-raised`, `--ns-ramp-1`, `--ns-ramp-2`, `--ns-ramp-3`, `--ns-ramp-4`, `--ns-ramp-5`, `--ns-ramp-shine`, `--ns-range`, `--ns-rest-1`, `--ns-rest-2`, `--ns-rest-3`, `--ns-rise`, `--ns-row`, `--ns-row-compact`, `--ns-row-hue`, `--ns-scrim`, `--ns-search-h`, `--ns-segment`, `--ns-segment-inset`, `--ns-segment-lift`, `--ns-segment-sm`, `--ns-selected`, `--ns-series`, `--ns-series-core`, `--ns-series-glint`, `--ns-series-tint`, `--ns-shadow-dialog`, `--ns-shadow-float`, `--ns-shadow-lift`, `--ns-shadow-panel`, `--ns-sheet`, `--ns-sheet-back`, `--ns-sheet-bottom`, `--ns-sheet-drop`, `--ns-sheet-rise`, `--ns-shift`, `--ns-side`, `--ns-signal`, `--ns-signal-ink`, `--ns-signal-wash`, `--ns-sk-figure`, `--ns-sk-land`, `--ns-sk-p`, `--ns-sk-p0`, `--ns-sk-p1`, `--ns-sk-p2`, `--ns-sk-p3`, `--ns-sk-p4`, `--ns-sk-p5`, `--ns-sk-p6`, `--ns-sk-p7`, `--ns-sk-read`, `--ns-sk-sweep`, `--ns-skeleton`, `--ns-skeleton-bone`, `--ns-skeleton-bone-light`, `--ns-skeleton-light`, `--ns-slab`, `--ns-slab-edge`, `--ns-slab-ink`, `--ns-sleep-awake`, `--ns-sleep-deep`, `--ns-sleep-light`, `--ns-sleep-rem`, `--ns-space-1`, `--ns-space-2`, `--ns-space-3`, `--ns-space-4`, `--ns-space-5`, `--ns-space-6`, `--ns-space-8`, `--ns-space-section`, `--ns-stack-fan`, `--ns-stack-fan-gap`, `--ns-stack-fan-lag`, `--ns-stack-on`, `--ns-stagger-item`, `--ns-stagger-mark`, `--ns-stagger-max`, `--ns-standing-critical`, `--ns-standing-in`, `--ns-standing-out`, `--ns-state-doing`, `--ns-state-done`, `--ns-state-review`, `--ns-state-todo`, `--ns-step`, `--ns-step-from`, `--ns-step-sign`, `--ns-swipe-surface`, `--ns-switch-h`, `--ns-switch-w`, `--ns-text-body`, `--ns-text-control`, `--ns-text-control-lg`, `--ns-text-display`, `--ns-text-editorial`, `--ns-text-empty`, `--ns-text-figure`, `--ns-text-giant`, `--ns-text-heading`, `--ns-text-headline`, `--ns-text-input`, `--ns-text-large`, `--ns-text-lede`, `--ns-text-meta`, `--ns-text-record`, `--ns-text-sentence`, `--ns-text-small`, `--ns-text-sub`, `--ns-text-title`, `--ns-theme-fade`, `--ns-tile-shadow`, `--ns-time-born`, `--ns-time-color`, `--ns-time-confirm`, `--ns-time-dialog`, `--ns-time-fling`, `--ns-time-flip`, `--ns-time-glide`, `--ns-time-grow`, `--ns-time-hold`, `--ns-time-menu`, `--ns-time-page`, `--ns-time-panel`, `--ns-time-quick`, `--ns-time-roll`, `--ns-time-settle`, `--ns-time-snap`, `--ns-time-spin`, `--ns-time-spring`, `--ns-time-sweep`, `--ns-time-toast`, `--ns-tint`, `--ns-tint-c`, `--ns-tint-ease`, `--ns-tint-fill`, `--ns-tint-gap`, `--ns-tint-h1`, `--ns-tint-h2`, `--ns-tint-h3`, `--ns-tint-ink`, `--ns-tint-row`, `--ns-tip-fold`, `--ns-tip-grow`, `--ns-toast-bottom`, `--ns-toast-gap`, `--ns-toast-left`, `--ns-toast-lift`, `--ns-toast-peek`, `--ns-toast-scale`, `--ns-toast-w`, `--ns-touch`, `--ns-tracking-body`, `--ns-tracking-caps`, `--ns-tracking-control`, `--ns-tracking-display`, `--ns-tracking-headline`, `--ns-tracking-sub`, `--ns-tracking-title`, `--ns-warn`, `--ns-warn-ink`, `--ns-wash-clay`, `--ns-wash-dusk`, `--ns-wash-graphite`, `--ns-wash-ink`, `--ns-wash-sage`, `--ns-wash-sand`, `--ns-weight-light`, `--ns-weight-medium`, `--ns-weight-regular`, `--ns-weight-strong`, `--ns-well`, `--ns-width-lg`, `--ns-width-md`, `--ns-width-sm`, `--ns-width-xl`.
- Never add Tailwind colour classes inside the component.

```tsx
import { Card } from "@/components/ui/notchset/card";
```

## Parts
- A single export that takes props.

## Match the original
- Read `components/ui/notchset/stream-adapters.tsx` as the reference implementation before changing or recreating anything, and match it: sizes, colours per theme, motion timings, copy and behaviour.
- If you deviate (a prop you can't honour, a style you changed, a dependency you swapped), say so in your reply, part by part.
- Keep the accessibility contract, the keyboard map and the motion levels listed below.

## Use it when
- Wiring any agentic piece to a stream: pass AI SDK messages straight in, or read another format's words through runStatusFrom and mcp.toneFromHints.

### Not when
- A piece's own words and looks are its props (a tool row's labels, a run pill's words); this holds only the shapes and the state names.

## Built from
- Ui message (shared helper, ships with it)
- Words (shared helper, ships with it)

## Mistakes
- Inventing a ninth run state: the eight are typed, so tsc refuses it
- Reading a cancel as a failure: stopped is something a person did
- Fetching or holding the conversation in a piece: state comes in, callbacks go out

## Usage

```tsx
"use client";
import * as React from "react";
import { Card } from "@/components/ui/notchset/card";
import { LiveLabel } from "@/components/ui/notchset/live-label";
import { StatusGlyphRun } from "@/components/ui/notchset/status-glyph-run";
import { RUN_STATUS_WORDS, RunAnnouncer, runOf, runStatusFrom, type RunStatus, type UIMessage } from "@/components/ui/notchset/stream-adapters";
import { useLessMotion } from "@/lib/notchset/motion";
import { useSelfPlay } from "./self-play";

/*
 * One run, fed by a format switch: the same scripted run (an agent fixing a GitHub build, asking before it pushes)
 * arrives as AI SDK messages, AG-UI events or A2A task states. Each goes through the contract's one reader and the
 * same two pieces react, the glyph and the live label, the same way whichever format it came in; under them, the
 * word the format itself sent. The run plays once on view and rests at its end (less motion shows the end); the
 * first touch makes it yours; choosing a format (the stage's switch) plays the run again in it.
 */
type Format = "ai-sdk" | "ag-ui" | "a2a";
const ask: UIMessage = { id: "u1", role: "user", parts: [{ type: "text", text: "Fix the failing GitHub build" }] };
const reply = (parts: UIMessage["parts"]): UIMessage[] => [ask, { id: "a1", role: "assistant", parts }];
const reading = { type: "tool-read_log", toolCallId: "t1", state: "output-available", output: "3 failures" } as const;
const push = (state: "approval-requested" | "approval-responded") => ({ type: "tool-git_push", toolCallId: "t2", state, approval: { id: "ap1", approved: state === "approval-responded" || undefined } }) as const;

/* each beat of the run, as each format says it */
const BEATS: { present: string; past: string; outcome?: string; ai: { status: string; parts: UIMessage["parts"] }; agUi: string | null; a2a: string }[] = [
  { present: "Fixing the GitHub build", past: "Queued behind one run", ai: { status: "submitted", parts: [] }, agUi: null, a2a: "submitted" },
  { present: "Reading the failing job's log", past: "Read the failing job's log", ai: { status: "streaming", parts: [{ ...reading, state: "input-available" }] }, agUi: "RUN_STARTED", a2a: "working" },
  { present: "Pushing the fix to main", past: "Asked to push the fix to main", ai: { status: "streaming", parts: [reading, push("approval-requested")] }, agUi: "RUN_FINISHED:interrupt", a2a: "input-required" },
  { present: "Pushing the fix to main", past: "Pushed the fix to main", ai: { status: "streaming", parts: [reading, push("approval-responded")] }, agUi: "STEP_STARTED", a2a: "working" },
  { present: "Fixing the GitHub build", past: "Fixed the GitHub build", outcome: "3 files", ai: { status: "ready", parts: [reading, push("approval-responded")] }, agUi: "RUN_FINISHED:success", a2a: "completed" },
];
const BEAT = 1600;
const TAKES = BEATS.map(() => BEAT);

/* the contract's one reader per format: whichever came in, a RunStatus comes out */
function statusOf(format: Format, b: (typeof BEATS)[number]): RunStatus {
  if (format === "ai-sdk") return runOf(reply(b.ai.parts), { status: b.ai.status })?.status ?? "queued";
  return runStatusFrom(format, format === "ag-ui" ? b.agUi : b.a2a) ?? "running";
}
const sent = (format: Format, b: (typeof BEATS)[number]) =>
  format === "ai-sdk" ? `status "${b.ai.status}"${b.ai.parts.some((p) => "state" in p && p.state === "approval-requested") ? ", a tool in approval-requested" : ""}` : format === "ag-ui" ? (b.agUi ?? "before RUN_STARTED") : `TaskState "${b.a2a}"`;

export default function StreamAdaptersDemo() {
  const knob = "ai-sdk" as Format;
  const [format, setFormat] = React.useState<Format>(knob);
  /* the knob's morph row sets the format too */
  const [knobWas, setKnobWas] = React.useState(knob);
  /* a new format plays the run again from its first beat, so the same pieces are seen reacting to it */
  const [replay, setReplay] = React.useState<number | null>(null);
  if (knob !== knobWas) {
    setKnobWas(knob);
    setFormat(knob);
    setReplay(0);
  }
  const less = useLessMotion();
  const root = React.useRef<HTMLDivElement>(null);
  const play = useSelfPlay(root, { beats: TAKES, off: less });
  React.useEffect(() => {
    if (replay === null || replay >= BEATS.length - 1) return;
    const id = window.setTimeout(() => setReplay((r) => (r ?? 0) + 1), BEAT);
    return () => window.clearTimeout(id);
  }, [replay]);
  const step = replay ?? (less ? BEATS.length - 1 : Math.max(0, play.step));
  const b = BEATS[step]!;
  const status = statusOf(format, b);
  const label = status === "running" ? "running" : status === "failed" ? "failed" : "done";
  return (
    <div ref={root} data-slot="stream-adapters-demo" onPointerDownCapture={play.handOver} onKeyDownCapture={play.handOver} onFocusCapture={play.handOver} className="flex w-[min(100%,var(--ns-width-md))] flex-col items-start gap-3">
      <Card inset className="w-full">
        <div className="flex flex-col gap-1.5">
          <div className="flex min-h-[var(--ns-row)] min-w-0 items-center gap-2.5 text-[length:var(--ns-text-body)]">
            <StatusGlyphRun state={status} label={b.present} />
            <LiveLabel state={label} present={b.present} past={b.past} outcome={b.outcome} />
            <span className="ms-auto shrink-0 text-[length:var(--ns-text-small)] text-[var(--ns-ink-3)]">{RUN_STATUS_WORDS[status]}</span>
          </div>
          <RunAnnouncer status={status} label={b.present} />
          <code className="inline-block max-w-full min-w-0 self-start truncate font-[family-name:var(--ns-font-mono)] text-[length:var(--ns-text-meta)] text-[var(--ns-ink-3)]">
            {`${sent(format, b)} → ${status}`}
          </code>
        </div>
      </Card>
    </div>
  );
}
```

This example also uses `card` (https://notchset.dev/components/card), `live-label` (https://notchset.dev/components/live-label), `status-glyph-run` (https://notchset.dev/components/status-glyph-run). Installing this item doesn't bring them; to paste the example as it is: `npx shadcn@latest add https://notchset.dev/r/stream-adapters.json https://notchset.dev/r/card.json https://notchset.dev/r/live-label.json https://notchset.dev/r/status-glyph-run.json`.

## Props

| Prop | Type | Default | What it does |
|---|---|---|---|
| `RunAnnouncer.status` | `RunStatus` |  | where the run stands |
| `RunAnnouncer.label` | `string` |  | what the run is doing, said with its phase: "Fixing the GitHub build" |
| `RunAnnouncer.labels` | `RunAnnouncerLabels` |  | the states' words and the sentence, over the English defaults ("Running" is said "Started") |

Full docs: https://notchset.dev/components/stream-adapters

## Customising
- Colours: every part reads the foundation's roles (`--ns-canvas`, `--ns-ink`, `--ns-line`, `--ns-signal` …), which read your shadcn tokens (`--background`, `--foreground`, `--border`, `--destructive` …), plus the optional `--success` and `--warning`. Retheme on `:root` or any container; never add Tailwind colour classes inside the component.
- Dark mode follows the `.dark` class or `data-theme="dark"` on an ancestor (the shadcn and next-themes conventions).
- Update later: Commit or stash local changes first (or copy the files), so the update can be undone. Read https://notchset.dev/r/changelog.json for the new versions: a major version, an entry marked breaking or a merge says what to change. Then re-run the install with `--overwrite`, on a branch. It replaces the component's files, the shared helper files they import, and the item's CSS rules in the global stylesheet, so review the whole diff (components, shared files, CSS), re-apply your own edits, and run the app's typecheck, tests and build.

## Keyboard

| Keys | Action |
|---|---|
| Tab | the format switch on its page; the contract itself draws nothing |

## Performance

- Types and a lookup table; one pure function per reading.
- No dependencies, no network.

## Responsive

- no UI, no network, no clock: now comes in
- any spelling of a format's word (TASK_STATE_INPUT_REQUIRED, input-required)

## Motion inventory

| Interaction | What moves |
|---|---|
| none of its own: the pieces it feeds move | none. Reduced motion: none. |

## Accessibility contract (preserve when editing)
- Its one element, RunAnnouncer, is the run's polite live region: it says each change of phase once ("Waiting on you: Fixing the GitHub build"), never a tick, and nothing for a run that arrived settled.
- The pieces it feeds read the same eight states, each its own shape and word.

## Install

```bash
# npm
npx shadcn@latest add https://notchset.dev/r/stream-adapters.json
# pnpm
pnpm dlx shadcn@latest add https://notchset.dev/r/stream-adapters.json
# yarn
yarn dlx shadcn@latest add https://notchset.dev/r/stream-adapters.json
# bun
bunx --bun shadcn@latest add https://notchset.dev/r/stream-adapters.json
```

Or add the `@notchset` registry to components.json and run `npx shadcn@latest add @notchset/stream-adapters`. Every components.json style gets the same files.

### Manual

1. Install the packages: none beyond `react` and `react-dom`.
2. Copy `components/ui/notchset/stream-adapters.tsx`, `lib/notchset/ui-message.ts`, `lib/notchset/words.ts` from https://notchset.dev/r/stream-adapters.json (each file's `content`, at its `target`), keeping the `@/` path alias of your tsconfig.
3. Add what it builds on: shadcn `utils` (cn), `notchset-foundation`.

## Continue the workflow

- [Change set](https://notchset.dev/components/change-set)
- [Checkpoint rail](https://notchset.dev/components/checkpoint-rail)
- [Message](https://notchset.dev/components/message)

## Source

### components/ui/notchset/stream-adapters.tsx

```tsx
// Notchset stream-adapters 1.0.0 · https://notchset.dev/changelog
"use client";
import * as React from "react";
import { fill } from "@/lib/notchset/words";
import { toolOf, type ToolPart, type ToolState, type UIMessage, type UIMessagePart } from "@/lib/notchset/ui-message";

/*
 * Stream adapters: the install contract as code. Every agentic piece takes plain data as props and reports what the
 * person did by callbacks; this file names that data once. The message and its parts are the AI SDK's UIMessage
 * verbatim (ui-message.ts, re-exported here), so a stream already on the AI SDK maps nothing; the shapes the SDK
 * leaves open (a run, a plan, an approval, a question, a cost, a change, a checkpoint) are ours, carried as data-*
 * parts. A run is in one of eight states (RunStatus), and nothing else; a tool call keeps the SDK's seven states,
 * read as six words (preparing, running, asking, done, failed, denied). Each stream format's own names for where a
 * run stands map onto RunStatus through one table (RUN_STATUS_FROM), read by one pure function. Nothing here draws,
 * fetches, imports a provider SDK or keeps a clock: `now` comes in. Its one element is RunAnnouncer, the polite
 * region a run's host says its phases in, once each (started, waiting on you, done, failed, stopped), never its ticks.
 *
 *   runStatusFrom("a2a", task.status.state)          "input-required" → "waiting"
 *   runStatusFrom("ag-ui", "RUN_FINISHED:interrupt")  → "waiting"
 *   mcp.toneFromHints(tool.annotations)              { readOnlyHint: true } → "read"
 *   runOf(messages, { status })                       the run the last reply carries, waiting while a gate is open
 *   <RunAnnouncer status={run.status} label={run.title} />
 */
export * from "@/lib/notchset/ui-message";

/* ---------- a run ---------- */

/** Where a run stands: the one vocabulary every agentic piece reads (LANGUAGE "Agents"). */
export type RunStatus = "queued" | "running" | "waiting" | "paused" | "done" | "failed" | "stopped" | "stale";
export const RUN_STATUSES: readonly RunStatus[] = ["queued", "running", "waiting", "paused", "done", "failed", "stopped", "stale"];
/** Each state's words, over which a host passes its own; stopped is something a person did, never a failure. */
export const RUN_STATUS_WORDS: Readonly<Record<RunStatus, string>> = {
  queued: "Queued",
  running: "Running",
  waiting: "Waiting on you",
  paused: "Paused",
  done: "Done",
  failed: "Failed",
  stopped: "Stopped",
  stale: "Not answering",
};
/** A run that has ended: nothing more will happen without a person. */
export const runEnded = (s: RunStatus) => s === "done" || s === "failed" || s === "stopped";

/** A reply's life, as Message reads it. */
export type ReplyStatus = "submitted" | "streaming" | "done" | "stopped" | "error";

/** Who does the work: an agent, a subagent it handed a part to, or a person. */
export type Actor = { id: string; name: string; kind: "agent" | "subagent" | "person"; mark?: React.ReactNode };

export type PlanStepStatus = "pending" | "active" | "done" | "failed" | "skipped";
export type PlanStep = { id: string; title: string; detail?: string | undefined; by?: "agent" | "person" | undefined; status: PlanStepStatus };
/** A plan (data-plan): drafted, approved, then worked step by step. */
export type Plan = { id: string; state: "draft" | "approved" | "running" | "paused" | "done"; startsAt?: number | undefined; steps: PlanStep[] };

/** What a run spent (the AI SDK's usage keys), plus credits, money and a rolling window. */
export type Cost = {
  inputTokens?: number | undefined;
  outputTokens?: number | undefined;
  reasoningTokens?: number | undefined;
  cachedInputTokens?: number | undefined;
  credits?: number | undefined;
  amount?: { value: number; currency: string } | undefined;
  window?: { label: string; used: number; limit: number; resetsAt: number } | undefined;
};

/** A proposed change to one text or file, as hunks a person keeps or undoes. */
export type ChangeHunk = { id: string; before: string; after: string; status: "pending" | "kept" | "undone" };
export type Change = { id: string; target: string; kind: "added" | "edited" | "removed"; actor: Actor; hunks: ChangeHunk[] };
/** A point a run can be rewound to: its content, its chat, or both. */
export type Checkpoint = { id: string; at: number; label: string; scopes: ("content" | "chat")[]; changes: number };

/** One agent's job (data-run), top level or a subagent's; any field may arrive late or never. */
export type Run = {
  id: string;
  title: string;
  status: RunStatus;
  actor: Actor;
  startedAt?: number | undefined;
  endedAt?: number | undefined;
  /** time spent paused, left out of the clock */
  pausedMs?: number | undefined;
  /** the last event's time, for stale */
  lastActivityAt?: number | undefined;
  waitingOn?: { kind: "approval" | "input" | "auth"; id: string; label: string } | undefined;
  plan?: Plan | undefined;
  children?: Run[] | undefined;
  cost?: Cost | undefined;
  outcome?: { summary: string; changes?: Change[] | undefined; error?: { message: string; stepId?: string | undefined; retryable: boolean } | undefined } | undefined;
};

/* ---------- a tool call ---------- */

/** How a tool's call is read: the SDK's seven states in six words. */
export type ToolDisplay = "preparing" | "running" | "asking" | "done" | "failed" | "denied";
export const TOOL_DISPLAY: Readonly<Record<ToolState, ToolDisplay>> = {
  "input-streaming": "preparing",
  "input-available": "running",
  "approval-requested": "asking",
  "approval-responded": "running",
  "output-available": "done",
  "output-error": "failed",
  "output-denied": "denied",
};
export const TOOL_DISPLAY_WORDS: Readonly<Record<ToolDisplay, string>> = {
  preparing: "Preparing",
  running: "Running",
  asking: "Asking",
  done: "Done",
  failed: "Failed",
  denied: "Denied",
};
/** A call's display state; a preliminary output (progress the tool streams) is still running. */
export const toolDisplayOf = (p: Pick<ToolPart, "state" | "preliminary">): ToolDisplay => (p.state === "output-available" && p.preliminary ? "running" : TOOL_DISPLAY[p.state]);

/** What a call does to the world: reads, changes ours, destroys, or reaches outside the app. */
export type ToolTone = "read" | "change" | "destructive" | "outside";
/** How a host names one tool (passed once, by tool name): its words in each tense, its mark and its tone. */
export type ToolLook = { running: string; done: (output: unknown) => string; failed?: string | undefined; mark?: React.ReactNode; tone?: ToolTone | undefined };

/* ---------- the gate and the question ---------- */

export type ApprovalScope = "once" | "session" | "always";
/** An approval: from a tool part's approval, or data-approval for a step that is not a tool. */
export type Approval = { id: string; toolCallId?: string | undefined; title: string; effect: string[]; untouched?: string[] | undefined; tone: ToolTone | undefined; scopes: ApprovalScope[]; expiresAt?: number | undefined };
export type ApprovalAnswer = { approved: boolean; scope?: ApprovalScope | undefined; reason?: string | undefined };

/** The part of JSON Schema a question's form uses: flat fields of plain types. */
export type JsonSchemaSubset = {
  type: "object";
  properties: Record<string, { type: "string" | "number" | "integer" | "boolean"; title?: string | undefined; description?: string | undefined; enum?: string[] | undefined; default?: unknown }>;
  required?: string[] | undefined;
};
/** A question (data-question; MCP elicitation, A2A input or auth required). */
export type Question = { id: string; message: string; mode: "choice" | "form" | "link"; options?: { value: string; label: string; detail?: string | undefined }[] | undefined; schema?: JsonSchemaSubset | undefined; url?: string | undefined };
export type QuestionAnswer = { action: "accept" | "decline" | "cancel"; values?: Record<string, unknown> | undefined };

/** A source's excerpt and whether the person may open it (data-source-extra, by sourceId): no access, no words. */
export type SourceExtra = { excerpt?: string | undefined; access?: "open" | "no-access" | undefined };

/** The metadata a reply carries (UIMessage's metadata). */
export type ReplyMeta = { status?: ReplyStatus | undefined; model?: string | undefined; startedAt?: number | undefined; finishedAt?: number | undefined; usage?: Cost | undefined };

/* ---------- each format's names for where a run stands ---------- */

export type StreamFormat = "ai-sdk" | "ag-ui" | "a2a" | "mcp" | "openai-agents" | "linear";
/**
 * The protocol table, as data: each format's word for where a run stands, and the RunStatus it is. AG-UI's
 * RUN_FINISHED carries its outcome after a colon ("RUN_FINISHED:interrupt"); OpenAI Agents' are its stream event
 * types and the run result's fields. Paused is always the host's own (no format sends it); stale is time
 * (staleAfter). Words are matched in any case, with any of _ - or space between them.
 */
export const RUN_STATUS_FROM: Readonly<Record<StreamFormat, Readonly<Record<string, RunStatus>>>> = {
  "ai-sdk": { submitted: "queued", streaming: "running", ready: "done", error: "failed", stopped: "stopped" },
  "ag-ui": {
    "": "queued",
    RUN_STARTED: "running",
    STEP_STARTED: "running",
    STEP_FINISHED: "running",
    "RUN_FINISHED:interrupt": "waiting",
    RUN_FINISHED: "done",
    "RUN_FINISHED:success": "done",
    "RUN_FINISHED:cancelled": "stopped",
    RUN_ERROR: "failed",
  },
  a2a: { submitted: "queued", working: "running", "input-required": "waiting", "auth-required": "waiting", completed: "done", failed: "failed", rejected: "failed", canceled: "stopped", cancelled: "stopped" },
  mcp: { working: "running", input_required: "waiting", completed: "done", failed: "failed", cancelled: "stopped" },
  "openai-agents": { run_item_stream_event: "running", raw_model_stream_event: "running", agent_updated_stream_event: "running", interruptions: "waiting", final_output: "done", error: "failed", abort: "stopped" },
  linear: { pending: "queued", active: "running", awaitingInput: "waiting", complete: "done", error: "failed", stale: "stale" },
};

/* one spelling for a format's word: lower case, a gRPC enum's prefix dropped, any separator a hyphen */
const key = (v: string) =>
  v
    .replace(/([a-z])([A-Z])/g, "$1-$2")
    .toLowerCase()
    .replace(/[\s_-]+/g, "-")
    .replace(/^task-state-/, "");
const KEYED = Object.fromEntries(Object.entries(RUN_STATUS_FROM).map(([f, t]) => [f, new Map(Object.entries(t).map(([w, s]) => [key(w), s]))])) as Record<StreamFormat, Map<string, RunStatus>>;

/**
 * Where a run stands, from a format's own word for it: undefined for a word the table doesn't know (an event that
 * says nothing about the run). AG-UI before RUN_STARTED is queued: pass nothing.
 */
export function runStatusFrom(format: StreamFormat, value: string | null | undefined): RunStatus | undefined {
  return KEYED[format].get(key(value ?? ""));
}

/** A run that heard nothing for the host's limit is stale; one that ended, paused or waits on a person is not. */
export function staleAfter(status: RunStatus, at: { lastActivityAt?: number | undefined; now: number; limitMs: number }): RunStatus {
  const quiet = at.lastActivityAt !== undefined && at.now - at.lastActivityAt > at.limitMs;
  return quiet && (status === "running" || status === "queued") ? "stale" : status;
}

/* ---------- MCP ---------- */

/** MCP's tool annotations, as a server sends them. */
export type McpToolAnnotations = { title?: string | undefined; readOnlyHint?: boolean | undefined; destructiveHint?: boolean | undefined; idempotentHint?: boolean | undefined; openWorldHint?: boolean | undefined };
export const mcp = {
  /** A tool's tone from its hints: read only reads, destructive destroys, open world reaches outside, else it changes ours. */
  toneFromHints(a: McpToolAnnotations | null | undefined): ToolTone {
    if (a?.readOnlyHint) return "read";
    if (a?.destructiveHint) return "destructive";
    if (a?.openWorldHint) return "outside";
    return "change";
  },
};

/* ---------- the run an AI SDK stream carries ---------- */

const dataOf = <T,>(parts: UIMessagePart[], type: string): T | undefined => {
  let last: T | undefined;
  for (const p of parts) if (p.type === type && "data" in p) last = p.data as T;
  return last;
};

/**
 * The run the last assistant message carries: its data-run (the latest one), its data-plan, and waiting while a
 * tool asks for approval or a data-question is open (data-question-answer closes it, by id). Without a data-run the
 * status comes from the chat's own (`status`, the AI SDK's), or stopped when the host stopped it. Null with no reply.
 */
export function runOf(messages: readonly UIMessage[], chat: { status?: string | undefined; stopped?: boolean | undefined; actor?: Actor | undefined } = {}): Run | null {
  const last = [...messages].reverse().find((m) => m.role === "assistant");
  if (!last) return null;
  const given = dataOf<Partial<Run>>(last.parts, "data-run");
  const plan = dataOf<Plan>(last.parts, "data-plan") ?? given?.plan;
  /* a stop is the host's to say; an ending the run itself sent stands; otherwise the chat's own status */
  const status: RunStatus = chat.stopped ? "stopped" : given?.status && runEnded(given.status) ? given.status : (runStatusFrom("ai-sdk", chat.status) ?? given?.status ?? "running");
  const run: Run = { ...given, id: given?.id ?? last.id, title: given?.title ?? "", actor: given?.actor ?? chat.actor ?? { id: "assistant", name: "Assistant", kind: "agent" }, status, ...(plan ? { plan } : {}) };
  if (runEnded(status)) return run;
  const asking = last.parts.map(toolOf).find((t) => t?.state === "approval-requested");
  if (asking) return { ...run, status: "waiting", waitingOn: { kind: "approval", id: asking.approval?.id ?? asking.toolCallId, label: asking.type.slice(5) } };
  const answered = new Set(last.parts.filter((p) => p.type === "data-question-answer" && "data" in p).map((p) => (p as { data: { id?: string } }).data.id));
  const open = last.parts.find((p) => p.type === "data-question" && "data" in p && !answered.has((p.data as Question).id));
  if (open && "data" in open) {
    const q = open.data as Question;
    return { ...run, status: "waiting", waitingOn: { kind: "input", id: q.id, label: q.message } };
  }
  return run;
}

/* ---------- saying a run's phases ---------- */

/** What the region says as a run changes phase: each state's words and the sentence ({state} and {name} filled in). */
export type RunAnnouncerLabels = Partial<Record<RunStatus, string>> & { read?: string | undefined };
type RunAnnouncerProps = {
  /** where the run stands */
  status: RunStatus;
  /** what the run is doing, said with its phase: "Fixing the GitHub build" */
  label: string;
  /** the states' words and the sentence, over the English defaults ("Running" is said "Started") */
  labels?: RunAnnouncerLabels | undefined;
};
const SAID: Readonly<Record<RunStatus, string>> & { read: string } = { ...RUN_STATUS_WORDS, running: "Started", read: "{state}: {name}" };

/**
 * One polite live region for a run: it says each change of phase once ("Waiting on you: Fixing the GitHub build"),
 * nothing for a run that arrived settled, and never a tick (a step's words changing while it runs). Unseen.
 */
export function RunAnnouncer({ status, label, labels }: RunAnnouncerProps) {
  const [said, setSaid] = React.useState({ status, text: "" });
  if (status !== said.status) {
    const L = { ...SAID, ...labels };
    setSaid({ status, text: fill(L.read ?? SAID.read, { state: L[status] ?? SAID[status], name: label }) });
  }
  return (
    <span data-slot="stream-adapters" role="status" aria-live="polite" className="sr-only">
      {said.text}
    </span>
  );
}
```

### lib/notchset/ui-message.ts

```tsx
// Notchset stream-adapters 1.0.0 · https://notchset.dev/changelog
/*
 * The assistant's shared words and shapes (installs to lib/notchset/ui-message.ts with any piece that reads it).
 *
 * Messages are shaped like the AI SDK's UIMessage (an id, a role and parts: text, reasoning, tool-*, dynamic-tool,
 * source-url, source-document, file, step-start, data-*), defined here so a piece needs no runtime dependency: a buyer on the AI SDK passes its messages
 * straight in. The figures every piece shows (what answered, how much of a window is used, when it resets) are
 * worked out here, once, so the usage meter, the composer's line and the plan card can never read two ways
 * ("One name, one calculation").
 */
import { DEFAULT_LOCALE } from "@/lib/notchset/words";

/* ---------- messages ---------- */

export type TextPart = { type: "text"; text: string; state?: "streaming" | "done" | undefined };
export type ReasoningPart = { type: "reasoning"; text: string; state?: "streaming" | "done" | undefined; durationMs?: number | undefined };
/** A tool call, as the AI SDK names its states, approvals included. */
export type ToolState = "input-streaming" | "input-available" | "approval-requested" | "approval-responded" | "output-available" | "output-error" | "output-denied";
export type ToolPart = {
  type: `tool-${string}`;
  toolCallId: string;
  state: ToolState;
  input?: unknown;
  output?: unknown;
  errorText?: string | undefined;
  /** an output a later one replaces (progress) */
  preliminary?: boolean | undefined;
  approval?: { id: string; approved?: boolean | undefined; reason?: string | undefined } | undefined;
};
export type SourceUrlPart = { type: "source-url"; sourceId: string; url: string; title?: string | undefined };
export type FilePart = { type: "file"; mediaType: string; url: string; filename?: string | undefined };
/** A tool the host registered at run time (the AI SDK's dynamic tool): named by `toolName`, not by its type. */
export type DynamicToolPart = {
  type: "dynamic-tool";
  toolName: string;
  toolCallId: string;
  state: ToolState;
  input?: unknown;
  output?: unknown;
  errorText?: string | undefined;
  title?: string | undefined;
  preliminary?: boolean | undefined;
  approval?: { id: string; approved?: boolean | undefined; reason?: string | undefined } | undefined;
};
export type SourceDocumentPart = { type: "source-document"; sourceId: string; mediaType: string; title: string; filename?: string | undefined };
/** Where one model step began in a multi-step reply: a boundary the SDK writes, nothing to draw. */
export type StepStartPart = { type: "step-start" };
/** Provider-specific content and files the model reasoned with: carried through, not drawn. */
export type CustomPart = { type: "custom"; kind: `${string}.${string}` };
export type ReasoningFilePart = { type: "reasoning-file"; mediaType: string; url: string };
export type DataPart = { type: `data-${string}`; id?: string | undefined; data: unknown };
export type UIMessagePart = TextPart | ReasoningPart | ToolPart | DynamicToolPart | SourceUrlPart | SourceDocumentPart | FilePart | ReasoningFilePart | CustomPart | StepStartPart | DataPart;

export type UIMessage<M = unknown> = { id: string; role: "system" | "user" | "assistant"; parts: UIMessagePart[]; metadata?: M | undefined };

export const isToolPart = (p: UIMessagePart): p is ToolPart => p.type.startsWith("tool-");
/** A tool call as one shape: a dynamic tool becomes `tool-<its name>`; anything else that is not a tool is null. */
export const toolOf = (p: UIMessagePart): ToolPart | null => (isToolPart(p) ? p : p.type === "dynamic-tool" ? { ...p, type: `tool-${p.toolName}` } : null);
export const textOf = (m: Pick<UIMessage, "parts">) =>
  m.parts
    .filter((p): p is TextPart => p.type === "text")
    .map((p) => p.text)
    .join("");

/* ---------- what answered ---------- */

/** The purpose-named choices a picker offers (never "Auto"); each maps to a model and an effort in the adapter. */
export type ModelPurpose = "fast" | "balanced" | "deep" | "long";
export type ModelLine = {
  /** the purpose the person reads: "Balanced" */
  purpose: string;
  /** the model's own name, a second line: "Claude Sonnet 5.5" */
  name: string;
  effort?: "low" | "medium" | "high" | undefined;
  /** how long it thought before answering, when it did */
  thoughtForMs?: number | undefined;
  /** the purpose that was asked for, when another one answered ("Deep thinking was busy") */
  asked?: string | undefined;
  /** why another answered */
  fallbackReason?: string | undefined;
};

/** "14 s", "1 min 5 s": a duration a person reads. */
export function seconds(ms: number) {
  const s = Math.max(1, Math.round(ms / 1000));
  return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min${s % 60 ? ` ${s % 60} s` : ""}`;
}

/** The model line under every reply: "Balanced · thought for 9 s", or what answered in another's place. */
export function modelLineWords(m: ModelLine) {
  const lead = m.asked && m.asked !== m.purpose ? `Answered by ${m.purpose}; ${m.asked} ${m.fallbackReason ?? "wasn't available"}` : m.purpose;
  return m.thoughtForMs ? `${lead} · thought for ${seconds(m.thoughtForMs)}` : lead;
}

/* ---------- usage ---------- */

/** What is used of each window, as a share from 0 to 1, and when each resets. Null when nothing measures it. */
export type Usage = {
  window: number;
  week: number;
  windowResetsAt: string;
  weekResetsAt: string;
  /** what this window's use was spent on, each a share of the window (0 to 1): "Chat" 0.44, "Code" 0.12 */
  windowParts?: readonly { label: string; share: number }[] | undefined;
};

/** "4:10 pm" in the reader's own clock. */
export function clockTime(iso: string, locale?: string) {
  return new Date(iso).toLocaleTimeString(locale ?? DEFAULT_LOCALE, { hour: "numeric", minute: "2-digit" }).replace(/\s?([AP])M$/i, (_, a: string) => ` ${a.toLowerCase()}m`);
}

/** "today at 4:10 pm", "Monday", or a date further out. */
export function resetWords(iso: string, now: Date, locale?: string) {
  const at = new Date(iso);
  const days = Math.round((new Date(at.getFullYear(), at.getMonth(), at.getDate()).getTime() - new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()) / 864e5);
  if (days <= 0) return clockTime(iso, locale);
  if (days === 1) return `tomorrow ${clockTime(iso, locale)}`;
  if (days < 7) return at.toLocaleDateString(locale ?? DEFAULT_LOCALE, { weekday: "long" });
  return at.toLocaleDateString(locale ?? DEFAULT_LOCALE, { month: "short", day: "numeric" });
}

/** The reset in a sentence: "at 4:10 pm", "tomorrow at 4:10 pm", "on Monday". */
export function resetPhrase(iso: string, now: Date, locale?: string) {
  const w = resetWords(iso, now, locale);
  return /^\d/.test(w) ? `at ${w}` : w.startsWith("tomorrow ") ? `tomorrow at ${w.slice(9)}` : `on ${w}`;
}

/** Where a figure stands against its limit: the same edges the Meter uses (75% warns, 100% is full). */
export type UsageLevel = "ok" | "near" | "full";

/**
 * Every usage figure the pieces show, from one calculation: each window's share used (a whole percent, rounded
 * down so "100%" only ever means full), its words, its reset, whether to warn (under 20% of the window left) and
 * whether the window is spent. Whichever window runs out first is the one that limits.
 */
export function usageFigures(u: Usage, now: Date, locale?: string) {
  const pct = (x: number) => Math.max(0, Math.min(100, Math.floor(x * 100)));
  const window = pct(u.window), week = pct(u.week);
  const level = (p: number): UsageLevel => (p >= 100 ? "full" : p >= 75 ? "near" : "ok");
  const windowReset = resetWords(u.windowResetsAt, now, locale), weekReset = resetWords(u.weekResetsAt, now, locale);
  const limiting = week >= 100 || (week > window && week >= 80) ? "week" : "window";
  const left = 100 - (limiting === "week" ? week : window);
  const reset = limiting === "week" ? weekReset : windowReset;
  return {
    window,
    week,
    windowLevel: level(window),
    weekLevel: level(week),
    windowLine: `${window}% used · resets ${windowReset}`,
    weekLine: `${week}% of this week · resets ${weekReset}`,
    limiting,
    left,
    reset,
    /** the reset in a sentence ("at 4:10 pm", "on Monday") */
    resetPhrase: resetPhrase(limiting === "week" ? u.weekResetsAt : u.windowResetsAt, now, locale),
    resetsAt: limiting === "week" ? u.weekResetsAt : u.windowResetsAt,
    /** under 20% left: the composer shows its quiet line */
    low: left < 20 && left > 0,
    atLimit: left <= 0,
    /** the composer's line, only when low or spent */
    composerLine: left <= 0 ? `${limiting === "week" ? "You've reached this week's limit" : "You've reached your limit for now"} · resets ${reset}` : `${left}% left${limiting === "week" ? " this week" : ""} · resets ${reset}`,
  };
}

/** How full a chat is against what the model can read at once, in words with no token talk (DEPTH 93). */
export function contextWords(share: number) {
  const p = Math.max(0, Math.min(100, Math.floor(share * 100)));
  if (p >= 90) return { pct: p, line: "This chat is very long: early messages may be left out. Start a new chat to keep answers sharp." };
  if (p >= 60) return { pct: p, line: "This chat is getting long: answers may miss early details." };
  return { pct: p, line: "Room to keep going in this chat." };
}
```

### lib/notchset/words.ts

```tsx
// Notchset stream-adapters 1.0.0 · https://notchset.dev/changelog
import * as React from "react";

/* Built-in words and figures, one way for every piece. */

/** The locale a piece writes in when the app passes none: English at launch, the same on the server and in the browser. */
export const DEFAULT_LOCALE = "en-US";

/** A count's words by the locale's plural rule: `other` always, any of the locale's other forms as it needs them. */
export type Plural = { other: string } & Partial<Record<Intl.LDMLPluralRule, string>>;

/** A whole number (or any figure) in the locale's digits and grouping. */
export function formatCount(n: number, locale: string = DEFAULT_LOCALE, options?: Intl.NumberFormatOptions): string {
  return new Intl.NumberFormat(locale, options).format(n);
}

/** A sentence with its `{name}` blanks filled; a blank with no value is left as written. */
export function fill(sentence: string, vars: Readonly<Record<string, string | number>>): string {
  return sentence.replace(/\{(\w+)\}/g, (blank, name: string) => (name in vars ? String(vars[name]) : blank));
}

/** The same, where a blank is a node (a name in ink): the sentence's own words stay in order around it. */
export function fillNodes(sentence: string, vars: Readonly<Record<string, React.ReactNode>>): React.ReactNode {
  return sentence.split(/(\{\w+\})/).map((part, i) => {
    const name = /^\{(\w+)\}$/.exec(part)?.[1];
    return name !== undefined && name in vars ? React.createElement(React.Fragment, { key: i }, vars[name]) : part;
  });
}

/** A count's sentence by the locale's plural rule, `{count}` written in the locale ("1 message", "4 messages"). */
export function plural(locale: string | undefined, n: number, forms: Plural, vars: Readonly<Record<string, string | number>> = {}): string {
  const loc = locale ?? DEFAULT_LOCALE;
  const rule = new Intl.PluralRules(loc).select(n);
  return fill(forms[rule] ?? forms.other, { count: formatCount(n, loc), ...vars });
}
```

The foundation (the tokens listed above, keyframes and motion levels) installs once with the first component; its CSS is public at https://notchset.dev/r/notchset-foundation.json.
