{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "terminal-web",
  "title": "Terminal (Web Components)",
  "description": "A command and its output in ANSI colors, following the end as it streams, with its approval, exit code and duration.",
  "dependencies": [
    "@kind-ui/agent-ui@0.9.0",
    "@ui-sdk/core@0.1.0-beta.17",
    "@ui-sdk/web@0.1.0-beta.17"
  ],
  "registryDependencies": [
    "@kind-ui/agent-ui-setup",
    "@kind-ui/confirmation-web"
  ],
  "files": [
    {
      "path": "packages/agent-ui/src/web/terminal.ts",
      "content": "import {\n  type AnsiLine,\n  type StepOpenChangeReason,\n  type TerminalApi,\n  type TerminalCopyReason,\n  type TerminalOptions,\n  type TerminalState,\n  terminalPrimitive,\n} from \"@kind-ui/agent-ui/core\";\nimport { createParts, wrappedButton } from \"@ui-sdk/web\";\nimport type { AttributeProperties, UiChangeEvent, UiElement } from \"@ui-sdk/web/events\";\nimport {\n  APPROVAL_KINDS,\n  type ApprovalAttributes,\n  approvalOptions,\n  defineConfirmation,\n  type KindConfirmationElement,\n  type KindConfirmationEvents,\n  writeApproval,\n} from \"./confirmation\";\n\nconst DEFAULT_PARTS = `<kind-terminal-trigger><button><kind-terminal-icon></kind-terminal-icon><kind-terminal-title></kind-terminal-title><kind-terminal-exit></kind-terminal-exit><kind-terminal-meta></kind-terminal-meta></button></kind-terminal-trigger><kind-terminal-approval></kind-terminal-approval><kind-terminal-content><div data-terminal-screen data-kind-code><div data-terminal-header><kind-terminal-command></kind-terminal-command><kind-terminal-copy><button></button></kind-terminal-copy></div><kind-terminal-viewport><kind-terminal-output></kind-terminal-output></kind-terminal-viewport><kind-terminal-jump><button hidden>Jump to latest</button></kind-terminal-jump></div></kind-terminal-content>`;\n\n// Parts this element wrote text into. A part someone wrote into keeps what they wrote, as React's children do. Kept\n// across instances, because UI SDK rebuilds one when the element returns to the page.\nconst owned = new WeakSet<Element>();\n\nconst fill = (part: Element | null, text: string) => {\n  if (!part || !(owned.has(part) || !part.textContent)) return;\n  owned.add(part);\n  if (part.textContent !== text) part.textContent = text;\n};\n\n// The pieces each title was last drawn from, odd ones code.\nconst titles = new WeakMap<Element, readonly string[]>();\n\nconst fillTitle = (part: Element | null, spans: readonly string[]) => {\n  if (!part || !(owned.has(part) || !part.textContent) || titles.get(part) === spans) return;\n  owned.add(part);\n  titles.set(part, spans);\n  part.replaceChildren(\n    ...spans.map((piece, index) => {\n      if (!(index % 2)) return piece;\n      const code = part.ownerDocument.createElement(\"code\");\n      code.textContent = piece;\n      return code;\n    }),\n  );\n};\n\n// The line each element was last drawn from, so a redraw writes only lines that changed.\nconst drawn = new WeakMap<Element, AnsiLine>();\n\nconst drawLine = (el: Element, line: AnsiLine) => {\n  if (drawn.get(el) === line) return;\n  drawn.set(el, line);\n  el.replaceChildren(\n    ...line.spans.map((span) => {\n      const run = el.ownerDocument.createElement(\"span\");\n      run.textContent = span.text;\n      if (span.fg) run.style.color = span.fg;\n      if (span.bg) run.style.backgroundColor = span.bg;\n      for (const name of [\"bold\", \"dim\", \"italic\", \"underline\", \"strike\"] as const) {\n        if (span[name]) run.setAttribute(`data-${name}`, \"\");\n      }\n      return run;\n    }),\n  );\n};\n\n// Each output's line elements by index, so drawing reads no attributes.\nconst lineElements = new WeakMap<Element, Map<number, Element>>();\n\n/** Draws a `kind-terminal-line` for each line in view, reusing each index's element. */\nconst drawLines = (output: Element, state: TerminalState) => {\n  const existing = lineElements.get(output) ?? new Map<number, Element>();\n  const wanted = new Set(state.rows.map((row) => row.index));\n  // Lines that left go first, so the rest are already in order.\n  for (const [index, line] of existing) {\n    if (wanted.has(index)) continue;\n    line.remove();\n    existing.delete(index);\n  }\n  let previous: Element | null = null;\n  for (const row of state.rows) {\n    let line = existing.get(row.index);\n    if (!line) {\n      line = output.ownerDocument.createElement(\"kind-terminal-line\");\n      line.setAttribute(\"index\", String(row.index));\n      existing.set(row.index, line);\n    }\n    const shown = state.lines[row.index];\n    if (shown) drawLine(line, shown);\n    const before: Element | null = previous ? previous.nextElementSibling : output.firstElementChild;\n    if (line !== before) output.insertBefore(line, before);\n    previous = line;\n  }\n  lineElements.set(output, existing);\n};\n\n/**\n * `<kind-terminal>` fills in its parts when it has no children, and draws the lines in view into its\n * `kind-terminal-output`. Set `output` as a property and give it the whole output on each update. Copying fires\n * `terminalcopy`, with the output without escapes as `detail.value`. While `approval` is set (a property), an empty\n * `<kind-terminal-approval>` gets a `kind-confirmation`, which offers Deny with the `can-deny` attribute, Always allow\n * with `can-always-allow` and Run with `can-approve`, which fire `deny`, `alwaysallow` and `approve` on the terminal.\n */\nexport function defineTerminal(): void {\n  if (customElements.get(\"kind-terminal\")) return;\n  defineConfirmation();\n  createParts(terminalPrimitive, {\n    root: {\n      tag: \"kind-terminal\",\n      kinds: APPROVAL_KINDS,\n      // Without the attribute the callback is left out; with it, `@ui-sdk/web` fills it in with an event.\n      options: (el) => approvalOptions(el as KindTerminalElement),\n      state: {\n        open: {\n          get: (api) => api.isOpen(),\n          set: (api, open) => api.setOpen(!!open),\n        },\n      },\n      // A native `copy` event bubbles from the selection.\n      events: { onCopy: \"terminalcopy\" },\n      // `copy` is a getter, offered only with output, which a copied list of methods would freeze.\n      api: [\"isOpen\", \"setOpen\", \"expand\", \"collapse\", \"toggle\", \"scrollToEnd\"],\n      render: (el, instance) => {\n        if (!el.firstElementChild) el.innerHTML = DEFAULT_PARTS;\n        const api = instance.api as TerminalApi;\n        const draw = () => {\n          const state = instance.get() as TerminalState;\n          fillTitle(el.querySelector(\"kind-terminal-title\"), api.titleSpans(state));\n          if (state.exitCode) fill(el.querySelector(\"kind-terminal-exit\"), `Exit ${state.exitCode}`);\n          fill(el.querySelector(\"kind-terminal-meta\"), state.meta);\n          // Filled only once there's an approval, so a terminal without one holds no Confirmation.\n          const part = state.approval && el.querySelector(\"kind-terminal-approval\");\n          if (part) {\n            if (!part.firstElementChild) part.innerHTML = \"<kind-confirmation></kind-confirmation>\";\n            const confirmation = part.querySelector<KindConfirmationElement>(\":scope > kind-confirmation\");\n            if (confirmation) writeApproval(confirmation, api.approvalState(state));\n          }\n          fill(el.querySelector(\"kind-terminal-command\"), state.command);\n          const output = el.querySelector(\"kind-terminal-output\");\n          if (output) drawLines(output, state);\n        };\n        draw();\n        return instance.subscribe(draw);\n      },\n    },\n    trigger: { tag: \"kind-terminal-trigger\", target: wrappedButton, display: \"contents\" },\n    icon: \"kind-terminal-icon\",\n    title: \"kind-terminal-title\",\n    exit: \"kind-terminal-exit\",\n    meta: \"kind-terminal-meta\",\n    approval: \"kind-terminal-approval\",\n    content: \"kind-terminal-content\",\n    command: \"kind-terminal-command\",\n    copy: { tag: \"kind-terminal-copy\", target: wrappedButton, display: \"contents\" },\n    viewport: \"kind-terminal-viewport\",\n    output: \"kind-terminal-output\",\n    line: \"kind-terminal-line\",\n    jump: { tag: \"kind-terminal-jump\", target: wrappedButton, display: \"contents\" },\n  });\n}\n\nexport type KindTerminalEvents = {\n  openchange: UiChangeEvent<boolean, StepOpenChangeReason>;\n  terminalcopy: UiChangeEvent<string, TerminalCopyReason>;\n  approve: KindConfirmationEvents[\"approve\"];\n  deny: KindConfirmationEvents[\"deny\"];\n  alwaysallow: KindConfirmationEvents[\"alwaysallow\"];\n};\n\nexport interface KindTerminalElement\n  extends UiElement<KindTerminalEvents>,\n    ApprovalAttributes,\n    AttributeProperties<typeof terminalPrimitive, \"api\" | \"open\" | \"approval\"> {\n  open: boolean;\n  approval?: TerminalOptions[\"approval\"];\n  api: Pick<TerminalApi, \"isOpen\" | \"setOpen\" | \"expand\" | \"collapse\" | \"toggle\" | \"scrollToEnd\">;\n}\n\ndeclare global {\n  interface HTMLElementTagNameMap {\n    \"kind-terminal\": KindTerminalElement;\n    \"kind-terminal-trigger\": HTMLElement;\n    \"kind-terminal-icon\": HTMLElement;\n    \"kind-terminal-title\": HTMLElement;\n    \"kind-terminal-exit\": HTMLElement;\n    \"kind-terminal-meta\": HTMLElement;\n    \"kind-terminal-approval\": HTMLElement;\n    \"kind-terminal-content\": HTMLElement;\n    \"kind-terminal-command\": HTMLElement;\n    \"kind-terminal-copy\": HTMLElement;\n    \"kind-terminal-viewport\": HTMLElement;\n    \"kind-terminal-output\": HTMLElement;\n    \"kind-terminal-line\": HTMLElement;\n    \"kind-terminal-jump\": HTMLElement;\n  }\n}\n",
      "type": "registry:ui",
      "target": "@ui/web/terminal.ts"
    }
  ],
  "meta": {
    "layer": "web"
  },
  "type": "registry:ui"
}
