Skip to content
Back to skills

Ui Integration

ASecurity

Wire agents into React, Vue, and Svelte frontends with streaming hooks, and set up server-side Next.js App Router or Express API routes using AgentStream.toSSE().

  • 33 stars
  • 0 votes
  • 0 copies
  • 2 views
  • Added October 11, 2026
ai-agentstypescriptrustshellreactvuenextjsnodeexpressawsapi

Works with

  • cursor
  • cli
  • api

Security analysis

A100/100

Scanned December 5, 2026

npx -y skills add tylerjrbuell/reactive-agents-ts --skill ui-integration --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Ui Integration?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Ui Integration
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/tylerjrbuell-ui-integration/badge)](https://www.skillsdirectory.com/skills/tylerjrbuell-ui-integration)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: ui-integration
description: Wire agents into React, Vue, and Svelte frontends with streaming hooks, and set up server-side Next.js App Router or Express API routes using AgentStream.toSSE().
compatibility: Reactive Agents TypeScript projects using @reactive-agents/*
metadata:
  author: reactive-agents
  version: "2.0"
  tier: "capability"
---

# UI Integration

## Agent objective

Produce a working server-side API route using `AgentStream.toSSE()` and a client-side component using the appropriate framework hook, connected end-to-end.

## When to load this skill

- Building a chat UI or streaming text interface in React, Vue, or Svelte
- Wiring an agent into a Next.js App Router API route
- Connecting an agent to an Express or Elysia HTTP server
- Needing real-time token-by-token streaming to the browser

## Implementation baseline

### Server — Next.js App Router

```ts
// app/api/agent/route.ts
import { ReactiveAgents, AgentStream } from "@reactive-agents/runtime";

export async function POST(req: Request) {
  const { prompt } = await req.json();
  const agent = await ReactiveAgents.create()
    .withProvider("anthropic")
    .withReasoning({ defaultStrategy: "adaptive", maxIterations: 10 })
    .withTools({ allowedTools: ["web-search", "checkpoint"] })
    .build();
  return AgentStream.toSSE(agent.runStream(prompt));
}
```

### Client — React

```tsx
import { useAgentStream } from "@reactive-agents/react";

function Chat() {
  const { text, status, error, run, cancel } = useAgentStream("/api/agent");
  return (
    <div>
      <button onClick={() => run("Explain quantum entanglement")} disabled={status === "streaming"}>
        Ask
      </button>
      {status === "streaming" && <button onClick={cancel}>Stop</button>}
      <p>{text}</p>
      {error && <p style={{ color: "red" }}>{error}</p>}
    </div>
  );
}
```

## Key patterns

### React hooks

```tsx
import { useAgentStream, useAgent } from "@reactive-agents/react";

// Streaming — token-by-token delivery
const {
  text,      // string — accumulated text so far
  events,    // AgentStreamEvent[] — all events received
  status,    // "idle" | "streaming" | "completed" | "error"
  error,     // string | null — error message
  output,    // string | null — final output (set on completion)
  run,       // (prompt: string, body?: Record<string, unknown>) => void — start the agent
  cancel,    // () => void — abort the stream
} = useAgentStream("/api/agent");

// One-shot — waits for full result
const {
  output: result, // string | null — final output
  loading,        // boolean
  error: failure, // string | null — error message
  run: ask,       // (prompt: string, body?: Record<string, unknown>) => Promise<string>
} = useAgent("/api/agent");
```

### Vue composables

```vue
<script setup lang="ts">
import { useAgentStream, useAgent } from "@reactive-agents/vue";

// Same return shape as React hooks
const { text, status, error, run, cancel } = useAgentStream("/api/agent");
const { output, loading, error: err, run: fetch } = useAgent("/api/agent");
</script>

<template>
  <button @click="run('Explain AI')">Ask</button>
  <p>{{ text }}</p>
</template>
```

Durable runs (from 0.20.1; needs Vue 3.2 or later). Same option names as the React hooks; state comes back as read-only refs:

```ts
import {
  useRun, useResumableRun, useInteractions, useTaskInbox, useRunCost, useRunSteps,
  decideApproval, respondToInteraction,
} from "@reactive-agents/vue";

// A resumable run. Options: endpoint, fetchImpl?, objectMode?, auto?: { prompt, body? }, attach?: { runId, cursor? }
const {
  state,     // Readonly<Ref<RunState>>: status, runId, text, output, lastSeq, pendingApproval, pendingInteraction, cost, error
  run,       // (prompt: string, body?: Record<string, unknown>) => void
  cancel,    // () => void: aborts the stream; the server-side run is not stopped
  reattach,  // (runId: string, cursor?: number) => void
} = useRun({ endpoint: "/api/agent" });
// state.value.status: "idle" | "streaming" | "awaiting-interaction" | "awaiting-approval" | "completed" | "error" | "cancelled"

// After a reload: reattach once mounted. Same return as useRun.
const resumed = useResumableRun({ endpoint: "/api/agent", runId: "run_123", cursor: 0 });

// Approval gate: send the decision, then reattach (the stream ended when the run paused).
const decide = async (decision: "approve" | "deny") => {
  const gate = state.value.pendingApproval; // { runId, gateId, toolName, args, subAgent? }
  if (!gate) return;
  const result = await decideApproval({ endpoint: "/api/approval", runId: gate.runId, gateId: gate.gateId, decision });
  if (result.success) reattach(gate.runId, state.value.lastSeq); // result: { success, output, error? }, never rejects
};

// Pending question (state.value.pendingInteraction): respond never rejects; pending and error are refs.
const { respond, pending, error } = useInteractions({ interactionEndpoint: "/api/interaction" });
// respond(runId, interactionId, value) => Promise<{ success: boolean; output: string }>
// Without the composable: respondToInteraction({ endpoint, runId, interactionId, value })

// The user's durable runs: refs runs (InboxRun[]: runId, task, status, updatedAt), loading, error; refresh().
const inbox = useTaskInbox({ endpoint: "/api/inbox", pollMs: 5000 });

// Read-only views; each takes the state ref, a getter or a plain RunState and returns a computed ref.
const cost = useRunCost(state);   // { tokens, usd }
const steps = useRunSteps(state); // StepEntry[]
```

`auto` and `attach` start after mount (a server render opens no stream); the stream is aborted when the component is unmounted. Full page: `/features/agentic-ui-vue-blocks/#durable-run-composables`.

### Svelte stores

```svelte
<script lang="ts">
  import { createAgentStream, createAgent } from "@reactive-agents/svelte";

  // Returns a Svelte readable store plus run() and cancel()
  const agent = createAgentStream("/api/agent");
  // $agent: AgentStreamState = { text, events, status, error, output }
  // agent.run(prompt) and agent.cancel() live on the returned object, not in the state

  const oneShot = createAgent("/api/agent");
  // $oneShot: AgentState = { output, loading, error }; oneShot.run(prompt)
</script>

<button on:click={() => agent.run("Explain AI")}>Ask</button>
<p>{$agent.text}</p>
{#if $agent.status === "streaming"}<span>●</span>{/if}
```

### Composer and slash menu (Svelte 5)

`@reactive-agents/svelte/components` ships `Composer` (textarea, send / queue / stop button, queued-message strip, file drop and paste, slash menu) and `SlashMenu`. The rules live in `@reactive-agents/ui-core` and are framework-free: `createSlashRegistry(commands)` (`parse`, `match`, `resolve`, `find`), `parseSlash` (a single line starting with `/` and a letters-and-dashes word; `/usr/bin/env` is a message), `matchCommands` (exact, then prefix, then substring), `commandWantsArg`, `commandInsertText`, `composerKeyAction(event, { menuOpen, enterSends?, hasQueued })` (returns `ignore` for IME composition, `menu-move`, `menu-pick`, `menu-close`, `clear-queued`, `submit` or `none`; `composerKeyHandled` says whether to `preventDefault`), `queueMessage`, `queuedAfterRun`, `composerAction`, `lastRunFailed`, `replaceDraft`, `restoreDraft`, `mentionTrigger(text, caret, marker?)` for `@` or `#`, `menuOptionId`, `moveMenuIndex`.

Drop-in: build a controller with `createComposer({ commands, onSend, onCommand?, onStop?, runsDuringRun?, menuItems? })` and pass `<Composer {composer} />`. The controller exposes `getState`, `subscribe`, `setText`, `setSending`, `submit`, `stop`, `sendAction`, `menu`, `keydown`, `choose`, `hover`, `dismissMenu`. Call `composer.setSending(true)` when a run starts and `setSending(false)` when it ends; a message typed during a run is queued and sent when the run ends normally. Pass `setSending(false, true)` after a stop or failure and the message stays queued.

```svelte
<script lang="ts">
  import "@reactive-agents/svelte/styles.css";
  import { createComposer, type SlashCommand } from "@reactive-agents/ui-core";
  import { Composer } from "@reactive-agents/svelte/components";

  const commands: SlashCommand[] = [{ name: "model", summary: "Switch model", arg: "<name>" }];
  let running = $state(false); // your run state; startRun, runCommand, stopRun are your functions
  const composer = createComposer({
    commands,
    onSend: (text) => startRun(text),
    onCommand: (command, arg) => runCommand(command.name, arg),
    onStop: () => stopRun(),
  });
  $effect(() => composer.setSending(running));
</script>

<Composer {composer} />
```

Controlled: `<Composer bind:value {sending} {queued} onSubmit onStop onClearQueued onSendQueuedNow />`, plus `menuOpen`, `menuIndex`, `menuItems`, `onMenuMove`, `onMenuPick`, `onMenuClose` when a menu is shown. Use it when the app already keeps that state; park a message typed during a run with `queueMessage(queued, text)`.

- `Composer` snippets: `leading`, `attachments`, `banner`, `belowField`, `footerStart`, `hint`, `actions`, `trailing`, `emptyMenu`. Props `labels` (any subset of every visible string), `icons`, `class`, `boxClass`. Hooks `data-ra-composer`, `data-ra-composer-box`, `data-ra-composer-input`, `data-ra-send` (with `data-action`), `data-ra-queued`, `data-ra-menu-keep`.
- `SlashMenu` props `items`, `selected`, `onHover`, `onDismiss`, `header` (Back row), `footer` (text or `false`), `keepSelector`; snippets `row` and `empty`. Row fields `multi`, `group`, `disabled`, `badge`, `hint`, `detail`, `active`, `run`, `complete`. The input points `aria-activedescendant` at `menuOptionId(id, index)`. Hooks `data-ra-slash-menu`, `data-ra-menu-row`, `data-selected`, `data-active`, `data-disabled`.
- Tokens: `--ra-composer-width` (48rem), `--ra-radius-panel`, `--ra-z-menu`, `--ra-text-md`, `--ra-text-2xs`, `--ra-lh-read`.

Full reference: `/features/agentic-ui-composer/`.

### Lists, tooltips and toasts (Svelte 5)

`@reactive-agents/svelte/components` (import `@reactive-agents/svelte/styles.css` once) ships `VirtualList`, `Tooltip` plus the `tooltip` action, and `Toaster`. The headless rules live in `@reactive-agents/ui-core` (`buildOffsets`, `computeWindow`, `shouldWindow`, `scrollDeltaForIndex`, `placeTooltip`, `resolveTip`, `tipOpenDelay`, `createToastQueue`, `addToast`, `removeToast`, `removeToastByKey`, `TOAST_DURATIONS_MS`), so React and Vue hosts can reuse them.

```svelte
<script lang="ts">
  import { VirtualList, tooltip, Toaster, createToaster } from "@reactive-agents/svelte/components";
  import RowView from "./RowView.svelte"; // your row view
  type Row = { readonly key: string; readonly label: string }; // items need a stable `key`
  let { rows }: { rows: Row[] } = $props();
  let list: VirtualList<Row>;
  const toast = createToaster();
</script>

<VirtualList bind:this={list} items={rows} label="Run timeline" estimate={30} overscan={8} threshold={120}>
  {#snippet item(row, index)}<RowView {row} {index} />{/snippet}
</VirtualList>
<button use:tooltip={"Delete run"} onclick={() => list.scrollToIndex(0, "start")}>Delete</button>
<Toaster toaster={toast} bottom={24} side="right" />
```

- `VirtualList`: `items` need a stable `key`; `label` names the list; `item` snippet `(item, index)`; lists shorter than `threshold` (default 120) render whole; rows announce `aria-setsize` and `aria-posinset`; `scrollToIndex(i, "start" | "center" | "end" | "nearest")` on a bound instance. Hooks `data-ra-virtual-list`, `data-ra-virtual-item`.
- `tooltip` action / `Tooltip` wrapper (`text`, `placement` `"top"` or `"bottom"`, `enabled`, `disabled`): opens on hover after a short delay and on keyboard focus, closes on Escape or scroll, sets `aria-describedby`. `enabled` is a boolean or a function read each time it would open. Hooks `data-ra-tooltip`, `data-side`.
- `Toaster` draws a `createToaster()` store (`success`, `error`, `warning`, `info`, `connection`, `prompt`, `permanent`, `remove`, `removeByKey`). A later toast with the same `key` replaces the earlier one. Props `toaster` (or share with `setToaster` / `getToaster`), `bottom`, `side`, `dismissLabel`, `icons`, `class`; snippets `icon` and `item`. Errors and warnings are `role="alert"`, others `role="status"`. A dismissed or replaced toast cancels its timer. Hooks `data-ra-toaster`, `data-ra-toast`, `data-kind`.
- Tokens: `--ra-surface-pop`, `--ra-shadow-pop`, `--ra-z-toast`, `--ra-z-tooltip`. Icons are string ids resolved through an `icons` registry.

### Cards and config shell (Svelte 5)

`@reactive-agents/svelte/components` also ships `ApprovalCard` (a run paused on an approval gate), `QuestionCard` (a `request_user_input` question), and the form parts `ApprovalParams`, `QuestionReply`, `QuestionForm`, `ConfigSection`, `FieldRow`, `ListField`. They own no store and send nothing: you pass `busy` and `error`, and perform the decision in a callback. Rules live in `@reactive-agents/ui-core`: `approvalArgRows(args, mask?)`, `approvalFullArgs`, `approvalArgsNeedDetail`, `approvalCardKey`, `hideCardKey`, `approvalCardMode`, `denyReasonOf`, `cardDismissKind`; `replyControl`, `choiceOptions`, `formFields`, `formValue`, `questionCardMode`, `questionsOf`, `buildAnswers`; `splitEntries`, `addUnique`, `isListed`, `removeAt`, `replaceAt`, `duplicateIssues`, `issuesAt`.

```svelte
<ApprovalCard {approval} {busy} {error} mask={redact}
  onApprove={() => decide("approve")} onDeny={(reason) => decide("deny", reason)}
  onHide={() => (hidden = true)} />
<QuestionCard {question} busy={questionBusy} {error} onReply={reply} onInvalid={(m) => (error = m)}
  onDismiss={() => sendDismiss(question)} />
```

- Dismiss is two different callbacks. `onHide` only takes the card off the screen; the approval or question stays pending. `onDismiss` is a decision your app sends (the card shows `busy="dismiss"`). `cardDismissKind` reads which is wired; `onDismiss` wins if both; neither means no button. Do not wire `onHide` where the user expects the gate to be answered.
- The default does not mask parameter values: pass `mask` (a `(text) => text` function) to hide secrets in `ApprovalCard` and `ApprovalParams`.
- `ApprovalCard` props: `approval` (`runId`, `gateId`, `toolName`, `args`, `subAgent?`), `onApprove`, `onDeny(reason)`, `onHide`, `onDismiss`, `busy` (`"approve" | "deny" | "dismiss"`), `busyText`, `error`, `mask`, `expanded`, `labels`, `icons`, `class`. Snippets `header`, `parameters`, `actions`, `icon`. Hooks `data-ra-approval`, `data-ra-tool`, `data-mode`, `data-action`.
- `QuestionCard` props: `question` (`runId`, `interactionId`, `kind`, `prompt`, `schema`, `questions?`), `onReply(value)`, `onInvalid(message)`, `onHide`, `onDismiss`, `busy` (`"reply" | "dismiss"`), `error`, `labels`, `class`. Snippets `header`, `prompt`, `reply`, `structured`, `actions`. A structured ask answers with an id-keyed map. Hooks `data-ra-question`, `data-mode`, `data-action`.
- `ConfigSection` (`id`, `open`, `onToggle`, `title`, `icon`, `flat`, `hideTitle`, `idPrefix`; snippet `head`): collapsible, or `flat` for an always-open panel; your app owns `open`. `FieldRow` (`label`, `for`, `description`, `wide`; snippets `help`, `control`). `ListField` (`id`, `items`, `text`, `onAdd` returns `false` to reject, `onRemove`, `issues`, `variant` `"chips"` or `"rows"`, `suggestions`; snippets `item`, `draftExtras`, `below`, `empty`).
- `ReceiptCard` (Svelte, React and Vue, each from its `/components` subpath) draws a finished run's trust receipt: verdict, verifier verdict, how the run ended, tools used, deliverables, harness interventions, recovered tool effects, provenance, signature state, and a copy action for the raw JSON. The verdict grades the evidence trail, never whether the answer is true. Props: `receipt` (`AgentResult.receipt`, the `StreamCompleted` event's `receipt`, or a stored copy; `null` or `undefined` shows the empty state), `signature` (`"valid" | "invalid" | "unsigned" | "unchecked"`), `redacted`, `noneReason`, `labels` (`Partial<ReceiptCardLabels>`, defaults `DEFAULT_RECEIPT_LABELS`), `onCopy(json)` (replaces the clipboard write; in Vue the `copy` event), `class` (`className` in React). The card makes no request and checks no signature: run `verifyReceipt` (from `reactive-agents`) yourself and pass `"valid"` or `"invalid"`; without `signature` a signed receipt is shown as signed but not checked. All rules are `receiptViewOf` in `@reactive-agents/ui-core`. Hooks `data-ra-receipt`, `data-state`, `data-verdict`, `data-signature`, `data-tone`, `data-action="copy"`.
- Strings: `labels` takes any subset of `ApprovalCardLabels`, `QuestionCardLabels`, `ListFieldLabels` (defaults `DEFAULT_APPROVAL_LABELS`, `DEFAULT_QUESTION_LABELS`, `DEFAULT_LIST_FIELD_LABELS`). Tokens `--ra-card-rail`, `--ra-card-tool`, `--ra-field-control-width`, `--ra-field-control-width-wide` have `var()` fallbacks and no dark set of their own.

### Context window views and markdown (Svelte 5)

Rules live in `@reactive-agents/ui-core`; you map your own record to a plain `ContextCall` (`id`, `position`, `iteration`, `lane: "main" | "aux"`; optional `systemPrompt`, `messages`, `toolRuns`, `guidanceChars`, `toolSchemaNames`, `tokensIn`, `cacheReadTokensIn`, and exact `recordedSections` and `recordedWindow`). `attributeContext(call, window?)`, `contextTimeline(calls, window?)` (main calls only) and `contextFindings(calls, window?)` (rules `pressure`, `duplicate-result`, `dominant-result`, `clipped-prompt`). Pressure: `contextPressureOf(events)` (falls back to iteration progress, or `null`), `contextWindowOf(events)`, `pressureTone`. Without recorded counts every number is an estimate (`estimateContextTokens`, about 4 chars per token) and an unrecorded section says `not-recorded`; never present an estimate as exact. Geometry and text: `donutSegments`, `barLayout`, `windowLineY`, `describeAttribution`, `describeTimeline`, `describePoint`, `rankedSections`, `formatContextTokens`, `formatShare`.

`@reactive-agents/svelte/components` ships `ContextGauge` (`events` or a ready `pressure`), `ContextChart` (`timeline`, `selectedId`, `onselect`, `legend`, `legendSnippet`, `captionSnippet`), `ContextAttribution` (`attribution`, `ranked`, `header`, `tooltipEnabled`) and `ContextFindings` (`findings`, `onInspect`, `limit`). All take `labels` (a subset of `ContextLabels`, defaults `DEFAULT_CONTEXT_LABELS`). Hooks `data-ra-context-gauge`, `data-ra-context-chart`, `data-ra-bar`, `data-ra-context-attribution`, `data-ra-context-findings`. Colours `--ra-ctx-system`, `-guidance`, `-skills`, `-memory`, `-tools`, `-history`, `-tool-results`, `-model-turns`, `-other`, with light and dark sets in `styles.css`.

```svelte
<ContextGauge {events} />
<ContextChart timeline={contextTimeline(calls, contextWindowOf(events))} selectedId={id} onselect={(c) => (id = c)} />
```

Markdown is a separate optional subpath: `import { Markdown } from "@reactive-agents/svelte/markdown"`, and install `marked` and `dompurify` (optional peers). Props `markdown`, `showCopy`, `codeCopy`, `headingIds`, `math` (a `(tex) => html` function you trust; its output is not re-sanitised), `render` (replaces the pipeline and must sanitise), `onrendered`, `onCopy`, `icons`, `labels`. Policy: images off; `class`, `style` and `on*` dropped; links keep `href` only for http(s), mailto and `#anchors`; external links get `rel="noopener noreferrer nofollow"`. The server render shows escaped raw text; sanitising runs only in the browser. Never pipe untrusted markdown through `{@html}` yourself.

### Drop-in blocks (React and Vue)

`@reactive-agents/react/components` and `@reactive-agents/vue/components` ship the same blocks as `@reactive-agents/svelte/components` (`ControlButton`, `ContinueStopped`, `Composer`, `SlashMenu`, `ApprovalCard`, `QuestionCard`, `ReceiptCard`, `ConfigSection`, `FieldRow`, `ListField`, `VirtualList`, `Tooltip`, `Toaster`, the four context blocks), built on the same `@reactive-agents/ui-core` view models. Import `@reactive-agents/react/styles.css` or `@reactive-agents/vue/styles.css` once: it is the shared `--ra-*` token sheet (dark under `[data-ra-theme="dark"]` or a `.dark` ancestor) plus the block rules. Props, `labels`, `data-ra-*` hooks and aria match Svelte. The examples were compiled against the built packages (`svelte-check`, `tsc`, `vue-tsc`); the docs build does not check them, so if one drifts, the exports win.

React: `className` for `class`, camelCase callbacks (`onClick`, `onApprove`, `onSelect`), snippets are render props (`header`, `actions`, `icon`, `item`, `parameters`, and `iconSnippet` on `ControlButton`) and simple slots are `ReactNode` props. `Composer` is drop-in (`composer` from `createComposer`; read its state with `useComposerState`) or controlled (`value` + `onValueChange`, `onCaretChange`, `inputRef`, `onFiles`, `onShortcut`). `useTooltip(text)` is a ref callback and `Tooltip` a wrapper. The toaster is `createToaster()` with `ToasterProvider`, `useToaster` and `useToasts`; `VirtualList` takes `listRef` for `scrollToIndex`. Icons: the `icons` prop or `IconRegistryProvider`.

Vue: plain `defineComponent` render functions (no SFC loader). Props down, emits up: `@continue`, `@retry`, `@approve`, `@deny`, `@reply`, `@toggle`, `@select`, `@inspect`, `@hide`, `@dismiss`; Svelte snippets are slots. `Composer` takes `v-model` and `v-model:caret` (controlled) or `:composer` (drop-in), emits `files`, and takes a `shortcut` function prop. `ListField` keeps `onAdd` as a callback prop (an event cannot return `false` to reject). The tooltip is the `v-tooltip` directive (`vTooltip`), `withTooltip`, or `Tooltip`. Toaster and icons: `provideToaster` / `useToaster` and `provideIconRegistry` / `useIconRegistry`, called from `setup`. `VirtualList` exposes `scrollToIndex` on a template ref.

`onHide` versus `onDismiss` (React props, Vue `@hide` and `@dismiss`): hide only takes the card off the screen and the approval stays pending; dismiss is a decision the host sends (the card shows `busy="dismiss"`). With both, dismiss wins; with neither, the card shows no Dismiss button (`cardDismissKind`).

Markdown is the optional subpath `@reactive-agents/react/markdown` or `@reactive-agents/vue/markdown` (`Markdown`, `renderMarkdown`, `sanitizeMarkdownHtml`, `decorateRendered`); install `marked` and `dompurify` (optional peers). Sanitising is always on. React reports through `onRendered` and `onCopy`, Vue through the `rendered` and `copy` events.

Full pages: `/features/agentic-ui-react-blocks/` and `/features/agentic-ui-vue-blocks/`.

### Streaming density

```ts
// Default: "tokens" — TextDelta events only (minimal payload)
const tokensOnly: Response = AgentStream.toSSE(agent.runStream(prompt));

// Full: all events including phase changes and tool calls
const everything: Response = AgentStream.toSSE(agent.runStream(prompt, { density: "full" }));
// Use "full" density when the UI shows tool usage or reasoning steps
```

### Express / Elysia server

```ts
import express from "express";
import { ReactiveAgents, AgentStream } from "@reactive-agents/runtime";

const app = express();
app.use(express.json());

app.post("/api/agent", async (req, res) => {
  const { prompt } = req.body;
  const agent = await ReactiveAgents.create()
    .withProvider("anthropic")
    .withReasoning({ defaultStrategy: "adaptive" })
    .withTools({ builtins: true })
    .build();

  const stream = agent.runStream(prompt);
  for await (const event of stream) {
    if (event._tag === "TextDelta") {
      res.write(`data: ${JSON.stringify(event)}\n\n`);
    }
    if (event._tag === "StreamCompleted") break;
  }
  res.end();
});
```

### Handling stream events client-side

```ts
import { useAgentStream } from "@reactive-agents/react";

const { events } = useAgentStream("/api/agent");

// Events are tagged by `_tag`. Some, with density: "full":
// TextDelta         — { _tag: "TextDelta", text: string }
// ToolCallStarted   — { _tag: "ToolCallStarted", toolName: string, callId: string }
// ToolCallCompleted — { _tag: "ToolCallCompleted", toolName: string, callId: string, durationMs: number, success: boolean }
// StreamCompleted   — { _tag: "StreamCompleted", output: string, metadata: ... }
// StreamError       — { _tag: "StreamError", cause: string }
// StreamCancelled   — { _tag: "StreamCancelled", reason: string, iterationsCompleted: number }
// The full union is UiStreamEvent in @reactive-agents/ui-core.
```

### Pause, stop and terminate events

`pause()`, `stop()` and `terminate()` on a `runStream()` handle emit `RunControlRequested` (`{ kind, requestedAt }`) and later `RunControlApplied` (`{ kind, requestedAt, appliedAt, latencyMs }`), where `kind` is `"pause" | "stop" | "terminate"`. `pause` and `stop` cut an in-flight model call at once but wait for a running tool to finish; only `terminate` cuts a tool. In a UI, use the headless helpers from `@reactive-agents/ui-core`: `controlFactsOf(type, payload)` reads either event, `applyControlEvent`/`beginControl`/`settleControl` hold the pending-button state, and `resumeOfferOf` says which Resume, Continue or Retry buttons a stopped run offers.

### Steer a live run

`useRun` (React, Vue), `createRun` (Svelte) and `useAgentStream` / `createAgentStream` return `steer(text): Promise<SteeringReceipt>`. A steering message is user input the kernel applies before its next model call. Pass a `steer` adapter (for example `handle.steer` from an in-process `agent.runStream()`) or a `steerUrl` your server hosts; the binding then sends `POST { text, runId }` and expects a receipt as JSON. With neither, `steer` answers `no-live-run`. The framework ships no steering route and does not authenticate: your route calls `agent.steer(runId, text)` (any agent in the process can reach a live run by id), after checking the caller owns the run.

```ts
const { state, run, steer } = useRun({ endpoint: "/api/agent", steerUrl: "/api/agent/steer" });
const receipt = await steer("Only the ones labelled bug");
// { accepted: true, id } | { accepted: false, reason: "queue-full" | "too-long" | "empty" | "no-live-run" | "unreachable" }
// "unreachable" is the binding's own answer for a network error, a 5xx or a non-JSON reply
```

Stream events: `SteeringApplied { id, iteration }` when the kernel applies a message; `unconsumedSteering` on `StreamCompleted`, `StreamCancelled` and `StreamError` for messages the run ended without applying. ui-core also exports `createSteer`, `parseSteeringReceipt` and `iterationsLabel` ("10 of 10 iterations"). Limits: only `runStream()` and durable runs are steerable (plain `run()` is not); steering works on the reactive kernel only. Reference: `/reference/builder-api/agent-sessions-and-control/`.

### Multimodal input (server route)

The server route can pass content parts to `agent.runStream()` or `session.chat()` instead of a string: `[{ type: "text", text }, { type: "image", source: { type: "base64", media_type, data } }]`. Check `modelInputCapabilities(provider, model)` first to enable or disable an attach control; an image or audio part for a model that cannot take it fails with `UnsupportedModalityError` before any model call.

### Safety entries

`safetyEntriesOf(events)` from `@reactive-agents/ui-core` builds `SafetyEntry` rows for a safety panel. Read `entry.place` (`SafetyPlace`: `"before-first-iteration" | "during" | "after-last-iteration"`; the iteration number for `"during"` is `entry.loop`). `entry.phase` (`"before" | "loop" | "end"`) is deprecated but kept with its old values; convert stored data with `safetyPlaceOfPhase(phase)`. `safetyPlaceLabel(entry)` renders either shape.

### Approvals, sub-agents, and recalled memory in the stream

- `ApprovalRequested` carries `runId` and `gateId`. Answer one gate with `agent.approveRun(runId, { gateId })` or `agent.denyRun(runId, reason, { gateId })`; parallel sub-agents ask under the root run id, so without `gateId` only the oldest wait is answered.
- Pending approvals from `agent.listPendingApprovals()` carry a `subAgent` label (the asking sub-agent's name) when a sub-agent asked. Show it so the user knows who is asking.
- `MemoryRecalled` events (one per non-empty memory tier at bootstrap) list what memory put into context; render them as a "context sources" view if useful.

## Packages

| Package | Exports |
|---------|---------|
| `@reactive-agents/react` | `useAgent`, `useAgentStream`; drop-in blocks at `/components`, Markdown at `/markdown`, `styles.css` |
| `@reactive-agents/vue` | `useAgent`, `useAgentStream`; from 0.20.1 `useRun`, `useResumableRun`, `useInteractions`, `useTaskInbox`, `useRunCost`, `useRunSteps`, `decideApproval`, `respondToInteraction` (Vue 3.2+); drop-in blocks at `/components`, Markdown at `/markdown`, `styles.css` |
| `@reactive-agents/svelte` | `createAgent`, `createAgentStream` |
| `@reactive-agents/runtime` | `AgentStream` (server-side SSE adapter) |

## Pitfalls

- The API route must be a server-side route — never build the agent in browser code (API keys would leak)
- `AgentStream.toSSE()` returns a `Response` object compatible with the Web Fetch API — it works in Next.js App Router and edge runtimes directly
- `density: "tokens"` (default) only sends `TextDelta` — use `density: "full"` if the client needs tool call visibility
- `useAgent` (one-shot) makes a POST and waits for JSON `{ output: string }` — the server route must return JSON, not SSE
- Always build the agent inside the request handler (not at module level) — module-level agents persist state across requests
- `cancel()` sends an AbortSignal to the server — the server route must pass the `AbortSignal` to `agent.runStream()` for it to take effect

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.