# Depute (AX) - Complete Documentation This file contains the complete, concatenated documentation for the Depute React component library. It is optimized for LLMs and AI coding agents. --- --- title: Introduction description: React primitives for the human side of agentic AI. --- ## What is Depute? *Depute (verb meaning to appoint or delegate).* **Depute** is a React component library for Agentic Experience (AX) design — purpose-built UI primitives for AI agent supervision and human oversight. The founding frame is [Delegation UI](/docs/lexicon#delegation-ui). Terms used on this site are defined in the [Lexicon](/docs/lexicon). When an AI agent runs in your product, users need to see what's happening — not raw logs, but structured UI for delegation, trust, and control. ## Why Depute? Most UI libraries build for CRUD apps. Depute builds for the moment *after* you hand off work to an agent: - The agent proposes a plan → [**Plan Card**](/docs/components/plan-card) shows it before execution - The agent wants to send email → [**Approval Gate**](/docs/components/approval-gate) blocks until the user approves - The agent is running → [**Run Controls**](/docs/components/run-controls) let the user pause or stop at any time - Multiple agents are coordinating → [**Orchestrator View**](/docs/components/orchestrator-view) shows who's managing whom **A toolkit for both Builders and Auditors:** For Product Engineers, Depute provides the UI to stop users from feeling anxious and losing context during long autonomous runs. For Security & Risk Teams, Depute is compliance infrastructure. Under emerging governance standards—like the **Singapore IMDA Agentic AI Governance Framework (Jan 2026)**—providing escalation paths, defining UI checkpoints for high-stakes actions, and making humans "meaningfully accountable" is a primary regulatory expectation. Depute helps you operationalize those governance requirements in code. ## Defeating Cognitive Failures Human-automation research shows that humans are terrible at passively monitoring highly autonomous systems. When working with AI agents, users fall into predictable cognitive traps. Depute maps its primitives directly against these known failures: - [**Automation Bias**](/docs/lexicon#automation-bias): Users blindly rubber-stamp agent actions without scrutiny → *Mitigated by an [**Automation Bias Alert**](/docs/components/automation-bias-alert) and [**Confidence Meter**](/docs/components/confidence-meter)* - [**Execution Amnesia**](/docs/lexicon#execution-amnesia): Users lose track of the total "blast radius" of a massive agent session → *Mitigated by a [**Session Overview**](/docs/components/session-overview) and [**State Diff**](/docs/components/state-diff)* - [**Responsibility Diffusion**](/docs/lexicon#responsibility-diffusion): Users approve actions assuming the machine is accountable → *Mitigated by a [**Decision Record**](/docs/components/decision-record) and [**Binding Approval**](/docs/components/binding-approval)* ## Mitigating Systemic Threats While Cognitive Failures describe UX traps, Systemic Threats describe catastrophic operational failure modes increasingly targeted by international AI legislation (e.g., IMDA Systemic Threats). Depute's components function as active algorithmic firebreaks: - [**Cascading Failures**](/docs/lexicon#cascading-failures): An agentic error pollutes downstream autonomous systems rapidly → *Contained by a [**Swarm Monitor**](/docs/components/swarm-monitor) and [**Orchestrator View**](/docs/components/orchestrator-view)* - [**Hallucinated Planning**](/docs/lexicon#hallucinated-planning): An agent proposes a destructive or nonsensical sequence of tools → *Exposed by a [**Plan Card**](/docs/components/plan-card) and [**Confidence Meter**](/docs/components/confidence-meter)* - [**Rogue Tool Use**](/docs/lexicon#rogue-tool-use): An agent attempts an irreversible action out-of-bounds → *Blocked by an [**Approval Gate**](/docs/components/approval-gate) and [**Tool Trace**](/docs/components/tool-trace)* - [**Unpredictable Outcomes**](/docs/lexicon#unpredictable-outcomes): A run completes with thousands of opaque, unlogged side effects → *Audited with a [**State Diff**](/docs/components/state-diff) and [**Session Overview**](/docs/components/session-overview)* ## Use-Case Index (Problem-First) Not sure which component to use? **Press `⌘K` to search by problem.** The docs are mapped to UX challenges (e.g., search for "cognitive load" or "context switch"). Or start here: - *"I need to safely switch agent focus across a swarm"* → Use an [**Orchestrator View**](/docs/components/orchestrator-view) + [**Shared Context Ledger**](/docs/components/shared-context-ledger) - *"I need to stop an agent from making an unrecoverable mistake"* → Use an [**Approval Gate**](/docs/components/approval-gate) + [**Tool Trace**](/docs/components/tool-trace) - *"I need to show the user what the agent is thinking"* → Use a [**Plan Card**](/docs/components/plan-card) + [**Confidence Meter**](/docs/components/confidence-meter) - *"I need to prevent users from blindly rubber-stamping approvals"* → Use an [**Automation Bias Alert**](/docs/components/automation-bias-alert) wrapping an [**Approval Gate**](/docs/components/approval-gate) - *"I need a person to confirm an irreversible action, then show the backend's receipt"* → Use a [**Binding Approval**](/docs/components/binding-approval) + [**Transaction Receipt**](/docs/components/transaction-receipt). Those components display a signature or hash your backend produced. They do not sign. - *"I need to roll back a sequence of 40 API calls"* → Use a [**Rollback Timeline**](/docs/components/rollback-timeline) + [**State Diff**](/docs/components/state-diff) ## Distribution model Components are delivered via CLI copy-paste (like shadcn/ui). The source lands in your repo — you own it, you can read it, you can modify it. ```bash npx ax-depute@latest add approval-gate ``` No lock-in. No black-box npm package the agent can't inspect. ## The AI Skill Layer You aren't the only one building this app—your AI agent is too. Depute ships with a native **Skill Layer** built for Claude Code, Cursor, and Copilot. When you install a component, you get the UI code for the human *and* the structural reasoning instructions for your AI agent. The skill teaches your agent exactly when to use an `ApprovalGate` versus a `RunControls` boundary, ensuring the UI your agent helps you build is the same UI your agent knows how to use. ```bash npx ax-depute@latest init ``` This command drops a `skills/depute/SKILL.md` file into your project, automatically giving Claude Code, Cursor, or Copilot deep intelligence on how to use Depute's primitives in your specific codebase. ## Three tiers | Tier | Components | Use case | |------|-----------|----------| | **Single Agent** | 7 primitives | One agent acting on behalf of a user | | **Multi-Agent** | 11 primitives | Multiple agents coordinating, delegating, or running in parallel | | **Compliance & Forensics** | 9 primitives | High-stakes intent, mutation visibility, and audit trails | ## Component Architecture To help you quickly understand how to compose the library, every component in the sidebar is explicitly tagged with its architectural classification. You will see these taxonomy badges next to every component name: - Primitive A foundational, single-responsibility building block (e.g., `PlanCard`, `ApprovalGate`). - View A compositional surface that aggregates multiple primitives into a larger macro-interface (e.g., `OrchestratorView`, `SwarmInbox`). - Control An operational or forensic surface used to halt, direct, or audit execution (e.g., `EscalationRouter`, `DecisionRecord`). - Pattern A highly specialized workflow wrapper designed to enforce a specific behavioral policy (e.g., `AutomationBiasAlert`, `HandoffProtocol`). Class definitions are canonical in the [Lexicon](/docs/lexicon#primitive). Start with Single Agent primitives. Add Multi-Agent when you need orchestration. Components in the sidebar are ordered by **solution patterns** — the sequence you'd encounter them when building a complete agent interaction, not alphabetically. --- --- title: Installation description: Add Depute components to your project using the CLI. --- ## Requirements - React 18+ - TypeScript - CSS Modules support (standard in Vite, Next.js, CRA) Depute is **agent-agnostic** — it works with any AI backend (OpenAI, Anthropic, LangChain, AutoGen, or custom). ## Install a component ```bash npx ax-depute@latest add approval-gate ``` ```bash pnpm dlx ax-depute@latest add approval-gate ``` ```bash yarn dlx ax-depute@latest add approval-gate ``` ```bash bunx ax-depute@latest add approval-gate ``` This copies the component source files directly into `src/components/ApprovalGate/`. You own the code. Each fetched file is checked against the release checksum before anything is written. If one does not match, or the command is interrupted, that attempt removes only the files and directories it created and restores any stylesheet it edited. Files and directories that were already in the project are left as they were, including empty directories. On first install, shared files are also added once, next to the component directory: - `src/types/ax-common.ts` — shared TypeScript types (`PlanStep`, `ToolCall`, `Artifact`) - `src/types/ax-core.ts` — handoff and presented-payload types (`HandoffContext`, `PresentedPayload`) - `src/utils/ax-receipt.ts` — canonical approval receipt, hash, and `verify` - `src/utils/ax-a11y.tsx` — accessibility utilities used across components - `src/styles/depute.css` — design tokens and motion. This is the one stylesheet import. ## Styles Component CSS reads `--ax-*` tokens. Without the stylesheet, an installed component renders unstyled. The CLI copies `depute.css`, `tokens.css`, and `animations.css` into `src/styles/` and, when it finds a global stylesheet such as `src/index.css`, inserts: ```css @import "./styles/depute.css"; ``` Pass `--css src/index.css` to choose the file, or `--no-css` to skip the edit and add the import yourself. That single import is the only manual step when the CLI cannot find a stylesheet. `--dir` moves the shared files with the components. `add run-controls --dir components/ax` writes the component to `components/ax/RunControls/` and the shared files to `components/types`, `components/utils`, and `components/styles`, then rewrites the imports so they resolve. ## Initialize the AI Skill Layer Depute ships with a native **Skill Layer** that teaches your AI agent (Claude Code, Cursor, Copilot) how to use the components you just installed. ```bash npx ax-depute@latest init ``` ```bash pnpm dlx ax-depute@latest init ``` ```bash yarn dlx ax-depute@latest init ``` ```bash bunx ax-depute@latest init ``` This command writes `skills/depute/SKILL.md` (and its reference files) into your repository, plus `skills/depute/depute.skill.json` with the CLI version. It also installs the design tokens when `src/styles/depute.css` is not already there, and writes `src/types/ax-common.ts` and `src/utils/ax-a11y.tsx` when those files are missing. A second run skips files that already exist and does not duplicate the CSS import. The skill tells an agent how to compose the primitives. It is not a runtime dependency. ## List all components ```bash npx ax-depute list ``` ```bash pnpm dlx ax-depute list ``` ```bash yarn dlx ax-depute list ``` ```bash bunx ax-depute list ``` ## Install multiple components ```bash npx ax-depute@latest add plan-card npx ax-depute@latest add tool-trace npx ax-depute@latest add run-controls ``` ```bash pnpm dlx ax-depute@latest add plan-card pnpm dlx ax-depute@latest add tool-trace pnpm dlx ax-depute@latest add run-controls ``` ```bash yarn dlx ax-depute@latest add plan-card yarn dlx ax-depute@latest add tool-trace yarn dlx ax-depute@latest add run-controls ``` ```bash bunx ax-depute@latest add plan-card bunx ax-depute@latest add tool-trace bunx ax-depute@latest add run-controls ``` ## Shared types All components use these core types from `src/types/ax-common.ts`: ```ts interface PlanStep { id: string; label: string; status: 'pending' | 'active' | 'completed' | 'failed'; confidence?: number; } interface ToolCall { id: string; name: string; input?: Record; output?: Record; status: 'pending' | 'running' | 'completed' | 'failed'; timestamp: string; policyFlags?: { requiresApproval?: boolean; writesState?: boolean; externalAction?: boolean; }; } interface Artifact { id: string; content: string; format: 'markdown' | 'json' | 'csv' | 'code'; sourceStepId?: string; toolCallIds?: string[]; } ``` ## No backend required Optional prototyping generators are a separate install. They are not copied with a component: ```bash npx ax-depute add mock-data ``` ```tsx const plan = generateMockPlan(4); // 4-step agent plan const trace = generateMockToolCalls(3); // 3 tool call entries ``` `mock-data` type-imports the components it describes. Add those components before typechecking. With `--dir`, the file is written under that directory's parent `utils/` folder and its imports point at the components you installed there. --- --- title: Agent Roster description: Status dashboard for scanning all active sub-agents. badge: View --- ## Install ```bash npx ax-depute@latest add agent-roster ``` ```bash pnpm dlx ax-depute@latest add agent-roster ``` ```bash yarn dlx ax-depute@latest add agent-roster ``` ```bash bunx ax-depute@latest add agent-roster ``` ## Overview A dense table view designed for the "Flat Swarm" orchestration model (e.g., [OpenAI's Swarm](https://github.com/openai/swarm)). It allows a human supervisor to scan 20+ concurrent workers at a glance, monitoring roll-up metrics like agent status, uptime, and token cost. ## Basic usage ```tsx const mockAgents: AgentRosterItem[] = [ { id: 'ag_1', name: 'Research Router', role: 'Orchestrator', status: 'working', currentTask: 'Delegating to search APIs', tokensUsed: 1250, lastActive: 'Just now' }, { id: 'ag_2', name: 'Browser Node', role: 'Web Scraper', status: 'failed', currentTask: 'Scraping Wikipedia', tokensUsed: 840, lastActive: '5m ago' } ]; export function App() { const [selectedId, setSelectedId] = useState('ag_1'); return (
setSelectedId(agent.id)} />
); } ``` ## Props | Prop | Type | Default | Description | | :--- | :--- | :--- | :--- | | `agents` | `AgentRosterItem[]` | `undefined` | Array of agent data objects to render as rows in the table. | | `selectedAgentId` | `string` | `undefined` | The `id` of the currently selected agent row. | | `onAgentSelect` | `(agent: AgentRosterItem) => void` | `undefined` | Callback fired when the user clicks on a row. | | `className` | `string` | `undefined` | Additional CSS class for the root element. | ## Types ### `AgentRosterItem` ```typescript export interface AgentRosterItem { id: string; name: string; role: string; status: AgentStatus; // 'idle' | 'working' | 'blocked' | 'failed' | 'completed' currentTask?: string; // E.g., "Summarizing PDF" tokensUsed?: number; // Token burn count for this session lastActive?: string; // E.g., "2m ago" } ``` ## Solution Patterns `Agent Roster` is specifically designed for flat worker pools. - Use it alongside **Swarm Monitor** at the top of the viewport to provide aggregate cost and error metrics for the entire fleet. - When a user clicks a specific row (`onAgentSelect`), surface the detail view for that agent using a combination of **Plan Card**, **Tool Trace**, and **Run Controls**. ## Design rationale **1. Data Density for Flat Swarms** While `Orchestrator View` is best for hierarchical workflows, `Agent Roster` is designed for "flat" worker pools (like OpenAI Swarm). It prioritizes information density over structural mapping, allowing supervisors to monitor dozens of parallel tasks without scrolling. **2. Roll-Up Status Metrics** The header of the roster automatically calculates and displays summary metric pills based on the `agents` array (e.g., showing how many agents are Working, Blocked, or Failed). This provides instant situational awareness of the swarm's health. **3. Economic Visibility** Agents spend money. The `tokensUsed` column surfaces economic metrics directly into the operational view, treating API spend as a first-class citizen alongside task status and uptime. --- --- title: Approval Gate description: Block execution and ask the user to approve a risky or high-stakes agent action. badge: Primitive --- Answers: [Rogue Tool Use](/docs/lexicon#rogue-tool-use), [Scoped grant](/docs/lexicon#scoped-grant), [Staged approval](/docs/lexicon#staged-approval), [L3 Supervised](/docs/lexicon#l3-supervised). ## Install ```bash npx ax-depute@latest add approval-gate ``` ```bash pnpm dlx ax-depute@latest add approval-gate ``` ```bash yarn dlx ax-depute@latest add approval-gate ``` ```bash bunx ax-depute@latest add approval-gate ``` ## Overview `Approval Gate` is the trust boundary primitive. It pauses agent execution and surfaces a structured approval UI before the agent crosses a trust boundary — sending emails, writing to a database, calling an external API. The key design principle (from Stripe's SPT pattern): **approvals are scoped grants, not binary yes/no decisions**. A user approving "send emails" shouldn't be approving "send unlimited emails forever." ## Basic usage ```tsx agent.continue()} onReject={() => agent.abort()} /> ``` ## With scoped grant ```tsx agent.continue()} onReject={() => agent.abort()} /> ``` ## Staged mode (Preview → Confirm → Execute) For high-risk multi-step actions, use `mode="staged"` to walk the user through three phases before execution: ```tsx agent.deploy()} onReject={() => agent.cancelDeploy()} /> ``` ## Async Approval Handoff (Dispatch Pattern) If an agent executes a long-running background workflow, the human may step away from their machine. A blocking modal that nobody is watching acts indistinguishably from a hung process. To solve this, configure the `approvalHandoff` prop to automatically hand the approval off to a mobile device or Slack channel after a set timeout: ```tsx { await sendSmsWebhook(user.phone, ctx); setStatus('handoff_pending'); }} handoffDeadlineMs={Date.now() + 86400000} // Backend TTL for UI rehydration sync /> ``` When `status` shifts to `handoff_pending`, the component drops the blocking modal trap and gracefully collapses into a non-blocking ambient status card that counts down to the deadline. ## Props | Prop | Type | Default | Description | |------|------|---------|-------------| | `title` | `string` | — | Short label for the action being approved | | `description` | `string` | — | Human-readable explanation of what the agent will do | | `agentReasoning` | `string` | — | Why the agent thinks this action is necessary | | `mode` | `'simple' \| 'staged'` | `'simple'` | Staged adds Preview → Confirm → Execute steps | | `status` | `'pending' \| 'approved' \| 'rejected' \| 'handoff_pending' \| 'handoff_denied' \| 'handoff_expired'` | `'pending'` | Controls gate state | | `scope` | `ApprovalScope` | — | Optional scoped grant (target, resourceLimit, durationSeconds) | | `onApprove` | `() => void` | — | Called when user approves | | `onReject` | `() => void` | — | Called when user rejects | | `approvalHandoff` | `ApprovalHandoff` | — | Configures timeout and fallback to automatically trigger async handoff. | | `onHandoff` | `(ctx) => Promise` | — | Fires when the synchronous timeout is breached. | | `handoffDeadlineMs` | `number` | — | Absolute unix timestamp for TTL enforcement (useful for UI sync on session restore). | ## When to use - The agent is about to cross a trust boundary — sending an email, modifying a database record, calling an external API, executing a financial transaction - The action is irreversible or hard to undo and a human should explicitly sign off before it runs - You need a scoped, time-limited capability grant rather than a blanket yes/no decision - The agent has low confidence or is operating in an unfamiliar context ## When not to use - The agent is performing read-only operations — no approval gate is needed for purely observational tool calls - Every single agent step requires approval — this creates approval fatigue; gate only the high-stakes boundaries - The action is trivially reversible (e.g., drafting a note that hasn't been sent) — use `Plan Card` to show intent without requiring an explicit approval - For irreversible actions where your backend must record the confirmation, escalate to `Binding Approval` instead ## Accessibility - The gate renders as a `role="dialog"` region with `aria-modal="true"` when in blocking mode to trap focus appropriately - Approve and Reject buttons have explicit `aria-label` values that include the action name (e.g., "Approve: Send email to customer") - Status changes (approved, rejected, handoff_pending) are announced via `aria-live="assertive"` on the status region - All scoped grant details are exposed as readable text, not just visual badges - Keyboard navigation: `Tab` moves between Approve/Reject, `Enter`/`Space` triggers; `Escape` does not dismiss (intentional — prevents accidental closure) ## Solution Patterns `Approval Gate` usually sits immediately after a `Plan Card` and before `Run Controls`: ```text Plan Card → [Approval Gate] → Run Controls → Tool Trace ``` It pauses execution until a person approves, rejects, or the handoff deadline passes. ## Design rationale **Why `scope`?** Binary approve/reject is the wrong mental model for agents. Stripe never approves an action with a simple yes/no — they issue capability grants scoped to a specific target, resource limit, and time window. **Why `mode="staged"`?** Agent flows are state machines, not request-response cycles. `staged` mode maps to Stripe's Authorization Chain pattern: Intent → Plan → Permission Check → Execution → Audit. Each phase can fail or pause for human input. **For irreversible or legally binding actions**, consider using [**Binding Approval**](/docs/components/binding-approval) instead. It extends the approval pattern with mandatory term acknowledgment, an `isSigning` freeze state, and signer identity capture. See the [decision rule](/docs/components/binding-approval#design-rationale) for when to escalate. --- --- title: Artifact Card description: Render the final output of an agentic workflow with export and provenance tracing. badge: Primitive --- Answers: [Provenance](/docs/lexicon#provenance), [L1 Human-Led](/docs/lexicon#l1-human-led). ## Install ```bash npx ax-depute@latest add artifact-card ``` ```bash pnpm dlx ax-depute@latest add artifact-card ``` ```bash yarn dlx ax-depute@latest add artifact-card ``` ```bash bunx ax-depute@latest add artifact-card ``` ## Overview The agent's "receipt" of work completed. It renders the final output alongside crucial provenance data: precisely which plan step and tool calls generated it. It also provides integrated export options. ## Basic usage ```tsx ``` ## With mock data Because `Artifact Card` requires a full artifact object to render, here is an example of what that object looks like: ```tsx const mockArtifact: Artifact = { id: 'art_123', type: 'code', title: 'Database Schema Migration', createdAt: new Date(), content: 'CREATE TABLE users (id SERIAL PRIMARY KEY, name VARCHAR(50));', sourceStepId: 'step_2', toolCallIds: ['call_456'] }; export function App() { return ( console.log(`Exporting as ${format}`)} showPreview={true} /> ); } ``` ## Streaming state When content is still arriving from a live backend, pass `isStreaming`. Adds `data-streaming="true"` to the root — no built-in animation; the host product styles it: ```tsx ``` ## Props | Prop | Type | Default | Description | |------|------|---------|-------------| | `artifact` | `Artifact` | **Required** | The artifact object to display (contains `title`, `type`, `content`, etc.). | | `exportFormats` | `ExportFormat[]` | `undefined` | Array of available export formats to show as action buttons (e.g., `'markdown'`, `'json'`). | | `onExport` | `(format: ExportFormat) => void` | `undefined` | Callback fired when an export button is clicked. | | `showPreview` | `boolean` | `true` | Whether to render a preview of the artifact's `content` inside the card. | | `maxPreviewHeight` | `string` | `'24rem'` | Maximum height of the content preview area before an internal scrollbar appears. | | `isStreaming` | `boolean` | `false` | Signals that content is still arriving. Adds `data-streaming="true"` to the root element — no built-in animation; style via CSS. | ## When to use - The agent has completed a workflow and produced a discrete, shareable output (document, code, report, data) that the user needs to review, export, or act on - Provenance matters — the user should be able to trace the output back to the specific plan step and tool calls that produced it - The output type varies across runs (markdown, JSON, code, SQL) and you need a single component that handles all of them ## When not to use - The agent's output is a direct action that has already been executed (e.g., an email sent, a file deployed) — use `Transaction Receipt` or `Decision Record` instead - The output is a streaming partial — wait for completion or use `isStreaming` only as a transitional state, not a permanent one - You only need to display a success/failure confirmation with no shareable content — a simple status notification is less heavyweight ## Accessibility - The artifact content area is a `
` with `aria-label` derived from the artifact title (e.g., "Artifact: Database Schema Migration") - Export buttons have explicit `aria-label` values that include the format (e.g., "Export as Markdown") - Streaming content is announced via `aria-live="polite"` so screen readers track new content arriving without interruption - Code content is rendered inside `
` with appropriate `role="region"` and `aria-label="Code output"` for keyboard traversal
- Provenance metadata (step ID, tool calls) is rendered as readable text, not hidden behind hover states

## Solution Patterns

`Artifact Card` is the grand finale of a single-agent execution sequence:

```text
Plan Card → Approval Gate → Run Controls → Tool Trace → [Artifact Card]
```
Once the agent finishes its work, the trace concludes and this component is rendered to display the final, tangible output.

## Design rationale

**Why the "Receipt" Pattern?** In traditional SaaS, the UI *is* the application. In agentic software, the UI is often just the exhaust of the application. The `Artifact Card` treats the final output as a primary, shareable asset. 

**Why verifiable provenance?** Trust requires auditability. The `sourceStepId` and `toolCallIds` metadata fields visually connect the final artifact back to the exact operations that produced it, preventing "hallucinated outputs" from passing without scrutiny.

**Why focus on actionability?** Agents excel at generation, but humans excel at distribution. Integrated `exportFormats` acknowledge that the artifact's lifecycle doesn't end in the chat UI—it needs to be pulled into PRs, Slack messages, or Google Docs.


---

---
title: Automation Bias Alert
description: Counteract "rubber-stamping" behavior by introducing deliberate friction when passive oversight is detected.
badge: Pattern
---


Answers: [Automation Bias](/docs/lexicon#automation-bias), [L3 Supervised](/docs/lexicon#l3-supervised).

## Install


  
```bash
npx ax-depute@latest add automation-bias-alert
```
  
  
```bash
pnpm dlx ax-depute@latest add automation-bias-alert
```
  
  
```bash
yarn dlx ax-depute@latest add automation-bias-alert
```
  
  
```bash
bunx ax-depute@latest add automation-bias-alert
```
  


## Overview

> [!NOTE]
> `AutomationBiasAlert` is not a standalone UI module. It is a **policy wrapper pattern** designed to sit exclusively over existing approval boundaries.

Automation bias occurs when humans over-trust automated systems, leading to passive oversight or "rubber-stamping" of errors. This wrapper counteracts this by monitoring approval patterns and introducing a mandatory review pause when bypass behavior is detected.


  




## Basic usage

The component works as a wrapper around interactive oversight elements (like `ApprovalGate`). It uses the `useAutomationBias` hook to monitor events and trigger the alert.

```tsx

function MyOversightUI() {
  const { isAlertTriggered, recordAction, dismissAlert } = useAutomationBias();

  const handleAction = (action: 'approved' | 'rejected') => {
    // Record the action to update internal bias heuristics
    recordAction(action);
    executeAction(action);
  };

  return (
    
      
    
  );
}
```

## With custom thresholds

You can tune the sensitivity of the bias detection by passing custom thresholds to the hook.

```tsx
const { isAlertTriggered, recordAction, dismissAlert } = useAutomationBias({
  consecutiveApprovals: 3,   // Alert after 3 consecutive approvals
  minApprovalTimeMs: 2500,  // Require 2.5s review time
  approvalRateCeiling: 0.8  // Alert if approval rate > 80%
});
```

## Detection Heuristics

The `useAutomationBias` hook monitors three specific behavioral signals:

1. **Consecutive Approvals**: Detecting long streaks of approvals without a single rejection or modification.
2. **Approval Velocity**: Measuring the time between the UI rendering and the user clicking "Approve". If it's faster than a human could realistically review the content, it triggers friction.
3. **Session Ceilings**: Monitoring the overall approval-to-rejection ratio. If a user approves >90% of actions over a long period, it indicates potential over-trust.

## Props

### AutomationBiasAlert

| Prop | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `children` | `ReactNode` | - | The interactive UI to be wrapped/protected. |
| `isActive` | `boolean` | `false` | Whether the friction overlay should be displayed. |
| `onAcknowledge` | `() => void` | - | Callback when the user acknowledges the alert after the pause. |
| `actionName` | `string` | `'this action'` | The name of the action being gated, used in the alert message. |
| `className` | `string` | - | Optional custom styling for the container. |

### useAutomationBias

| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `consecutiveApprovals` | `number` | `5` | Trigger alert after this many consecutive approvals. |
| `minApprovalTimeMs` | `number` | `1500` | Minimum ms required for a "valid" review. |
| `approvalRateCeiling` | `number` | `0.9` | Trigger alert if overall approval rate exceeds this % (0-1). |

## When to use

- Users are approving high-stakes agent actions in rapid succession — financial transactions, code deployments, medical recommendations
- You have evidence or suspicion of rubber-stamping behavior in your product (high approval rates, very short review times)
- The consequence of a false positive (approving a bad action) significantly outweighs the friction cost of a pause
- You are operating a swarm inbox or batch approval queue where velocity bias is structurally likely

## When not to use

- The approval flow is for low-stakes reversible actions — introducing friction here erodes trust in the friction itself, making it ineffective when it matters
- Users have no ability to meaningfully review the content before approving (e.g., the action details aren't surfaced) — fix the information architecture first
- You are using it as a substitute for actually improving the clarity of the approval interface

## Accessibility

- The friction overlay renders as a `role="alertdialog"` with `aria-modal="true"` to capture focus during the mandatory pause
- The countdown timer is announced as a live region (`aria-live="polite"`) so screen reader users are aware of the pause duration
- The acknowledge button is focussed automatically when the overlay appears
- The alert message includes explicit text explaining why the pause was triggered — not just a visual warning icon
- Color (amber/red) is never the sole indicator of the alert state; an icon and text label always accompany it

## Solution Patterns

### The Interceptor Layer
`AutomationBiasAlert` is an **interceptor layer**. It should wrap components that have `onApprove` or `onProceed` callbacks:

```text
Plan Card → [Automation Bias Alert → Approval Gate] → Run Controls
```

It monitors the final interaction point before an irreversible action is executed.

### Progressive Friction against Approval Fatigue
In high-throughput environments (like a `SwarmInbox` queue), users experience "velocity bias" — they approve faster as the queue grows, actively degrading their scrutiny. You can dynamically scale the friction thresholds to combat this cognitive failure.

```tsx
// Instead of static thresholds, progressively harden them based on state
const consecutiveThreshold = approvalStreak >= 5 ? 2 : 5;
const requiredPauseMs = approvalStreak >= 5 ? 5000 : 1500;

const { isAlertTriggered, recordAction, dismissAlert } = useAutomationBias({
  consecutiveApprovals: consecutiveThreshold,
  minApprovalTimeMs: requiredPauseMs,
});
```
*If a user approves 5 items in a row without rejection, the enforced pause climbs from 1.5 seconds to 5 seconds. This explicitly breaks their automatic rhythm.*

## Design rationale

**Why friction?**
When an interface is too smooth, users stop paying attention. They settle into a rhythm of clicking — "rubber-stamping" — and critical details slip past them unreviewed.

**Why does familiarity increase errors?**
The more a user feels "in control" of an AI system, the more likely they are to blindly accept its suggestions. Research by [Shalaleh Rismani](https://shalalehrismani.com/), an AI safety researcher at McGill and Mila, confirms this: users who better understood an AI writing assistant trusted it more — and accepted significantly more errors as a result. More transparency doesn't always lead to better oversight; it often leads to more trust and less scrutiny.

**Why a mandatory pause?**
`AutomationBiasAlert` detects when repeated approvals suggest a user has stopped actually reviewing — and introduces a pause to break the pattern. The discomfort is the point.

- **Non-blocking**: It doesn't prevent the user from approving, but it breaks the physical rhythm of repetitive clicking.
- **Contextual**: It only appears when behavioral patterns suggest the human is no longer actually reviewing the data.
- **Safety-Critical**: Essential for agents performing financial transactions, medical evaluations, or high-consequence code deployments.


---

---
title: Binding Approval
description: High-stakes intent gate. Displays a signature your backend supplies.
badge: Primitive
---


Answers: [Binding Approval](/docs/lexicon#binding-approval), [Responsibility Diffusion](/docs/lexicon#responsibility-diffusion).

## Install


  
```bash
npx ax-depute@latest add binding-approval
```
  
  
```bash
pnpm dlx ax-depute@latest add binding-approval
```
  
  
```bash
yarn dlx ax-depute@latest add binding-approval
```
  
  
```bash
bunx ax-depute@latest add binding-approval
```
  


## Overview

Unlike a standard `ApprovalGate` used for day-to-day coordination, `BindingApproval` provides a heavy-duty friction boundary for irreversible or financial actions. It forces explicit acknowledgment of terms and implements a multi-phase `isSigning` visual state.

`BindingApproval` does not sign, hash, or talk to a ledger. Pass `signature` and `hash` when your backend has already produced them, and pass `onVerify` if the app should check that proof. The component only displays those values.


  




## Basic Usage

```tsx
 backend.recordIntent()}
  onVerify={(proof) => backend.verify(proof)}
/>
```

## Solution Patterns

This primitive replaces `ApprovalGate` in high-stakes nodes. The internal state expects a clear distinction between `reviewing` and `signing`, where `isSigning: true` disables interaction and renders a deterministic loading state while your backend records the intent.

## Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `title` | `string` | — | Title of the binding action |
| `description` | `string` | — | Detailed explanation of the action |
| `impactStatement` | `string` | — | Estimated impact (e.g., "$5,000 will be transferred") |
| `status` | `'reviewing' \| 'signing' \| 'signed' \| 'rejected' \| 'expired'` | `'reviewing'` | Current status |
| `terms` | `BindingTerm[]` | — | Terms that must be acknowledged |
| `requireAllTerms` | `boolean` | `true` | Require all terms acknowledged to sign |
| `isSigning` | `boolean` | `false` | Toggles the active signing visual state |
| `signerIdentity` | `string` | — | Identity of the approver |
| `timeoutSeconds` | `number` | — | Signing window timeout |
| `onSign` | `() => void` | — | Called when the user confirms. Your backend records the intent. |
| `onReject` | `(reason?: string) => void` | — | Called when rejected |
| `signature` | `string` | — | Signature string from your backend. Display only. |
| `hash` | `string` | — | Hash string from your backend. Display only. |
| `onVerify` | `(proof) => void` | — | Your app's check for the displayed signature and hash. |

## Design rationale

**When to use `ApprovalGate` vs `BindingApproval`:**

| | `ApprovalGate` | `BindingApproval` |
|---|---|---|
| **Use when** | The action is reversible, operational, or low-to-moderate stakes | The action is irreversible or financial, and your backend will record the intent |
| **Friction level** | Quick scoped grant — review and approve | Mandatory term acknowledgment + signing flow |
| **State model** | `pending → approved / rejected` | `reviewing → signing → signed / rejected` |
| **Examples** | "Send this email", "Deploy to staging", "Run this query" | "Wire $50k", "Sign this contract", "Commit to ledger" |

Use `ApprovalGate` by default. Escalate to `BindingApproval` only when the action is irreversible and your backend must record who confirmed it.

**Why `isSigning`?** Normal approvals execute instantly. High-stakes approvals often wait on a backend round trip. `isSigning` freezes the component so the user cannot submit twice. The component still does not produce a signature.

**Why explicit terms?** Click-fatigue trains users to blindly click "Approve." Forcing the user to manually acknowledge explicit terms (e.g. "This action cannot be undone") breaks automatic behavior and captures verifiable intent.


---

---
title: Branch Controls
description: Scoped execution controls for a single branch of the swarm.
badge: Control
---


## Install


  
```bash
npx ax-depute@latest add branch-controls
```
  
  
```bash
pnpm dlx ax-depute@latest add branch-controls
```
  
  
```bash
yarn dlx ax-depute@latest add branch-controls
```
  
  
```bash
bunx ax-depute@latest add branch-controls
```
  


## Overview

While `Run Controls` operates on a single agent, and `Swarm Monitor` can kill the entire fleet, `Branch Controls` operates on a specific *sub-tree*. It allows a supervisor to pause or quarantine a troubled workflow branch without freezing the rest of the healthy swarm.



  




## Basic usage
```tsx

export function App() {
  return (
    
console.log('Pausing branch')} onResume={() => console.log('Resuming branch')} onQuarantine={() => console.log('Quarantining branch')} onCancel={() => console.log('Canceling branch')} onThrottle={() => console.log('Throttling branch speed')} />
); } ``` ## Props | Prop | Type | Default | Description | | :--- | :--- | :--- | :--- | | `branchName` | `string` | **Required** | The display name of the organizational branch or sub-tree. | | `status` | `'running' \| 'paused' \| 'quarantined'` | **Required** | The current execution state of this specific branch. | | `onPause` | `() => void` | `undefined` | Callback fired to halt execution on this branch. | | `onResume` | `() => void` | `undefined` | Callback fired to resume execution on this branch. | | `onQuarantine` | `() => void` | `undefined` | Callback fired to isolate this branch (e.g., cut off its network/API access). | | `onCancel` | `() => void` | `undefined` | Callback fired to permanently terminate all agents in this branch. | | `onThrottle` | `() => void` | `undefined` | Callback fired to artificially slow down the loop speed of this branch. | | `className` | `string` | `undefined` | Additional CSS class for the root element. | ## Solution Patterns `Branch Controls` is applied to sub-trees within an `Orchestrator View`: ```text Orchestrator View → Tree Node → [Branch Controls] ``` Rather than stopping the entire swarm, it pauses a specific branch of execution. ## Design rationale **1. Surgical Intervention** In a 20-agent swarm, one agent hitting a bad API shouldn't crash the other 19. `Branch Controls` provides the surgical tools needed to manage a complex hierarchical system. If a "Scraper" branch is misbehaving, you can pause it, adjust the scraper prompt, and resume it, all while the "Summary" branch continues to process the data already collected. **2. The Quarantine Concept** Unlike "Pause" (which stops the agent from reasoning), "Quarantine" allows the branch to continue thinking but revokes its Write/Execute permissions. This is a critical debugging state: it lets the human observe *what the agent wants to do next* without actually letting it do it. **3. State-Driven UI** The visible buttons dynamically swap based on the `status` prop. If the branch is `running`, the user sees Pause and Quarantine. If it's `paused`, they see Resume. This prevents the supervisor from clicking invalid state transitions during a fast-moving escalation. --- --- title: Budget Meter description: Visual gauge showing session budget vs. burn rate. badge: Primitive --- Answers: [Budget](/docs/lexicon#budget). ## Install ```bash npx ax-depute@latest add budget-meter ``` ```bash pnpm dlx ax-depute@latest add budget-meter ``` ```bash yarn dlx ax-depute@latest add budget-meter ``` ```bash bunx ax-depute@latest add budget-meter ``` ## Overview Delegation requires guardrails. Instead of blocking every action, `Budget Meter` allows users to grant agents an explicit budget (API tokens, currency, or API call limits) and tracks the real-time burn rate. It automatically calculates severity thresholds to warn users before the budget is exhausted. ## Basic Usage ```tsx ``` ## Solution Patterns Integrate `BudgetMeter` directly into a `DelegationGate` prior to spawning a new agent to enforce explicit limits, or embed it persistently within `RunControls` alongside pause/stop actions to maintain situational awareness of a running swarm. ## Props | Prop | Type | Default | Description | |------|------|---------|-------------| | `label` | `string` | — | Human-readable label | | `spent` | `number` | — | Current amount consumed | | `limit` | `number` | — | Maximum budget allowance | | `unit` | `'currency' \| 'tokens' \| 'api-calls' \| 'compute' \| 'custom'` | `'tokens'` | Unit type | | `burnRate` | `number` | — | Current burn rate per minute | | `estimatedTimeRemaining` | `string` | — | Human-readable time remaining | | `elevatedThreshold` | `number` | `60` | Percentage to trigger elevated state | | `criticalThreshold` | `number` | `85` | Percentage to trigger critical state | | `compact` | `boolean` | `false` | Render inline variant | ## Design rationale **Why proportional thresholds?** Raw numbers (e.g., "45,000 tokens") are meaningless without context. Auto-calculating elevated (>60%) and critical (>85%) severity colors translates abstract numbers into actionable visual urgency. --- --- title: Capability Matrix description: Permission inspector showing allowed and denied capabilities. badge: Primitive --- Answers: [Capability](/docs/lexicon#capability). ## Install ```bash npx ax-depute@latest add capability-matrix ``` ```bash pnpm dlx ax-depute@latest add capability-matrix ``` ```bash yarn dlx ax-depute@latest add capability-matrix ``` ```bash bunx ax-depute@latest add capability-matrix ``` ## Overview `Capability Matrix` is the "Agent Handshake." As products explicitly declare their tools to agents via frameworks like WebMCP, humans need to see that exact programmatic contract. This component visualizes what an agent is capable of doing in the current specific operating context. ## Basic Usage ```tsx ``` ## Solution Patterns Render `CapabilityMatrix` inside a `DelegationGate` when an agent is spawned, ensuring the user understands the absolute bounds of the agent's authority before letting it execute. ## Props | Prop | Type | Default | Description | |------|------|---------|-------------| | `title` | `string` | — | Title of the matrix | | `agentId` | `string` | — | Agent identity label | | `capabilities` | `Capability[]` | — | List of defined permissions | | `groupByCategory` | `boolean` | `true` | Group capabilities by category | | `highlightDenied` | `boolean` | `true` | Emphasize denied/none permissions | ## Design rationale **Why `highlightDenied`?** In security, knowing what an agent *cannot* do is often more important than what it can. Visually elevating explicit denials (e.g., "Write to Production: Denied") builds trust that guardrails are actively in place. --- --- title: Confidence Meter description: Show how confident the agent is in its next step. badge: Primitive --- Answers: [Automation Bias](/docs/lexicon#automation-bias), [Hallucinated Planning](/docs/lexicon#hallucinated-planning). ## Install ```bash npx ax-depute@latest add confidence-meter ``` ```bash pnpm dlx ax-depute@latest add confidence-meter ``` ```bash yarn dlx ax-depute@latest add confidence-meter ``` ```bash bunx ax-depute@latest add confidence-meter ``` ## Overview Displays an agent's confidence score with optional reasoning. Supports a full `meter` display (a horizontal bar) as well as a compact `badge` display for tight spaces like roster rows in `Subagent Card`. ## Basic usage ```tsx ``` ## Compact Badge Display For tight UI spaces like tables or agent rosters, use the `badge` variant. ```tsx ``` ## Props | Prop | Type | Default | Description | |------|------|---------|-------------| | `value` | `number` | `undefined` | Confidence score from 0-100. If omitted, meter shows an indeterminate pulsing state. | | `display` | `'meter' \| 'badge'` | `'meter'` | Structural variant: full horizontal bar (`meter`) or a compact inline pill (`badge`). | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Size of the component. | | `showValue` | `boolean` | `true` | Whether to show the exact numeric percentage. | | `showLabel` | `boolean` | `true` | Whether to display a textual confidence category (e.g., "High", "Medium", "Low"). | | `reasoning` | `string` | `undefined` | An optional explanation from the agent justifying its confidence score. | | `animate` | `boolean` | `true` | Whether to animate the bar filling and color transitions when the value changes. | ## When to use - The agent's confidence in its next action is meaningful signal — e.g., before an `Approval Gate` where confidence should influence the human's decision - The agent is operating in a domain with variable accuracy (medical, legal, financial) where uncertainty carries real stakes - You want to preemptively surface a human review trigger: if confidence drops below a threshold, escalate automatically ## When not to use - Your agent backend doesn't produce calibrated confidence scores — displaying a fabricated or uncalibrated number is actively misleading and erodes trust - The operation is routine and fully reversible — injecting a confidence signal for low-stakes actions adds noise without value - The agent has already completed the action — `Confidence Meter` communicates intent before execution, not retrospective certainty ## Accessibility - The meter renders as `` (native HTML) with `min`, `max`, and `value` attributes set, giving screen readers built-in percentage readout - The confidence label (High / Medium / Low) is always present as visible text, not conveyed through color alone - Color differentiation (green / amber / red) meets WCAG 3:1 minimum contrast ratio against the background - Reasoning text is rendered as a visible `

` and not hidden behind a tooltip — no hover-only content - Badge variant includes `aria-label="Confidence: 42%"` for screen reader clarity in dense layouts ## Solution Patterns `Confidence Meter` is typically evaluated continuously during an agent's runtime, often surfaced right before an `Approval Gate`: ```text Plan Card → [Confidence Meter] → Approval Gate → Run Controls ``` If confidence drops below a specified threshold, the flow can be automatically paused for human review. ## Design rationale **Why quantitative trust signaling?** Humans struggle to calibrate trust in LLMs. Without a signal, every agent response carries the same implicit weight — whether the model is 95% confident or guessing. Surfacing a score *before* execution creates a moment of deliberate comparison: the human sees the number, and that number reframes how they read the output. A 58% confidence on a financial recommendation is a different document than a 96% one. **Why the `reasoning` prop?** A score without rationale is still partially opaque. An agent that outputs `58%` with no explanation is almost as unhelpful as no score at all. The `reasoning` prop gives the agent space to surface what it's uncertain about — missing context, competing interpretations, ambiguous inputs. That explanation is what makes the confidence score actionable rather than decorative, and what gives the human something to actually verify. --- --- title: Decision Record description: Immutable visual receipt of a human approval decision to counteract Responsibility Diffusion. Who approved, why, and under what policy. badge: Control --- Answers: who approved — [Responsibility Diffusion](/docs/lexicon#responsibility-diffusion), [Decision Record](/docs/lexicon#decision-record), [Who approved](/docs/lexicon#who-approved), [Audit Triad](/docs/lexicon#audit-triad), [L3 Supervised](/docs/lexicon#l3-supervised). ## Install ```bash npx ax-depute@latest add decision-record ``` ```bash pnpm dlx ax-depute@latest add decision-record ``` ```bash yarn dlx ax-depute@latest add decision-record ``` ```bash bunx ax-depute@latest add decision-record ``` ## The Audit Triad `DecisionRecord` is one of three audit-layer components. Each captures a different moment in the accountability chain: | Component | Scope | Records | Question it answers | |-----------|-------|---------|---------------------| | **Decision Record** | Per-approval | Who approved, why, and under what policy | *"Who authorized this?"* | | [**Transaction Receipt**](/docs/components/transaction-receipt) | Per-action | What the machine did, with verification hash | *"What actually happened?"* | | [**Session Overview**](/docs/components/session-overview) | Per-session | Semantic rollup of everything the agent touched | *"What was the total blast radius?"* | Use all three together for full audit coverage: `DecisionRecord` captures the human side, `TransactionReceipt` captures the machine side, and `SessionOverview` captures the session-level summary. ## Basic usage Use `` to log a human's active oversight of an agentic workflow. While the agent executes actions, you need an immutable record of *who* authorized it and *why*. ```tsx export function AuditLog() { return ( ); } ``` ## Props | Prop | Type | Default | Description | |------|------|---------|-------------| | `decision` | `'approved' \| 'rejected' \| 'modified'` | — | The final human decision | | `approver` | `{ name: string, role?: string, timestamp: Date \| string }` | — | The human who made the decision | | `agentContext` | `{ intent: string, policyInvoked?: string }` | — | The agent intent and policy at the time | | `humanReasoning` | `string` | — | Optional human reasoning for the decision | The component intentionally requires strict object shapes to ensure the audit log is semantically complete for role-based access control (RBAC) environments. ## Solution Patterns ### The Responsibility Terminal Embed the `DecisionRecord` at the end of every `ApprovalGate` flow. If the user clicks "Approve", the final screen rendered should be the immutable receipt. ```text Action Propsed → [Approval Gate] → (Approves) → [Action Executes] → [Decision Record] ``` This closes the "Execution Amnesia" loop by confirming to the user that their identity is now bound to the output. ## Design rationale **Why not just use `TransactionReceipt`?** A `TransactionReceipt` logs what the *machine* did (e.g., "Deployed smart contract `0x123` at block `8841`"). A `DecisionRecord` logs what the *human* did (e.g., "Alice approved the contract deployment because the Q/A tests passed"). In enterprise and high-compliance environments, "Responsibility Diffusion" happens when humans blindly click approve because they aren't explicitly reminded that their identity is being audited. By forcing an explicit, formal, visual receipt of *their* decision, we heighten their scrutiny on the next request. --- --- title: Delegation Gate description: Approval surface for spawning a new autonomous sub-agent. badge: Control --- Answers: [Mandate](/docs/lexicon#mandate), [L2 Collaborative](/docs/lexicon#l2-collaborative). ## Install ```bash npx ax-depute@latest add delegation-gate ``` ```bash pnpm dlx ax-depute@latest add delegation-gate ``` ```bash yarn dlx ax-depute@latest add delegation-gate ``` ```bash bunx ax-depute@latest add delegation-gate ``` ## Overview A specialized approval surface explicitly designed for the creation of new autonomous entities. It surfaces the proposed agent's mandate, tool constraints, and forecasted economic cost before the agent is allowed to execute. ## Basic usage ```tsx export function App() { const proposedAgent = { role: 'Financial Analyst', mandate: 'Read Q3 earnings reports and extract revenue metrics into a CSV.', allowedTools: ['read_file', 'write_csv'], maxDepth: 10, estimatedTokens: 15000, estimatedCost: '$0.25' }; return (

console.log('Sub-agent authorized')} onDeny={() => console.log('Spawn request denied')} />
); } ``` ## Props | Prop | Type | Default | Description | | :--- | :--- | :--- | :--- | | `requestingAgent` | `string` | **Required** | The name or ID of the parent agent requesting to spawn the child. | | `proposedSubagent` | `Object` | **Required** | Details about the sub-agent being proposed (see Type below). | | `onApprove` | `() => void` | **Required** | Callback fired when the user authorizes the creation of the sub-agent. | | `onDeny` | `() => void` | **Required** | Callback fired when the user rejects the creation of the sub-agent. | | `className` | `string` | `undefined` | Additional CSS class for the root element. | ## Types ### `ProposedSubagent` ```typescript export interface ProposedSubagent { role: string; // Display role, e.g., "Financial Analyst" mandate: string; // The specific instructions given to the new agent allowedTools?: string[]; // Sandbox constraints: which tools it can access maxDepth?: number; // Maximum number of reasoning steps before timeout estimatedTokens: number; // Forecasted token burn estimatedCost: string; // Forecasted USD cost, e.g., "$0.25" } ``` ## Solution Patterns ## Solution Patterns `Delegation Gate` intercepts an orchestrator right before it spawns a new worker. **Authorization is not just approval.** Because approving an agent is an authorization of *autonomy* (not just a single action), it represents a significantly higher-stakes decision. We strongly recommend wrapping this in `AutomationBiasAlert` to prevent "rubber-stamping" of agent authorizations: ```text Orchestrator View → [AutomationBiasAlert → Delegation Gate] → Subagent spawned ``` It ensures human oversight before compute is multiplied. ## Design rationale **1. Intent vs. Autonomy** `Approval Gate` (v0) is used before an agent takes a specific, discrete action. `Delegation Gate` (v1) is used before an agent *creates another agent*. Approving an action validates intent; approving an agent authorizes capacity. The UI reflects this shift from operational to structural decision-making. **2. The "Box" Model (Sandboxing)** When humans manage humans, they create boundaries via job descriptions. When humans manage AI, they create boundaries via constraints. The `allowedTools` and `maxDepth` fields explicitly visualize the "sandbox" the new agent will be trapped in, increasing human trust that the sub-agent cannot escape its mandate. **3. Forecasted Economics** Agents aren't just code; they are active compute consumers. Displaying `estimatedCost` directly on the spawn request shifts the UI from purely operational to financial, preventing "infinite loop" surprises on the monthly bill. --- --- title: Escalation Router description: Alert feed for sub-agent failures with routing options. badge: Control --- ## Install ```bash npx ax-depute@latest add escalation-router ``` ```bash pnpm dlx ax-depute@latest add escalation-router ``` ```bash yarn dlx ax-depute@latest add escalation-router ``` ```bash bunx ax-depute@latest add escalation-router ``` ## Overview A high-severity intervention surface. When an agent critically fails (e.g., gets stuck in a loop, hits a rate limit, or crashes), `Escalation Router` surfaces the error trace and provides the human supervisor with three deterministic resolution paths: Retry, Reassign, or Cancel. ## Basic usage ```tsx export function App() { return (
console.log('Retrying task on same agent...')} onReassign={() => console.log('Opening reassignment modal...')} onCancelBranch={() => console.log('Killing branch_7A')} />
); } ``` ## Props | Prop | Type | Default | Description | | :--- | :--- | :--- | :--- | | `failedAgent` | `string` | **Required** | The name or ID of the agent that encountered the critical error. | | `errorSummary` | `string` | **Required** | A human-readable, single-sentence summary of what went wrong. | | `onRetry` | `() => void` | **Required** | Callback fired when the human chooses to restart the failed task on the same agent. | | `onReassign` | `() => void` | **Required** | Callback fired when the human chooses to route the task to a different agent. | | `onCancelBranch` | `() => void` | **Required** | Callback fired to terminate the task and explicitly fail the workflow branch. | | `branchId` | `string` | `undefined` | The specific execution branch or thread ID associated with the task. | | `errorTrace` | `string` | `undefined` | The raw system error, API response, or stack trace (rendered in a dark-themed code block). | | `recommendation` | `'retry' \| 'reassign' \| 'cancel'` | `undefined` | The orchestrator's suggestion for how the human should resolve the issue (highlights the primary button). | | `className` | `string` | `undefined` | Additional CSS class for the root element. | ## Solution Patterns `Escalation Router` surfaces hard blockers from deep within the swarm up to the human supervisor: ```text Failed Subagent → [Escalation Router] → Human Override ``` It allows the user to re-route or manually resolve the blocker. ## Design rationale **1. The "Three-Way Intersection"** When autonomous systems fail, they often just stop or loop infinitely. `Escalation Router` forces the system to pause and present a clear three-way intersection to the human: Try Again (transient errors), Give to Someone Else (capability errors), or Give Up (bad intent/unsolvable). **2. Visual Urgency** This is one of the few components in the library that uses aggressive Red styling by default. It acts as an `alertdialog`, breaking the user out of passive monitoring and demanding active resolution. **3. Orchestrator Recommendations** If the orchestrator is intelligent enough to know *why* an agent failed (e.g., a 429 Rate Limit), it can use the `recommendation` prop. This highlights the "Retry" button as the primary action, turning the human into a simple "Approve" clicker rather than forcing them to diagnose the trace themselves. --- --- title: Handoff Protocol description: Structured comprehension UI for context transfers between agents. badge: Pattern --- ## Install ```bash npx ax-depute@latest add handoff-protocol ``` ```bash pnpm dlx ax-depute@latest add handoff-protocol ``` ```bash yarn dlx ax-depute@latest add handoff-protocol ``` ```bash bunx ax-depute@latest add handoff-protocol ``` ## Overview A "Comprehension UI" that visualizes the transfer of state between two agents (or an agent and a human). It clearly delineates the source, destination, assigned goal, and the exact payload being transferred. ## Basic usage ```tsx export function App() { const payload = [ { label: 'Scraped URLs', value: '42 pages processed' }, { label: 'Extraction Rule', value: 'Find pricing tables' }, { label: 'Cost Incurred', value: '$0.45' } ]; return (
console.log('Handoff proceeds')} onIntercept={() => console.log('Human takes over')} onCancel={() => console.log('Handoff cancelled')} />
); } ``` ## Props | Prop | Type | Default | Description | | :--- | :--- | :--- | :--- | | `sourceAgent` | `string` | **Required** | The name or ID of the agent sending the context. | | `destinationAgent` | `string` | **Required** | The name or ID of the agent (or human) receiving the context. | | `goal` | `string` | **Required** | The high-level intent behind this specific transfer of control. | | `summary` | `string` | **Required** | A readable description from the source agent of what has been accomplished so far. | | `payload` | `HandoffPayloadItem[]` | `undefined` | Key-value pairs representing the structured data being passed. | | `nextRequest` | `string` | `undefined` | Explicit instructions from the source agent to the destination agent. | | `canIntercept` | `boolean` | `false` | If true, renders the action buttons allowing the human to Accept, Intercept, or Cancel the transfer. | | `onAccept` | `() => void` | `undefined` | Callback fired when the user allows the handoff to proceed. | | `onIntercept` | `() => void` | `undefined` | Callback fired when the user decides to take over the task manually or reroute it. | | `onCancel` | `() => void` | `undefined` | Callback fired when the user cancels the handoff entirely. | | `className` | `string` | `undefined` | Additional CSS class for the root element. | ## Types ### `HandoffPayloadItem` ```typescript export interface HandoffPayloadItem { label: string; value: string; } ``` ## Solution Patterns `Handoff Protocol` sits securely between two agents when ownership or state transfers: ```text Source Agent → [Handoff Protocol] → Destination Agent ``` It gives the human a chance to intercept the transfer before the next agent begins. ## Design rationale **1. Comprehension Over Logging** Agent handoffs are usually hidden deep in terminal logs (`Agent A passed context to Agent B`). `Handoff Protocol` pulls this event out of the log and formats it as a formal "shipping manifest," drastically increasing the human supervisor's situational awareness. **2. Not Inherently a Gate** Unless `canIntercept` is `true`, this component is purely a *Comprehension UI*. It exists to be read, not clicked. In full autonomous mode, these cards stream by as a verifiable record of context transfer. **3. The Intercept Hook** When an AI orchestrator realizes it is stuck or routing incorrectly, it can use the `Handoff Protocol` with `canIntercept={true}`. The "Intercept" action allows the human to break the chain, take the accumulated context, and manually complete or reroute the task. --- --- title: Orchestrator View description: Visualize the full agent hierarchy as a collapsible tree. badge: View --- Answers: [Cascading Failures](/docs/lexicon#cascading-failures), [L4 Autonomous](/docs/lexicon#l4-autonomous). ## Install ```bash npx ax-depute@latest add orchestrator-view ``` ```bash pnpm dlx ax-depute@latest add orchestrator-view ``` ```bash yarn dlx ax-depute@latest add orchestrator-view ``` ```bash bunx ax-depute@latest add orchestrator-view ``` ## Overview A recursive tree graph representing the Orchestrator and all of its spawned worker sub-agents. It provides a macro-view of the swarm's structure and highlights blocked or failed nodes that require human attention. ## Basic usage ```tsx const mockSwarm: OrchestratorNode[] = [ { id: 'orch_1', label: 'Main Router', role: 'Orchestrator', status: 'working', currentTask: 'Delegating work to sub-agents...', children: [ { id: 'sub_1', label: 'Data Researcher', role: 'Search API', status: 'completed', }, { id: 'sub_2', label: 'Code Writer', role: 'React Expert', status: 'blocked', currentTask: 'Waiting for missing API key', } ] } ]; export function App() { const [selectedId, setSelectedId] = useState('orch_1'); return (
setSelectedId(node.id)} />
); } ``` ## Props | Prop | Type | Default | Description | | :--- | :--- | :--- | :--- | | `nodes` | `OrchestratorNode[]` | `undefined` | Hierarchical tree data. Usually contains a single root node representing the main orchestrator agent. | | `onNodeClick` | `(node: OrchestratorNode) => void` | `undefined` | Callback fired when the user clicks on an individual node in the tree. | | `selectedNodeId` | `string` | `undefined` | The `id` of the currently selected node, used to highlight the active agent in the tree. | | `className` | `string` | `undefined` | Additional CSS class for the root element. | ## Types ### `OrchestratorNode` ```typescript export type AgentStatus = 'idle' | 'working' | 'blocked' | 'failed' | 'completed'; export interface OrchestratorNode { id: string; label: string; status: AgentStatus; role?: string; currentTask?: string; children?: OrchestratorNode[]; } ``` ## Solution Patterns `Orchestrator View` acts as the navigation tree for a complex, hierarchical swarm. - Use it as the left-pane side navigation in a specialized dashboard. - Pair it with **Swarm Monitor** at the top of the viewport for aggregate metrics spanning the entire tree. - When an individual node is clicked (`onNodeClick`), render a **Plan Card** + **Tool Trace** + **Run Controls** trio in the main right-hand pane to inspect that specific sub-agent. ## Design rationale **1. The Macro/Micro Split** When multiple agents are running in a swarm, a single terminal log or chat thread becomes impossible to follow. `Orchestrator View` serves as the "macro" view—a structural map of *who* is doing what. Clicking a node typically updates an adjacent pane with the "micro" view (a standard `Plan Card` + `Tool Trace` for that specific agent). **2. Exception Highlighting** The tree naturally collapses cognitive load by burying successful (`completed`) and waiting (`idle`) agents. However, `blocked` and `failed` nodes use high-contrast color codes to draw the supervisor's eye directly to the nodes requiring intervention, regardless of how deep they are nested. **3. Depth** Nesting is the indent and the dashed guide beside a child list. A node does not get a colored side stripe. Its state is the dot and the status label. --- --- title: Plan Card description: Show the agent's proposed plan before it executes. Users see the trajectory before anything happens. badge: Primitive --- Answers: [Hallucinated Planning](/docs/lexicon#hallucinated-planning), [Plan-first](/docs/lexicon#plan-first). ## Install ```bash npx ax-depute@latest add plan-card ``` ```bash pnpm dlx ax-depute@latest add plan-card ``` ```bash yarn dlx ax-depute@latest add plan-card ``` ```bash bunx ax-depute@latest add plan-card ``` ## Overview `Plan Card` implements the plan-first pattern: show the trajectory, then execute. Before an agent takes any action, it proposes a plan — a numbered list of steps with confidence scores and assumptions. This lowers fear and increases informed consent. Users can see where they're going before anything happens. ## Basic usage ```tsx ``` ## With mock data ```tsx const plan = generateMockPlan(4); // 4-step plan ``` ## Live execution state When the agent is running, pass `activeStepId` to highlight the current step: ```tsx ``` ## Streaming state When steps are still being generated by a streaming backend, pass `isStreaming`. This adds `data-streaming="true"` to the root element — no built-in animation. Style it however the host product expects: ```tsx ``` ```css /* Host product controls the visual */ [data-streaming="true"] .plan-card-title::after { content: "…"; animation: pulse 1s infinite; } ``` ## Per-step reasoning When each `PlanStep` has a `reasoning` string, opt-in to collapsible reasoning toggles with `showReasoning`. Set `defaultExpandedStepId` to pre-expand a specific step on mount: ```tsx ``` ## Props | Prop | Type | Default | Description | |------|------|---------|-------------| | `steps` | `PlanStep[]` | **Required** | Ordered list of plan steps | | `title` | `string` | **Required** | Title of the plan | | `assumptions` | `string[]` | `undefined` | Agent's stated assumptions | | `reasoning` | `string` | `undefined` | Agent's overall reasoning (collapsible) | | `activeStepId` | `string` | `undefined` | ID of the currently executing step | | `showConfidence` | `boolean` | `false` | Show confidence badge per step | | `isStreaming` | `boolean` | `false` | Signals that steps are still being generated. Adds `data-streaming="true"` to the root element — no built-in animation; style via CSS. | | `showReasoning` | `boolean` | `false` | Renders a collapsible reasoning toggle on each step that has a `reasoning` string. | | `defaultExpandedStepId` | `string` | `undefined` | ID of the step whose reasoning is expanded by default (uncontrolled). Follows the `activeStepId` pattern. | ## PlanStep type ```ts interface PlanStep { id: string; label: string; status: 'pending' | 'active' | 'completed' | 'failed'; confidence?: number; // 0–1 } ``` ## When to use - The agent is about to take a multi-step or multi-tool action and the user should be aware of the trajectory before it begins - Trust is low or the action surface is new — surfacing the plan early builds informed consent - The agent's intent is ambiguous without a plan (e.g., "refactor this codebase" covers too many possibilities) - You want to give the user a natural moment to abort before any irreversible step starts ## When not to use - The agent is performing a single, trivially understood action (e.g., "look up the weather") — a full plan card adds friction without value - The agent's actions are happening fully in the background with no synchronous human checkpoint; use `Tool Trace` for passive monitoring instead - You are already showing a `Decision Record` that captures the full approved plan — avoid duplicating plan state in both components ## Accessibility - Uses semantic `
    ` for step lists; each step renders as `
  1. ` with `role="listitem"` - Active step is annotated with `aria-current="step"` to assist screen reader navigation - Completed and failed steps carry `aria-label` values that include their status (e.g., "Step 2: Complete. Write schema migration.") - Streaming state is announced via `aria-live="polite"` on the container when `isStreaming` is true - All collapsible reasoning toggles use `