K

Explore

Agent Templates

Build

/21st SDK vs TerminalUse

21st SDK vs TerminalUse: A Deep Architectural Comparison

A comprehensive analysis of two AI agent deployment platforms - comparing architecture, runtime, deployment, streaming, UI, state management, security, and developer experience.

serafimcloud
serafimcloud
@serafimcloud

TL;DR

21st SDK and TerminalUse both solve the same fundamental problem: deploying production AI agents. But they take very different architectural paths to get there. 21st SDK is a TypeScript-first, component-driven platform built around the Claude Code runtime with a drop-in React chat UI. TerminalUse is a Python-first, Kubernetes-native platform designed as "Vercel for background agents" with a filesystem-centric model.

This article breaks down every architectural decision, feature, and trade-off between the two platforms.


Architecture Philosophy

The two platforms diverge fundamentally in how they think about what an "agent" is.

21st SDK: Relay + E2B Sandbox

21st SDK uses a Relay architecture. When a user sends a message:

  1. Your app calls the Chat API
  2. The Relay (runtime service) authenticates the request, resolves agent config
  3. Relay provisions an E2B sandbox (isolated Linux environment)
  4. The agent runtime (Claude Code / Codex) starts inside the sandbox
  5. User tools + MCP servers are loaded
  6. Response streams back via SSE (Server-Sent Events)

The Relay is the intermediary that handles auth, routing, sandbox provisioning, token counting, cost tracking, and session persistence. Developers never interact with the Relay directly - the SDK handles it.

TerminalUse: Kubernetes + Bubblewrap

TerminalUse uses a Kubernetes-native architecture with 11 foundational primitives:

  1. Namespace - top-level isolation (gets its own K8s namespace, GCS bucket, GCP service account)
  2. Project - collaboration boundary
  3. Filesystem - persistent files mounted at /workspace
  4. Agent - a deployed Python runtime
  5. Environment - deployment policies (production, preview)
  6. Branch - deployment slot tied to git branches
  7. Version - immutable build artifact
  8. Task - one running conversation
  9. Event - input to tasks
  10. Message - output from agents
  11. State - per-task persisted JSON

Two operational loops: Deploy Loop (code -> tu deploy -> version -> environment) and Run Loop (filesystem -> task -> event -> message -> filesystem).

Key Difference

21st SDK abstracts away infrastructure entirely - you don't think about containers, replicas, or orchestration. TerminalUse exposes infrastructure as first-class primitives - you manage namespaces, branches, versions, and replica counts directly.


Agent Definition & Languages

21st SDKTerminalUse
Primary languageTypeScript/JavaScriptPython
Additional languagesGo (full support), Python (server SDK only)TypeScript (app SDK only)
Agent definitionagents/<slug>/index.ts with agent() config wrappersrc/agent.py with AgentServer() class + lifecycle hooks
Config formatCode-as-config (TypeScript)config.yaml + Python code
Scaffoldingnpx @21st-sdk/cli init scaffolds agent directorytu init generates project structure

21st SDK Agent Definition

agents/my-agent/index.ts
import { agent, tool } from "@21st-sdk/agent"
import { z } from "zod"

export default agent({
  model: "claude-sonnet-4-6",
  runtime: "claude-code",
  systemPrompt: "You are a helpful assistant.",
  permissionMode: "bypassPermissions",
  maxTurns: 30,
  maxBudgetUsd: 2,
  tools: {
    search: tool({
      description: "Search docs",
      inputSchema: z.object({ query: z.string() }),
      execute: async ({ query }) => ({
        content: [{ type: "text", text: "results" }],
      }),
    }),
  },
})

TerminalUse Agent Definition

# src/agent.py
from terminaluse.lib import AgentServer, TaskContext

server = AgentServer()

@server.on_create
async def handle_create(ctx: TaskContext):
    await ctx.state.create({"status": "started"})
    await ctx.messages.send("Welcome!")

@server.on_event
async def handle_event(ctx: TaskContext, event):
    state = await ctx.state.get() or {}
    await ctx.state.update({"turns": state.get("turns", 0) + 1})
    await ctx.messages.send("Processed your message")

@server.on_cancel
async def handle_cancel(ctx: TaskContext):
    pass

Key Difference

21st SDK uses a declarative approach - you declare what the agent is (model, tools, prompt) and the platform handles the lifecycle. TerminalUse uses an imperative approach - you write lifecycle hooks (on_create, on_event, on_cancel) that control exactly what happens at each stage.


Runtime & Model Support

Both platforms support Claude and OpenAI models, but differ in how they expose the runtime and what comes out of the box.

21st SDKTerminalUse
Runtime approachManaged - platform runs Claude Code / Codex runtime for youBYO - you call Claude SDK or Codex SDK from your Python code
Supported modelsAny model via OpenRouter (Claude, GPT, Gemini, GLM, etc.)Any model - you import the SDK you need
Model switchingRuntime toggle for end users, per-request overrideDeveloper-controlled in code
Built-in toolsBash, Read, Write, Edit, Glob, Grep, WebSearch, WebFetchNo built-in tools (BYO)
Custom toolsZod-schema typed tools in TypeScriptPython functions via ADK
MCP supportFull MCP protocol via .mcp.jsonNot documented

Built-in Tools Comparison

21st SDK ships with 8 built-in tool categories that are enabled by default when using the Claude Code runtime:

  • Read-only: Read, Glob, Grep (file search and read)
  • Edit: Edit, Write (create and modify files)
  • Execution: Bash (run shell commands)
  • Web: WebFetch, WebSearch (fetch URLs and web search)

TerminalUse does not include built-in tools - you bring your own via the Agent Development Kit (ADK) or connect external SDKs (Claude Agent SDK, Codex Agent SDK).


Sandbox & Execution Environment

21st SDKTerminalUse
Sandbox technologyE2B (dedicated microVMs)Bubblewrap (Linux namespaces)
Isolation levelFull VM-level isolationProcess-level namespace isolation
SpecsUp to 8 CPU, 8 GB RAMNot publicly documented
Pre-installed toolsNode 24, git, curl, ripgrep, GitHub CLIDepends on Dockerfile
PersistenceSandbox persists across messages, destroyed on idleFilesystem persists independently of tasks
Filesystem modelPer-sandbox filesystemShared filesystem entity, mountable across tasks
Concurrent access"Last user wins" semanticsConditional writes with version-based concurrency
Network accessFull (web search, API calls, git clone)Full (maintained for model APIs and external services)

Filesystem Philosophy

This is one of the most significant architectural differences:

21st SDK: The sandbox IS the filesystem. Each sandbox has its own isolated filesystem that persists across messages within that sandbox. When the sandbox is destroyed, the filesystem is gone.

TerminalUse: Filesystems are independent entities that can be created, shared, mounted (writable, read-only, or tmpfs), and persisted across multiple tasks and agents. Multiple agents can share the same filesystem. Files are backed by Google Cloud Storage with checksums for change detection.

TerminalUse's filesystem model is more powerful for workflows where multiple agents need to collaborate on shared files, or where file state needs to survive across many task lifecycles.


Deployment

21st SDKTerminalUse
Deploy commandnpx @21st-sdk/cli deploytu deploy
Build systemesbuild (JS/TS) or Go toolchainDocker container build
TargetE2B sandbox templateKubernetes deployment
EnvironmentsVia --name flag (e.g. --name my-agent-staging)Named environments in config.yaml (production, preview)
Branch mappingManual via --nameAutomatic: main -> production, others -> preview
VersioningAuto-incrementing versions with status trackingImmutable versions with status tracking
Rollbacknpx @21st-sdk/cli rollback to switch active versiontu rollback to restore version + secrets snapshot
ReplicasManaged by platformConfigurable 1-10 replicas per environment
Task stickinessN/AConfigurable: tasks stay on old version or migrate

Deploy Pipeline Comparison

21st SDK (4 steps):

  1. Bundle - CLI bundles with esbuild
  2. Upload - bundle + metadata uploaded
  3. Sandbox - platform prepares E2B sandbox template
  4. Live - deployment is immediately live

TerminalUse (5 steps):

  1. Build - CLI builds Docker container
  2. Push - image pushed to Google Artifact Registry
  3. Deploy - platform creates K8s deployment
  4. Register - container starts and registers itself
  5. Ready - CLI polls until READY or FAILED

Key Difference

21st SDK optimizes for speed - deploy in seconds with zero Docker knowledge, with built-in versioning and rollback. TerminalUse optimizes for control - you get replica management, branch-to-environment mapping, and task stickiness policies, but you need Docker and the deploy is slower.


Streaming & API

Both platforms use Server-Sent Events (SSE) for streaming and are compatible with the Vercel AI SDK.

21st SDKTerminalUse
Streaming protocolSSESSE
AI SDK compatNative (useChat, createAgentChat)Via @terminaluse/vercel-ai-sdk-provider
Stream resumptionDedicated GET /stream endpointLast-Event-ID header
Stream cancellationDELETE /stream endpointPOST /tasks/{id}/cancel
AuthJWT token exchange (an_sk_ prefix)Bearer token (tu_ prefix)
ID prefixessb_ (sandbox), th_ (thread)No documented prefix convention

SSE Event Types

Both platforms stream rich, granular events -- not just text tokens.

21st SDK events (11 types):

  • start, finish, error
  • text-start, text-delta, text-end
  • tool-input-start, tool-input-delta (streaming tool input JSON)
  • tool-input-available (complete tool call), tool-output-available (tool result)
  • message-metadata (sessionId, totalCostUsd, tokens, duration)

TerminalUse events:

  • start, finish, error
  • start-step, finish-step (per-step token usage)
  • text-start, text-delta, text-end
  • reasoning-start, reasoning-delta, reasoning-end
  • tool-input-start/delta/end, tool-call, tool-result
  • handler-complete

Both protocols are comparable in richness. 21st SDK streams tool inputs and outputs as first-class events. TerminalUse adds explicit reasoning events and step-level boundaries.


Frontend & UI

21st SDKTerminalUse
Drop-in chat UIYes (<AgentChat> React component)No
Theming & customizationYes (CSS variables, presets, Theme Builder)No
Tool call visualizationsYes (file edits, terminal, web searches)No
Frontend SDK@21st-sdk/react, @21st-sdk/nextjs@terminaluse/sdk, @terminaluse/vercel-ai-sdk-provider

Key Difference

This is the largest gap between the two platforms. 21st SDK includes a production-ready chat UI with extensive theming, tool visualizations, and customization options. TerminalUse provides only SDKs - you build the entire UI yourself.

If you need a chat interface, 21st SDK saves weeks of frontend development. If you're building a backend-only agent (CI/CD pipelines, background jobs, data processing), TerminalUse's approach may be more appropriate.


State Management

21st SDKTerminalUse
Conversation modelSandbox -> Threads -> MessagesTask -> Events (in) / Messages (out)
State persistenceMessages stored per thread in databaseExplicit per-task JSON state via ctx.state
Multi-conversationMultiple threads within same sandboxOne task = one conversation
History managementRelay appends newest turn, SDK restores via client.threads.get()ADK provides adk.state CRUD
Cross-turn stateImplicit (sandbox filesystem + thread history)Explicit (developer manages ctx.state.create/get/update)

Key Difference

21st SDK manages state implicitly - the sandbox filesystem and thread history persist automatically. TerminalUse requires explicit state management - you call ctx.state.create(), ctx.state.get(), and ctx.state.update() to persist data across turns.


Cost Controls & Observability

21st SDKTerminalUse
Budget capYes (maxBudgetUsd per conversation)No
Turn limitYes (maxTurns)No
Token & cost trackingYes (per-turn tokens, total USD)Per-step token usage in SSE events
Web dashboardYes (sessions, costs, errors, live monitoring)Yes (app.terminaluse.com, details not publicly documented)
CLI logsYes (npx @21st-sdk/cli logs)Yes (tu logs)

Skills & Knowledge Management

21st SDKTerminalUse
Skills systemSKILL.md files, auto-discovered, on-demand contextNo equivalent
System promptsMax 4,000 chars, sent every turn, layerableNot documented as a platform feature
Per-request overridessystemPrompt, maxTurns, maxBudgetUsd, disallowedToolsNot documented

21st SDK's Skills system is unique - it provides structured knowledge management through filesystem-backed markdown files that are automatically discovered by the runtime and referenced on demand. This separates general instructions (system prompt) from detailed domain knowledge (skills).


Security & Access Control

21st SDKTerminalUse
Sandbox isolationE2B microVM (full VM-level)Bubblewrap (namespace-level)
Permission modesDefault, Accept Edits, Bypass AllNot documented
Env var handlingEncrypted, injected into sandbox runtime (not agent process)Managed via tu env, secrets snapshot on deploy
Auth mechanismAPI key -> JWT token exchangeAPI key + Webhook keys
Multi-tenant isolationPer-sandboxPer-namespace (K8s + GCS + GCP SA)
Access controlTeam-scoped API keysRole-based (discoverer/viewer/editor/owner/admin/executor)
Webhook verificationN/ADedicated webhook key system (internal, external, GitHub, Slack)

Key Difference

21st SDK uses VM-level isolation (E2B microVMs) which provides stronger security boundaries. TerminalUse uses process-level isolation (bubblewrap with Linux namespaces) which is lighter but has a smaller isolation boundary.

TerminalUse has a more granular access control system with role-based permissions, dual-parent authorization, and multiple authentication mechanisms. 21st SDK keeps it simpler with team-scoped API keys and permission modes.


CLI Comparison

Command21st SDK (npx @21st-sdk/cli, or 21st if installed globally)TerminalUse (tu)
Installnpx @21st-sdk/cliuv tool install terminaluse
Authloginlogin, logout, whoami
Scaffoldinitinit
Deploydeploydeploy
Rollbackrollbackrollback
Env varsenv list/set/removeenv add/ls/get/rm/pull/import
Logslogs with filterslogs with filters
Tasks-tasks create/send/list/pull/delete
Filesystem-fs create/push/pull/list
Projects-projects list/get/create/update/delete
Agentsagents, agents get/deleteagents ls/get/delete
Versionsversions / deploymentsls (list versions)

TerminalUse has a richer CLI with full CRUD operations for tasks, filesystems, and projects. 21st SDK's CLI is focused on the agent lifecycle: scaffold, deploy, rollback, manage agents, and inspect versions.


API Surface Area

21st SDKTerminalUse
Sandboxes/TasksCreate, Get, Delete sandboxCreate, List, Get, Update, Cancel, Migrate tasks
Sandbox OperationsExec command, Write files, Read file, Git clone-
Threads/EventsList, Create, Get, Delete threadsSend events, list events
Chat/MessagesSend message (SSE), Resume stream, Cancel streamSend event, stream SSE, list messages
FilesWrite/Read via sandbox APICreate filesystem, Upload/Download, Presigned URLs
StateImplicit (sandbox + thread)Full CRUD on per-task JSON state
AgentsList, Get, Delete agents-
DeployVia CLI, versionedVia CLI + API endpoint
VersionsList deployments, RollbackRedeploy, Rollback

TerminalUse has a larger API surface with more fine-grained control over every entity. 21st SDK's API covers the full agent lifecycle (deploy, version, rollback, manage) while abstracting away lower-level infrastructure.


When to Choose 21st SDK

  • You want a chat UI out of the box with theming and tool visualizations
  • Your agents are conversational (chatbots, assistants, support agents)
  • You prefer TypeScript/JavaScript for agent code
  • You want zero infrastructure management (no Docker, no K8s)
  • You need built-in Claude Code tools (Bash, file operations, web search)
  • You want fast deploys (seconds, not minutes)
  • You need cost controls (budget caps, turn limits) as platform features
  • You want per-request runtime overrides without redeploying
  • You need a rich observability dashboard with live monitoring
  • You need stronger security isolation (VM-level sandboxing, encrypted environment variables)

When to Choose TerminalUse

  • You need shared filesystems across multiple agents
  • You want full infrastructure control (replicas, branch mapping, task stickiness)
  • You need granular access control with roles and permissions
  • You need task migration between versions
  • You want conditional file writes with version-based concurrency
  • Your workflow requires the Deploy Loop + Run Loop model
  • You need explicit state management with per-task JSON state

Summary Table

Dimension21st SDKTerminalUse
PhilosophyAbstraction-first, code-as-configControl-first, infrastructure-as-primitives
LanguageTypeScript (+ Go)Python
SandboxE2B microVMsBubblewrap (Linux namespaces)
Deploymentesbuild -> E2B template (seconds), versioned with rollbackDocker -> Kubernetes (minutes)
Chat UIDrop-in <AgentChat> with 70+ theme varsBYO
Built-in tools8 tool categoriesNone
FilesystemPer-sandbox, ephemeralIndependent entity, persistent, shareable
StateImplicit (sandbox + threads)Explicit (per-task JSON CRUD)
Cost controlsmaxBudgetUsd, maxTurnsNot documented
ObservabilityDashboard + CLI logsCLI logs
Access controlTeam-scoped API keysRole-based with dual-parent auth
CLI richness8 command groups15+ command groups
API surface~15 endpoints~50+ endpoints
Skills systemSKILL.md auto-discoveryNo equivalent
StreamingSSE (11 event types, tool streaming)SSE (reasoning + step boundaries)
Best forConversational agents with UIBackground agents with file workflows
21st SDK vs TerminalUse: A Deep Architectural Comparison | 21st | 21st