Cedar OS

repository·main·Indexed 41 days ago

https://github.com/cedarcopilot/cedar-os

A React framework for building AI-native applications that bridges the gap between AI agents and application state. It provides a comprehensive suite of tools including a component library with over 35 UI elements, agentic state management via the useCedarState hook, and support for AI providers such as OpenAI, Anthropic, Mastra, and Vercel AI SDK. The ecosystem includes @cedar-os/backend for JSON schema extraction and cedar-os-cli for project scaffolding.

Tokens
157K
Snippets
420
Records
564
Agent score
51%

What's inside Cedar OS

  1. Overview of Cedar-OS

    main

    Cedar-OS is an open-source framework designed for building AI-native React applications. It aims to move applications beyond simple side-chatbots by providing deep integration between AI agents and the application itself.

    Key capabilities include:

    • Agentic State Access: Allowing agents to read and write to the application's local state.
    • Streaming & Tool Calls: Real-time rendering of message streaming and agent tool execution.
    • Diff & History Management: Tracking AI-driven changes, managing history, and implementing user approval workflows.
    • Context-Aware Mentions: A system for providing specific context to chat via mentions.
    • Spells: Specialized agent interactions and workflows.
    • Voice Integration: Support for voice-powered agent interactions.
    • Flexible UI: A library of pre-built, customizable components (Shadcn style) including Floating, SidePanel, Caption, or Embedded chat interfaces.
  2. Overview of Cedar-OS features

    main

    Cedar-OS is an open-source React framework designed for building AI-native applications. It provides the building blocks for sophisticated AI interactions, including:

    Core AI Capabilities

    • Diff & History: Track and display state changes made by the AI, allowing users to approve or reject changes.
    • Voice Integration: Enables voice-powered agent interactions.
    • Mentions: A system for controlling agent context via user state.
    • Spells: Methods to interact with the agent outside of the standard chat interface.

    UI and Integration Building Blocks

    • State Access: Allows agents to read and write to your application state.
    • Chat Components: Pre-built UI components including Floating, SidePanel, Caption, and Embedded chat layouts.
    • Streaming & Tool Calls: Support for real-time message streaming and rendering agent tool execution.
    • Agent Connection Modules: Modules to connect your application to various AI backends.
    • Component Library: A library of pre-built UI components optimized for AI-native interfaces.
  3. Explore Cedar-OS core AI features

    main

    Cedar-OS provides several specialized features for building AI-native applications:

    • Agent State and Actions: Allows AI agents to read and modify your React state in real-time. This includes making state accessible to AI, defining how AI can modify data, and managing advanced agent context.
    • Spells: A system for creating contextual, gesture-based interactions. Spells bind keyboard shortcuts, mouse gestures, and selection events to custom UI behaviors and actions.
    • Voice: Built-in support for natural voice interactions, including recording and AI response playback.
    • MCP Integration: Both Cedar and Mastra support Model Context Protocol (MCP) servers, allowing you to connect your application to tools like Cursor.
  4. How ChatBubbles handles message grouping and scrolling

    main

    Message Grouping

    The component visually groups consecutive messages from the same sender to reduce visual clutter:

    • First message in a group: Uses full spacing (mt-2).
    • Consecutive messages from the same sender: Uses reduced spacing (mt-1).
    • Different senders: Triggers full spacing (mt-2) between groups.

    Auto-Scrolling

    • Initial render: Automatically scrolls to the bottom using useLayoutEffect.
    • New messages: Performs a smooth scroll to the bottom whenever the message list changes.

    Typing Indicator

    When the isProcessing state is true in the Cedar store, the component displays an animated typing indicator positioned as an assistant message.

  5. Understand Context Tokenization for different Provider types

    main

    Cedar's sendMessage function handles context differently depending on whether you are using a structured provider or a text-based provider.

    Structured Providers (e.g., Mastra, Custom)

    Context is sent as separate fields. The prompt contains clean user text, and additionalContext contains a structured data object.

    • prompt: state.stringifyEditor()
    • additionalContext: state.compileAdditionalContext()

    Text-Based Providers (e.g., OpenAI, Anthropic, AI-SDK)

    Context is merged into a single unified prompt string.

    • prompt: state.stringifyInputContext() (A combined string containing both user text and the additional context data).
  6. Understand default agent response types and processors

    main

    Cedar OS automatically handles several response types via default processors. When an agent returns a response, the corresponding processor executes logic to update the application state or UI.

    Available Default Types:

    • "message": Adds text messages to the chat. Requires content: string and optional role: 'user' | 'assistant' | 'bot'.
    • "setState": Executes state actions via setters. Requires stateKey: string, setterKey: string, and optional args: unknown.
    • "progress_update": Manages progress message lifecycles (creating or updating existing messages). Requires text: string and state: 'in_progress' | 'complete' | 'error'.
    • "frontendTool": Executes registered frontend tools. Requires toolName: string and optional args: unknown.
    • "humanInTheLoop": Suspends workflow execution to request user input or approval. Requires status: 'suspended', runId: string, and various lifecycle properties.
  7. How the AI workflow processes responses

    main

    When an LLM returns a response, Cedar-OS routes it through handleLLMResponse(). This function processes an array of items that can be either raw strings (text) or structured objects. Structured objects are routed via processStructuredResponse() to specific processors based on their type field.

    Supported built-in response types include:

    • message: Handled by messageResponseProcessor to convert backend formats to chat messages.
    • setState: Handled by setStateResponseProcessor to execute state mutations via executeStateSetter().
    • frontendTool: Handled by frontendToolResponseProcessor to execute registered tools via executeFrontendTool().
    • progress_update: Handled by ProgressUpdateResponseProcessor to show loading states.
  8. ChatInput Voice Integration and States

    main

    The ChatInput component includes built-in voice support with automatic microphone permission handling. The UI transitions through several states:

    • Idle: Default state, microphone available.
    • Listening: Actively recording audio (red, pulsing UI).
    • Speaking: AI is currently speaking a response (green UI).
    • Denied: Microphone permission was denied (grayed out).
    • Not Supported: Voice functionality is not supported by the browser.
  9. Understand the Spell Architecture in Cedar OS

    main

    The Spell Architecture is a gesture-based interaction system designed for high performance and robust event handling. It relies on four primary pillars to manage user interactions (spells) efficiently:

    1. SpellActivationManager: A centralized singleton manager that handles all incoming events and orchestrates the activation logic.
    2. SpellSlice: A Zustand-based state slice that ensures all spell-related state (active, triggered, etc.) is synchronized across the application.
    3. useSpell Hook: The primary React interface used by components to interact with the spell system.
    4. Activation Modes: Flexible logic for how a spell is triggered, supporting different user interaction patterns like toggling, holding, or immediate triggering.

    This architecture uses a singleton pattern and ref-based callbacks to ensure that gesture processing remains performant and does not cause unnecessary React re-renders.

  10. Understand the LLM Response Structure

    main

    When your agent backend returns responses, they follow the LLMResponse interface. Cedar uses the object field to find structured responses for processing. The content field is always added to the chat by default as a simple text message.

    An LLMResponse can contain:

    • content: Text content from the LLM.
    • usage: Token usage information (promptTokens, completionTokens, totalTokens).
    • metadata: Additional metadata as a Record<string, unknown>.
    • object: A single StructuredResponseType or an array of them. This is where Cedar looks for structured data to process via the response processing system.
    interface LLMResponse {
    	content: string; // Text content from the LLM
    	usage?: {
    		promptTokens: number;
    		completionTokens: number;
    		totalTokens: number;
    	};
    	metadata?: Record<string, unknown>; // Additional metadata
    	// The object field contains structured output when using JSON Schema or Zod
    	object?: StructuredResponseType | StructuredResponseType[];
    }
  11. How Agentic State Management works with useCedarState

    main

    Cedar OS allows AI agents to read and modify your React application state through a type-safe interface. By using the useCedarState hook, you register state that is accessible to the AI. The AI can then perform actions that trigger the state's setter, enabling seamless interaction between the agent and your application logic.

    Use useCedarState with the following parameters:

    • key: A unique string identifier for the state.
    • initialValue: The starting value of the state.
    • description: A string describing the state to help the AI understand its purpose and how to use it.
    // AI can read and modify this state
    const [todos, setTodos] = useCedarState(
    	'todos',
    	[],
    	'User todo list manageable by AI'
    );