### Configuring Actors in Rivet App - JavaScript/TypeScript Source: https://github.com/rivet-gg/actor-core/blob/main/docs/llm/prompt.mdx Actors are registered with the Rivet application during setup. The `setup` function is used to define the actors available, and the `serve` function starts the application server. ```JavaScript setup({ actors: { actorName }}) ``` ```JavaScript serve(app) ``` -------------------------------- ### Start Server with bun Source: https://github.com/rivet-gg/actor-core/blob/main/docs/drivers/file-system.mdx Starts the development server using the bun dev command, assuming a standard package.json script is configured. ```bash bun dev ``` -------------------------------- ### Quick Start Example with React Hooks Source: https://github.com/rivet-gg/actor-core/blob/main/packages/frameworks/react/README.md Demonstrates initializing an ActorCore client, creating React hooks with createReactActorCore, and using useActor and useActorEvent within functional components to manage actor state and listen for events. ```tsx import { createClient } from "actor-core/client"; import { createReactActorCore } from "@actor-core/react"; import type { App } from "../counter/src/index"; import React, { useState } from "react"; // Create a client const client = createClient("http://your-actor-core-server.com"); // Create React hooks for your actors const { useActor, useActorEvent } = createReactActorCore(client); function ReactApp() { return ( <> ); } function Counter() { // Get or create an actor const [{ actor }] = useActor("counter"); return (
); } function CounterValue({ actor }) { const [count, setCount] = useState(0); // Listen to events useActorEvent({ actor, event: "newCount" }, (newCount) => { setCount(newCount); }); return count; } render(, document.getElementById("root")); ``` -------------------------------- ### Start Server with pnpm Source: https://github.com/rivet-gg/actor-core/blob/main/docs/drivers/file-system.mdx Starts the development server using the pnpm dev command, assuming a standard package.json script is configured. ```bash pnpm dev ``` -------------------------------- ### Start Server with npm Source: https://github.com/rivet-gg/actor-core/blob/main/docs/drivers/file-system.mdx Starts the development server using the npm run dev command, assuming a standard package.json script is configured. ```bash npm run dev ``` -------------------------------- ### Starting ActorCore Development Server with CLI Source: https://github.com/rivet-gg/actor-core/blob/main/docs/snippets/step-run-studio.mdx Use the `@actor-core/cli` to start the development server for your ActorCore application. Replace `actors/app.ts` with the path to your main application file. The command automatically opens the ActorCore Studio for debugging. ```sh npm npx @actor-core/cli@latest dev actors/app.ts ``` ```sh pnpm pnpm exec @actor-core/cli@latest dev actors/app.ts ``` ```sh yarn yarn @actor-core/cli@latest dev actors/app.ts ``` ```sh bun bunx @actor-core/cli@latest dev actors/app.ts ``` -------------------------------- ### Start Server with yarn Source: https://github.com/rivet-gg/actor-core/blob/main/docs/drivers/file-system.mdx Starts the development server using the yarn dev command, assuming a standard package.json script is configured. ```bash yarn dev ``` -------------------------------- ### Installing ActorCore Source: https://github.com/rivet-gg/actor-core/blob/main/packages/actor-core/README.md Provides commands for installing the ActorCore library using various popular Node.js package managers such as npm, pnpm, Yarn, and Bun. ```bash # npm npm add actor-core # pnpm pnpm add actor-core # Yarn yarn add actor-core # Bun bun add actor-core ``` -------------------------------- ### Installing and Running Tests with Vitest (Bash) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/concepts/testing.mdx Explains the basic commands to install the Vitest testing framework as a dev dependency and how to execute the tests using npm. ```bash # Install Vitest npm install -D vitest # Run tests npm test ``` -------------------------------- ### Running Mintlify Development Server (Shell) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/README.md This command uses `yarn dlx` to execute the `mintlify dev` command without needing to install Mintlify globally. It starts a local server to preview your documentation. ```Shell yarn dlx mintlify dev ``` -------------------------------- ### Installing ActorCore Python Client (bash) Source: https://github.com/rivet-gg/actor-core/blob/main/clients/python/README.md Provides the command-line instruction to install the `python-actor-core-client` package using pip. This is the first step required to use the client library. ```bash pip install python-actor-core-client ``` -------------------------------- ### Installing ActorCore packages Source: https://github.com/rivet-gg/actor-core/blob/main/docs/clients/javascript.mdx Install the ActorCore client and Node.js platform packages using different package managers. ```sh npm npm install actor-core ``` ```sh pnpm pnpm add actor-core ``` ```sh yarn yarn add actor-core ``` ```sh bun bun add actor-core ``` -------------------------------- ### Running Logic on Actor Start with onStart (TypeScript) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/concepts/lifecycle.mdx Shows how to use the `onStart` hook, which is called whenever the actor starts (e.g., after restart or code upgrade), to set up resources or start background tasks like intervals. ```typescript import { actor } from "actor-core"; const counter = actor({ state: { count: 0 }, onStart: (c) => { console.log('Actor started with count:', c.state.count); // Set up interval for automatic counting const intervalId = setInterval(() => { c.state.count++; console.log('Auto-increment:', c.state.count); }, 10000); // Store interval ID to clean up later if needed c.custom.intervalId = intervalId; }, actions: { /* ... */ } }); ``` -------------------------------- ### Starting Actor Core Server (npm) - Bash Source: https://github.com/rivet-gg/actor-core/blob/main/examples/linear-coding-agent/README.md Starts the ActorCore server using the npm script `dev`. This server hosts the main coding agent logic. ```Bash npm run dev ``` -------------------------------- ### Activating Python Virtual Environment (Shell) Source: https://github.com/rivet-gg/actor-core/blob/main/clients/python/requirements.txt A commented-out shell command showing how to activate the previously created 'venv' virtual environment. Activation modifies the shell's PATH to use the environment's Python and installed packages. ```Shell # source venv/bin/activate ``` -------------------------------- ### Starting Actor Core Server (CLI) - Bash Source: https://github.com/rivet-gg/actor-core/blob/main/examples/linear-coding-agent/README.md Starts the ActorCore server directly using the `@actor-core/cli` command, specifying the main application file. ```Bash npx @actor-core/cli dev src/actors/app.ts ``` -------------------------------- ### Starting the Development Server Source: https://github.com/rivet-gg/actor-core/blob/main/docs/drivers/memory.mdx Run the development server using the dev script defined in your `package.json`, typically executed via npm, yarn, pnpm, or bun. ```bash npm run dev ``` ```bash yarn dev ``` ```bash pnpm dev ``` ```bash bun dev ``` -------------------------------- ### Install TypeScript Dependencies and Initialize Config (bun) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/snippets/setup-typescript.mdx Installs typescript, @types/node, and tsx as development dependencies using bun, then initializes the tsconfig.json file with es2022 target, nodenext module system, nodenext module resolution, and sets the output directory to 'dist'. ```sh bun add -D typescript @types/node tsx bun tsc --init --target es2022 --module nodenext --moduleResolution nodenext --outDir dist ``` -------------------------------- ### Listing Python Project Dependencies Source: https://github.com/rivet-gg/actor-core/blob/main/clients/python/requirements.txt Specifies the required Python packages and their exact versions for the project. This list is typically used with pip to install dependencies, ensuring a consistent environment. ```Python asyncio==3.4.3 iniconfig==2.1.0 maturin==1.8.3 packaging==24.2 pluggy==1.5.0 pytest==8.3.5 pytest-asyncio==0.26.0 ``` -------------------------------- ### Finding or Creating Actor with Tags (get) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/concepts/interacting-with-actors.mdx Shows how to use the `get` method to connect to an actor based on provided tags. If no actor matches the tags, a new one is created. Includes examples of calling an actor method after connection. ```typescript // Connect to a chat room for the "general" channel const room = await client.chatRoom.get({ name: "chat_room", channel: "general" }); // Now you can call methods on the actor await room.sendMessage("Alice", "Hello everyone!"); ``` ```rust use actor_core_client::GetOptions; use serde_json::json; // Connect to a chat room for the "general" channel let tags = vec![ ("name".to_string(), "chat_room".to_string()), ("channel".to_string(), "general".to_string()), ]; let mut options = GetOptions { tags: Some(tags), ..Default::default() }; let room = client.get("chatRoom", options) .await .expect("Failed to connect to chat room"); // Now you can call methods on the actor room.action("sendMessage", vec![json!("Alice"), json!("Hello everyone!")]) .await .expect("Failed to send message"); ``` ```python # Connect to a chat room for the "general" channel room = await client.get("chatRoom", tags=[ ("name", "chat_room"), ("channel", "general") ]) # Now you can call methods on the actor await room.action("sendMessage", ["Alice", "Hello everyone!"]) ``` -------------------------------- ### Setting Up and Serving an Actor Application in TypeScript Source: https://github.com/rivet-gg/actor-core/blob/main/docs/concepts/overview.mdx Demonstrates how to create an `actor-core` application by registering actors and starting the server. It also exports the app type for client-side type safety. ```typescript import { setup, serve } from "actor-core"; import chatRoom from "./chat_room"; // Create the application const app = setup({ actors: { chatRoom } }); // Start serving on default port serve(app); // Export the app type for client usage export type App = typeof app; ``` -------------------------------- ### Using Client Get with Actor Tags in TypeScript Source: https://github.com/rivet-gg/actor-core/blob/main/docs/concepts/overview.mdx Provides examples of using the `client.get` method to retrieve actors based on different tag patterns, demonstrating actor discovery. ```typescript import { createClient } from "actor-core/client"; import type { App } from "./src/index"; const client = createClient("http://localhost:6420"); // Game room with ID parameter const gameRoom = await client.gameRoom.get({ roomId: "ABC123" }); // User profile with ID const userProfile = await client.userProfile.get({ profileId: "1234" }); // Document with multiple parameters const document = await client.document.get({ workspaceId: "team-alpha", documentId: "budget-2024" }); ``` -------------------------------- ### Install TypeScript Dependencies and Initialize Config (npm) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/snippets/setup-typescript.mdx Installs typescript, @types/node, and tsx as development dependencies using npm, then initializes the tsconfig.json file with es2022 target, nodenext module system, nodenext module resolution, and sets the output directory to 'dist'. ```sh npm install typescript @types/node tsx --save-dev npx tsc --init --target es2022 --module nodenext --moduleResolution nodenext --outDir dist ``` -------------------------------- ### Install TypeScript Dependencies and Initialize Config (pnpm) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/snippets/setup-typescript.mdx Installs typescript, @types/node, and tsx as development dependencies using pnpm, then initializes the tsconfig.json file with es2022 target, nodenext module system, nodenext module resolution, and sets the output directory to 'dist'. ```sh pnpm add -D typescript @types/node tsx pnpm exec tsc --init --target es2022 --module nodenext --moduleResolution nodenext --outDir dist ``` -------------------------------- ### Install ActorCore Bun Package (sh) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/platforms/bun.mdx Installs the necessary Bun platform package for ActorCore using the Bun package manager. ```sh bun add @actor-core/bun ``` -------------------------------- ### Install Resend SDK (Bash) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/integrations/resend.mdx Installs the Resend SDK using npm, a package manager for Node.js, as a dependency for your project. ```bash npm install resend ``` -------------------------------- ### Install File System Driver with npm Source: https://github.com/rivet-gg/actor-core/blob/main/docs/drivers/file-system.mdx Installs the @actor-core/file-system and @actor-core/nodejs packages using npm, required for using the File System driver in a Node.js environment. ```bash npm install @actor-core/file-system @actor-core/nodejs ``` -------------------------------- ### Starting the React Development Server Source: https://github.com/rivet-gg/actor-core/blob/main/docs/frameworks/react.mdx Run the development server for the React application using the configured script (typically `dev`) with different package managers. ```sh npm cd my-app npm run dev ``` ```sh pnpm cd my-app pnpm run dev ``` ```sh yarn cd my-app yarn dev ``` ```sh bun cd my-app bun run dev ``` -------------------------------- ### Installing Memory Driver Packages Source: https://github.com/rivet-gg/actor-core/blob/main/docs/drivers/memory.mdx Install the necessary `@actor-core/memory` and `@actor-core/nodejs` packages using your preferred package manager (npm, yarn, pnpm, or bun). ```bash npm install @actor-core/memory @actor-core/nodejs ``` ```bash yarn add @actor-core/memory @actor-core/nodejs ``` ```bash pnpm add @actor-core/memory @actor-core/nodejs ``` ```bash bun add @actor-core/memory @actor-core/nodejs ``` -------------------------------- ### Installing Dependencies (npm) - Bash Source: https://github.com/rivet-gg/actor-core/blob/main/examples/linear-coding-agent/README.md Installs the project dependencies listed in the package.json file using npm. This is a standard step after cloning a Node.js project. ```Bash npm install ``` -------------------------------- ### Define and Start ActorCore Server with Bun (TypeScript) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/platforms/bun.mdx Creates a TypeScript file (`src/index.ts`) that imports the `serve` function from `@actor-core/bun` and the application logic, then starts the ActorCore server using the default file-system driver. ```typescript import { serve } from "@actor-core/bun"; import { app } from "../actors/app"; // Start the server with file-system driver (default) serve(app); ``` -------------------------------- ### Copying Environment Variables - Bash Source: https://github.com/rivet-gg/actor-core/blob/main/examples/linear-coding-agent/README.md Copies the example environment file `.env.example` to `.env`. This file needs to be edited with actual configuration details. ```Bash cp .env.example .env ``` -------------------------------- ### Installing ActorCore Node.js Dependency Source: https://github.com/rivet-gg/actor-core/blob/main/docs/platforms/nodejs.mdx Install the necessary ActorCore package for Node.js using various package managers. ```sh npm install @actor-core/nodejs ``` ```sh pnpm add @actor-core/nodejs ``` ```sh yarn add @actor-core/nodejs ``` ```sh bun add @actor-core/nodejs ``` -------------------------------- ### Install TypeScript Dependencies and Initialize Config (yarn) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/snippets/setup-typescript.mdx Installs typescript, @types/node, and tsx as development dependencies using yarn, then initializes the tsconfig.json file with es2022 target, nodenext module system, nodenext module resolution, and sets the output directory to 'dist'. ```sh yarn add -D typescript @types/node tsx yarn tsc --init --target es2022 --module nodenext --moduleResolution nodenext --outDir dist ``` -------------------------------- ### Installing ActorCore Packages in React Source: https://github.com/rivet-gg/actor-core/blob/main/docs/frameworks/react.mdx Navigate into the new project directory and install the necessary ActorCore client and React integration packages using different package managers. ```sh npm cd my-app npm install actor-core @actor-core/react ``` ```sh pnpm cd my-app pnpm add actor-core @actor-core/react ``` ```sh yarn cd my-app yarn add actor-core @actor-core/react ``` ```sh bun cd my-app bun add actor-core @actor-core/react ``` -------------------------------- ### Start ActorCore Server Source: https://github.com/rivet-gg/actor-core/blob/main/docs/drivers/redis.mdx Execute the development script to start the ActorCore server configured with the Redis driver. This command assumes a 'dev' script is defined in the project's package.json. ```bash npm run dev ``` ```bash yarn dev ``` ```bash pnpm dev ``` ```bash bun dev ``` -------------------------------- ### Install File System Driver with bun Source: https://github.com/rivet-gg/actor-core/blob/main/docs/drivers/file-system.mdx Adds the @actor-core/file-system and @actor-core/nodejs packages using bun, required for using the File System driver in a Bun environment. ```bash bun add @actor-core/file-system @actor-core/nodejs ``` -------------------------------- ### Building ActorCore Project Source: https://github.com/rivet-gg/actor-core/blob/main/CLAUDE.md Commands to build the ActorCore project for production. The first command builds the entire monorepo, and the second builds a specific package using Turbopack. ```Shell yarn build ``` ```Shell yarn build -F actor-core ``` -------------------------------- ### Start Local Development Servers Source: https://github.com/rivet-gg/actor-core/blob/main/docs/examples/live-cursors.mdx Starts both the ActorCore server (on port 6420) and the Next.js development server (on port 3000) concurrently for local testing and development. ```Shell yarn dev ``` -------------------------------- ### Initializing a Rivet Actor Project Source: https://github.com/rivet-gg/actor-core/blob/main/docs/examples/chat.mdx This command initializes a new Rivet actor project named 'chat-room' using the 'counter' template as a starting point. It sets up the necessary project structure and dependencies. ```sh npx create-actor@latest chat-room -p rivet -t counter ``` -------------------------------- ### Find Relevant ActorCore Code Queries Source: https://github.com/rivet-gg/actor-core/blob/main/docs/llm/windsurf.mdx Examples of natural language queries for Windsurf's AI to help locate specific code implementations, find examples of design patterns (like RPC methods), or understand how state management is handled within the ActorCore codebase. ```Natural Language Query # Find implementations of specific components Find the files that implement the Redis driver # Locate examples of specific patterns Show me examples of RPC methods in the codebase # Understand actor state management Explain how actor state is persisted between restarts ``` -------------------------------- ### Understand the Codebase Prompts Source: https://github.com/rivet-gg/actor-core/blob/main/docs/llm/cursor.mdx Example prompts for Cursor to help understand the architecture, communication patterns, and lifecycle hooks within the ActorCore codebase. ```Prompt # Get an overview of ActorCore's architecture Explain the architecture of ActorCore and how the different topologies work # Understand how actors communicate Explain how actors communicate with each other in the coordinate topology # Learn about specific concepts Explain the lifecycle hooks for actors and when each one is called ``` -------------------------------- ### Running All Services with ngrok - Bash Source: https://github.com/rivet-gg/actor-core/blob/main/examples/linear-coding-agent/README.md Starts both servers and also exposes the local webhook server to the internet using ngrok, making it accessible for external services like Linear webhooks. ```Bash npm run start:ngrok ``` -------------------------------- ### Install File System Driver with pnpm Source: https://github.com/rivet-gg/actor-core/blob/main/docs/drivers/file-system.mdx Adds the @actor-core/file-system and @actor-core/nodejs packages using pnpm, required for using the File System driver in a Node.js environment. ```bash pnpm add @actor-core/file-system @actor-core/nodejs ``` -------------------------------- ### Running Webhook Server - Bash Source: https://github.com/rivet-gg/actor-core/blob/main/examples/linear-coding-agent/README.md Starts the separate HTTP server responsible for receiving Linear webhooks and forwarding them to the agent. ```Bash npm run server ``` -------------------------------- ### Install File System Driver with yarn Source: https://github.com/rivet-gg/actor-core/blob/main/docs/drivers/file-system.mdx Adds the @actor-core/file-system and @actor-core/nodejs packages using yarn, required for using the File System driver in a Node.js environment. ```bash yarn add @actor-core/file-system @actor-core/nodejs ``` -------------------------------- ### Formatting ActorCore Code Source: https://github.com/rivet-gg/actor-core/blob/main/CLAUDE.md Command to automatically format the codebase according to predefined style rules using the Biome formatter. ```Shell yarn fmt ``` -------------------------------- ### Quickstart: Define and Call Actor with Resend Source: https://github.com/rivet-gg/actor-core/blob/main/docs/integrations/resend.mdx Demonstrates how to define an ActorCore actor ('user') that integrates with Resend for sending emails and how to call its actions from a client. ```typescript import { actor, setup } from "actor-core"; import { Resend } from "resend"; const resend = new Resend(process.env.RESEND_API_KEY); const user = actor({ state: { email: null as string | null, }, actions: { // Example: Somehow acquire the user's email register: async (c, email: string) => { c.state.email = email; }, // Example: Send an email sendExampleEmail: async (c) => { if (!c.state.email) throw new Error("No email registered"); await resend.emails.send({ from: "updates@yourdomain.com", to: c.state.email, subject: "Hello, world!", html: "

Lorem ipsum

", }); }, }, }); export const app = setup({ actors: { user } }); export type App = typeof app; ``` ```typescript import { createClient } from "actor-core"; import { App } from "./actors/app.ts"; const client = createClient("http://localhost:8787"); const userActor = await client.user.get({ tags: { user: "user123" } }); await userActor.register("user@example.com"); await userActor.sendExampleEmail(); ``` -------------------------------- ### Running All Services (concurrently) - Bash Source: https://github.com/rivet-gg/actor-core/blob/main/examples/linear-coding-agent/README.md Starts both the actor server and the webhook server simultaneously using a tool like `concurrently`. This is a convenient way to run the full application locally. ```Bash npm run start ``` -------------------------------- ### Install ActorCore React Package Source: https://github.com/rivet-gg/actor-core/blob/main/packages/frameworks/react/README.md Commands to add the @actor-core/react package to your project using different Node.js package managers. ```bash # npm npm add @actor-core/react ``` ```bash # pnpm pnpm add @actor-core/react ``` ```bash # Yarn yarn add @actor-core/react ``` ```bash # Bun bun add @actor-core/react ``` -------------------------------- ### Creating Python Virtual Environment (Shell) Source: https://github.com/rivet-gg/actor-core/blob/main/clients/python/requirements.txt A commented-out shell command demonstrating how to create a Python virtual environment named 'venv' using the standard 'venv' module. This isolates project dependencies from the system Python. ```Shell # python -m venv venv ``` -------------------------------- ### Initialize New ActorCore Project Source: https://github.com/rivet-gg/actor-core/blob/main/README.md This command uses npx to run the latest version of the create-actor package, which is the recommended way to scaffold a new ActorCore project from a template. ```bash npx create-actor@latest ``` -------------------------------- ### Find Relevant Code Prompts Source: https://github.com/rivet-gg/actor-core/blob/main/docs/llm/cursor.mdx Example prompts for Cursor to find specific code implementations, patterns, and understand state management within the ActorCore project. ```Prompt # Find implementations of specific components Find the files that implement the Redis driver # Locate examples of specific patterns Show me examples of RPC methods in the codebase # Understand actor state management Explain how actor state is persisted between restarts ``` -------------------------------- ### Defining ActorCore Server in Node.js Source: https://github.com/rivet-gg/actor-core/blob/main/docs/platforms/nodejs.mdx Create the main server file (`src/index.ts`) to import the necessary functions and start the ActorCore server with the default file-system driver. ```typescript import { serve } from "@actor-core/nodejs"; import { app } from "../actors/app"; // Start the server with file-system driver (default) serve(app); ``` -------------------------------- ### Debug ActorCore Issues with Claude Code (Bash) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/llm/claude.mdx Provides examples of using `claude` commands to get help debugging common issues in ActorCore, including connection problems, state persistence failures, and performance/scaling concerns. ```bash # Diagnose connection problems claude "my actor connections are dropping, help me debug why" # Fix state persistence issues claude "my actor state isn't persisting between restarts, what could be wrong?" # Address scaling problems claude "my actors are using too much memory, how can I optimize them?" ``` -------------------------------- ### Implementing Tenant Logic in React (TypeScript) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/snippets/landing-snippets.mdx This snippet shows the client-side implementation for handling tenant-specific logic within a React component. It runs in the browser and interacts with the backend actor. ```TypeScript ``` -------------------------------- ### Run Verdaccio Docker Container (Bash) Source: https://github.com/rivet-gg/actor-core/blob/main/CONTRIBUTING.md Starts a Verdaccio Docker container named 'verdaccio', mapping port 4873 and removing the container upon exit. This sets up a local npm registry. ```bash $ docker run -it --rm --name verdaccio -p 4873:4873 verdaccio/verdaccio ``` -------------------------------- ### Actor-Core Client and React Hook Setup Source: https://github.com/rivet-gg/actor-core/blob/main/docs/snippets/examples/document-react.mdx Initializes the `actor-core` client pointing to the backend service and creates the React hooks (`useActor`, `useActorEvent`) bound to this client instance. ```typescript import { createClient } from "actor-core/client"; import { createReactActorCore } from "@actor-core/react"; import type { App } from "../actors/app"; const client = createClient("http://localhost:6420"); const { useActor, useActorEvent } = createReactActorCore(client); ``` -------------------------------- ### Create Sync ActorCore Client (Python) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/clients/python.mdx Demonstrates creating a synchronous ActorCore client, getting an actor instance, subscribing to events using a callback, calling an action, and handling cleanup within the event handler. ```python from actor_core_client import Client # Replace with your endpoint URL after deployment client = Client("http://localhost:6420") # Get or create an actor instance counter = client.get("counter") # Subscribe to events using callback def on_new_count(msg): print(f"Event: {msg}") # Clean up once we receive our event counter.disconnect() counter.on_event("newCount", on_new_count) # Call an action result = counter.action("increment", 5) print(f"Action result: {result}") # Clean is handled on by on_new_count ``` -------------------------------- ### Use Claude Code to Add New Features in ActorCore (Bash) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/llm/claude.mdx Shows examples of using `claude` commands to get assistance with implementing new features in ActorCore, such as creating new actors, adding authentication, or implementing error handling. ```bash # Create a new actor implementation claude "help me create a new actor for managing user sessions" # Add authentication to an actor claude "show me how to add authentication to my actor's _onBeforeConnect method" # Implement error handling claude "help me implement proper error handling for my actor's RPC methods" ``` -------------------------------- ### Setup Redis Drivers and Serve App Source: https://github.com/rivet-gg/actor-core/blob/main/docs/drivers/redis.mdx Configure ActorCore to use the Redis drivers for manager, actor, and coordinate roles. This involves creating an ioredis client instance and passing it to the driver constructors before calling the `serve` function. ```typescript import { serve } from "@actor-core/nodejs" import { RedisManagerDriver } from "@actor-core/redis/manager"; import { RedisActorDriver } from "@actor-core/redis/actor"; import { RedisCoordinateDriver } from "@actor-core/redis/coordinate"; import Redis from "ioredis"; // Create a Redis connection const redis = new Redis(); serve(app, { topology: "coordinate", // Can be "standalone" or "coordinate" drivers: { manager: new RedisManagerDriver(redis), actor: new RedisActorDriver(redis), coordinate: new RedisCoordinateDriver(redis), }, }); ``` -------------------------------- ### Mounting ActorCore Router with Hono (TypeScript) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/integrations/hono.mdx Demonstrates how to set up the ActorCore application and mount its router within a Hono application. It highlights the importance of setting the `basePath` in the `setup` function to match the path where the router is mounted in Hono. ```TypeScript // Setup the ActorCore app const app = setup({ actors: { counter }, // IMPORTANT: Must specify the same basePath where your router is mounted basePath: "/my-path" }); // Create a router from the app const { router: actorRouter } = createRouter(app); // Mount at the same path specified in basePath honoApp.route("/my-path", actorRouter); ``` -------------------------------- ### Setup Game Logic with React useEffect Hook Source: https://github.com/rivet-gg/actor-core/blob/main/docs/snippets/examples/game-react.mdx Uses the `useEffect` hook to set up core game logic when the `actor` or `players` state changes. This includes attaching keyboard event listeners, starting an interval for sending player input to the actor, initiating a render loop using `requestAnimationFrame` to draw players on the canvas, and defining a cleanup function to remove listeners and stop loops when the component unmounts or dependencies change. ```TypeScript useEffect(() => { if (!actor) return; // Set up keyboard handlers const handleKeyDown = (e: KeyboardEvent) => { keysPressed.current[e.key.toLowerCase()] = true; }; const handleKeyUp = (e: KeyboardEvent) => { keysPressed.current[e.key.toLowerCase()] = false; }; window.addEventListener("keydown", handleKeyDown); window.addEventListener("keyup", handleKeyUp); // Input update loop const inputInterval = setInterval(() => { const input = { x: 0, y: 0 }; if (keysPressed.current["w"] || keysPressed.current["arrowup"]) input.y = -1; if (keysPressed.current["s"] || keysPressed.current["arrowdown"]) input.y = 1; if (keysPressed.current["a"] || keysPressed.current["arrowleft"]) input.x = -1; if (keysPressed.current["d"] || keysPressed.current["arrowright"]) input.x = 1; actor.setInput(input); }, 50); // Rendering loop const renderLoop = () => { const canvas = canvasRef.current; if (!canvas) return; const ctx = canvas.getContext("2d"); if (!ctx) return; ctx.clearRect(0, 0, canvas.width, canvas.height); // Use for loop instead of forEach for (let i = 0; i < players.length; i++) { const player = players[i]; ctx.fillStyle = player.id === connectionId ? "blue" : "gray"; ctx.beginPath(); ctx.arc(player.position.x, player.position.y, 10, 0, Math.PI * 2); ctx.fill(); } requestAnimationFrame(renderLoop); }; const animationId = requestAnimationFrame(renderLoop); return () => { window.removeEventListener("keydown", handleKeyDown); window.removeEventListener("keyup", handleKeyUp); clearInterval(inputInterval); cancelAnimationFrame(animationId); }; }, [actor, connectionId, players]); ``` -------------------------------- ### Create Async ActorCore Client (Python) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/clients/python.mdx Demonstrates creating an asynchronous ActorCore client, getting an actor instance, subscribing to events using a callback, calling an action, and handling cleanup within an async function. ```python import asyncio from actor_core_client import AsyncClient async def main(): # Replace with your endpoint URL after deployment client = AsyncClient("http://localhost:6420") # Get or create an actor instance counter = await client.get("counter") # Subscribe to events using callback def on_new_count(msg): print(f"Event: {msg}") counter.on_event("newCount", on_new_count) # Call an action result = await counter.action("increment", 5) print(f"Action result: {result}") # Wait to receive events await asyncio.sleep(1) # Clean up await counter.disconnect() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Deploying the Rivet Actor Source: https://github.com/rivet-gg/actor-core/blob/main/docs/examples/chat.mdx These commands navigate into the project directory and initiate the deployment process for the Rivet actor to the Rivet platform. ```sh cd chat-room npm run deploy ``` -------------------------------- ### Create Server with File System Driver in TypeScript Source: https://github.com/rivet-gg/actor-core/blob/main/docs/drivers/file-system.mdx Demonstrates how to set up a simple server using the @actor-core/nodejs serve function and configure it with the File System driver for actor state management in a standalone topology. ```typescript import { serve } from "@actor-core/nodejs" import { FileSystemManagerDriver, FileSystemActorDriver, FileSystemGlobalState } from "@actor-core/file-system"; const fsState = new FileSystemGlobalState(); serve(app, { topology: "standalone", drivers: { manager: new FileSystemManagerDriver(app, fsState), actor: new FileSystemActorDriver(fsState), }, }); ``` -------------------------------- ### Handling Connection Parameters with createConnState (TypeScript) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/concepts/connections.mdx Demonstrates how to handle connection parameters passed by the client within the `createConnState` function on the actor side, typically used for authentication or initial setup. It also shows the client-side code for passing these parameters when connecting. ```typescript import { actor } from "actor-core"; const gameRoom = actor({ state: {}, // Handle connection setup createConnState: (c, { params }) => { // Validate authentication token const authToken = params.authToken; if (!authToken || !validateToken(authToken)) { throw new Error("Invalid auth token"); } // Create connection state return { userId: getUserIdFromToken(authToken), role: "player" }; }, actions: { // ... } }); ``` ```typescript import { createClient } from "actor-core/client"; import type { App } from "./src/index"; const client = createClient("http://localhost:6420"); const gameRoom = await client.gameRoom.get({ params: { authToken: "supersekure" } }); ``` -------------------------------- ### Basic Actor Testing with setupTest (TypeScript) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/concepts/testing.mdx Demonstrates how to use `setupTest` to create an isolated test environment for an ActorCore application. It shows how to get an actor client, interact with the actor's actions, and make assertions about the state using Vitest. Includes the corresponding actor definition. ```ts import { test, expect } from "vitest"; import { setupTest } from "actor-core/test"; import { app } from "../src/index"; test("my actor test", async (test) => { const { client } = await setupTest(test, app); // Now you can interact with your actor through the client const myActor = await client.myActor.get(); // Test your actor's functionality await myActor.someAction(); // Make assertions const result = await myActor.getState(); expect(result).toEqual("updated"); }); ``` ```ts import { actor, setup } from "actor-core"; const myActor = actor({ state: { value: "initial" }, actions: { someAction: (c) => { c.state.value = "updated"; return c.state.value; }, getState: (c) => { return c.state.value; } } }); export const app = setup({ actors: { myActor } }); export type App = typeof app; ``` -------------------------------- ### Setting up Actor-Core Application with Counter Actor - TypeScript Source: https://github.com/rivet-gg/actor-core/blob/main/docs/snippets/setup-actor.mdx This snippet demonstrates how to define an actor with state and actions using `actor-core` and then set up a basic application containing this actor. It includes CORS configuration and exports the application and its type for client use. ```TypeScript import { actor, setup } from "actor-core"; // Create actor const counter = actor({ state: { count: 0 }, actions: { increment: (c, x: number) => { c.state.count += x; c.broadcast("newCount", c.state.count); return c.state.count; } } }); // Create the application export const app = setup({ actors: { counter }, cors: { origin: "http://localhost:8080" } }); // Export app type for client usage export type App = typeof app; ``` -------------------------------- ### Install ActorCore Cloudflare Workers Dependency Source: https://github.com/rivet-gg/actor-core/blob/main/docs/platforms/cloudflare-workers.mdx Installs the necessary package for integrating ActorCore with Cloudflare Workers using various package managers. ```npm npm install @actor-core/cloudflare-workers ``` ```pnpm pnpm add @actor-core/cloudflare-workers ``` ```yarn yarn add @actor-core/cloudflare-workers ``` ```bun bun add @actor-core/cloudflare-workers ``` -------------------------------- ### Create Rivet Actor Project Source: https://github.com/rivet-gg/actor-core/blob/main/docs/examples/live-cursors.mdx Initializes a new Rivet actor project named 'cursor-demo' using the 'cursors' template via the create-actor CLI tool. ```Shell npx create-actor@latest cursor-demo -p rivet -t cursors ``` -------------------------------- ### Initializing ActorCore Client Source: https://github.com/rivet-gg/actor-core/blob/main/docs/concepts/interacting-with-actors.mdx Demonstrates how to create a client instance to connect to an ActorCore service using different programming languages. Requires the actor-core client library. ```typescript import { createClient } from "actor-core/client"; import type { App } from "../src/index"; // Create a client with the connection address and app type const client = createClient(/* CONNECTION ADDRESS */); ``` ```rust use actor_core_client::{Client, TransportKind, EncodingKind}; // Create a client with connection address and configuration let client = Client::new( "http://localhost:6420".to_string(), // Connection address TransportKind::WebSocket, // Transport (WebSocket or SSE) EncodingKind::Cbor, // Encoding (Json or Cbor) ); ``` ```python from actor_core_client import AsyncClient as ActorClient # Create a client with the connection address client = ActorClient("http://localhost:6420") ``` -------------------------------- ### Install ActorCore Client Dependency (Shell) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/clients/python.mdx Installs the `actor-core-client` package using pip, adding it to the project's dependencies within the virtual environment. ```sh pip install actor-core-client ``` -------------------------------- ### Install Rivet Package Source: https://github.com/rivet-gg/actor-core/blob/main/docs/platforms/rivet.mdx Instructions to install the `@actor-core/rivet` package using different Node.js package managers. This package is a dependency for deploying ActorCore applications to Rivet. ```sh npm install @actor-core/rivet ``` ```sh pnpm add @actor-core/rivet ``` ```sh yarn add @actor-core/rivet ``` ```sh bun add @actor-core/rivet ``` -------------------------------- ### Install Redis Driver Packages Source: https://github.com/rivet-gg/actor-core/blob/main/docs/drivers/redis.mdx Install the necessary npm packages for the Redis driver and Node.js integration using various package managers. Requires `@actor-core/redis`, `@actor-core/nodejs`, and `ioredis`. ```bash npm install @actor-core/redis @actor-core/nodejs ioredis ``` ```bash yarn add @actor-core/redis @actor-core/nodejs ioredis ``` ```bash pnpm add @actor-core/redis @actor-core/nodejs ioredis ``` ```bash bun add @actor-core/redis @actor-core/nodejs ioredis ``` -------------------------------- ### Passing Connection Parameters to ActorCore Get Source: https://github.com/rivet-gg/actor-core/blob/main/docs/concepts/interacting-with-actors.mdx Demonstrates how to pass custom parameters to an actor when connecting using the `get` method. These parameters can be accessed by the actor during the connection process. ```TypeScript const chatRoom = await client.chatRoom.get({ channel: "super-secret" }, { params: { userId: "1234", authToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", displayName: "Alice" } }); ``` ```Rust use serde_json::json; use actor_core_client::GetOptions; let tags = vec![ ("channel".to_string(), "super-secret".to_string()), ]; let params = json!({ "userId": "1234", "authToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "displayName": "Alice" }); let options = GetOptions { tags: Some(tags), params: Some(params), no_create: None, create: None, }; let chat_room = client.get("chatRoom", options) .await .expect("Failed to connect to chat room"); ``` ```Python chat_room = await client.get( "chatRoom", tags=[("channel", "super-secret")], params={ "userId": "1234", "authToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "displayName": "Alice" } ) ``` -------------------------------- ### Initializing ActorCore Client with Options Source: https://github.com/rivet-gg/actor-core/blob/main/docs/concepts/interacting-with-actors.mdx Provides examples of initializing the ActorCore client with various configuration options, such as data encoding format (`encoding`) and preferred network transports (`supportedTransports`). Note that Rust and Python clients currently support only a single transport. ```TypeScript // Example with all client options const client = createClient( "https://actors.example.com", { // Data serialization format encoding: "cbor", // or "json" // Network transports in order of preference supportedTransports: ["websocket", "sse"] } ); ``` ```Rust use actor_core_client::{Client, TransportKind, EncodingKind}; // Create client with specific options let client = Client::new( "https://actors.example.com".to_string(), TransportKind::WebSocket, // or TransportKind::Sse EncodingKind::Cbor, // or EncodingKind::Json ); // Rust does not support accepting multiple transports ``` ```Python from actor_core_client import AsyncClient as ActorClient # Example with all client options client = ActorClient( "https://actors.example.com", "websocket" # or "sse" "cbor", # or "json" ) # Python does not support accepting multiple transports ``` -------------------------------- ### Initializing State and Running Setup with state, createState, and onCreate (TypeScript) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/concepts/lifecycle.mdx Demonstrates the different ways to initialize actor state using the `state` constant or `createState` function, and how to use the `onCreate` hook for running initialization logic that doesn't return state, such as logging or setting up external services. ```typescript import { actor } from "actor-core"; // Using state constant const counter1 = actor({ state: { count: 0 }, actions: { /* ... */ } }); // Using createState function const counter2 = actor({ createState: () => { // Initialize with a count of 0 return { count: 0 }; }, actions: { /* ... */ } }); // Using onCreate const counter3 = actor({ state: { count: 0 }, // Run initialization logic (logging, external service setup, etc.) onCreate: (c) => { console.log("Counter actor initialized"); // Can perform async operations or setup // No need to return anything }, actions: { /* ... */ } }); ``` -------------------------------- ### Creating Rivet Actor Project with Package Managers Source: https://github.com/rivet-gg/actor-core/blob/main/docs/snippets/create-actor-cli.mdx These commands execute the `create-actor` tool via different package managers to set up a new Rivet actor project directory with initial files and configuration. ```sh npx create-actor@latest ``` ```sh npm create actor@latest ``` ```sh pnpm create actor@latest ``` ```sh yarn create actor@latest ``` ```sh bun create actor@latest ``` -------------------------------- ### Configuring CORS with actor-core Setup (TypeScript) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/concepts/cors.mdx This snippet demonstrates how to configure CORS when setting up an actor-core application using the `setup` function. It shows how to include the `cors` option with a specific origin, which should be changed to match your frontend's domain. ```ts import { setup } from "actor-core"; import counter from "./counter"; const app = setup({ actors: { counter }, // Change this to match your frontend's origin cors: { origin: "https://yourdomain.com" } }); ``` -------------------------------- ### Complete Rivet Actor Core Chat Web Client HTML/JavaScript Source: https://github.com/rivet-gg/actor-core/blob/main/docs/examples/chat.mdx This full HTML document provides a complete example of a web client for a Rivet Actor Core chat room. It includes the necessary HTML structure, basic CSS styling, and JavaScript code to initialize the Rivet client, connect to a chat channel, load historical messages, listen for real-time new messages, and handle sending messages via a form. ```html Rivet Chat Room

Rivet Chat Room

    ``` -------------------------------- ### Deploy Rivet Actors Source: https://github.com/rivet-gg/actor-core/blob/main/docs/examples/live-cursors.mdx Navigates into the project directory and runs the npm deploy script to build and deploy the actors to the Rivet platform, following interactive prompts for account, project, and environment selection. ```Shell cd cursor-demo npm run deploy ``` -------------------------------- ### Connect to ActorCore and Interact (Rust) Source: https://github.com/rivet-gg/actor-core/blob/main/clients/rust/README.md This Rust example demonstrates how to create an ActorCore client, connect to a specific actor (a chat room), listen for events, send actions, and disconnect. Requires `tokio` for async execution, `serde_json` for JSON handling, and `anyhow` for error handling. ```rust use actor_core_client::{client::{Client, GetOptions}, drivers::TransportKind, encoding::EncodingKind}; use serde_json::json; #[tokio::main] async fn main() -> anyhow::Result<()> { // Create a client connected to your ActorCore manager let client = Client::new( "http://localhost:6420".to_string(), TransportKind::Sse, EncodingKind::Json ); // Connect to a chat room actor let chat_room = client.get("chat-room", GetOptions::default()).await?; // Listen for new messages chat_room.on_event("newMessage", |args| { let username = args[0].as_str().unwrap(); let message = args[1].as_str().unwrap(); println!("Message from {}: {}", username, message); }).await; // Send message to room chat_room.action("sendMessage", vec![ json!("william"), json!("All the world's a stage.") ]).await?; // When finished chat_room.disconnect().await; Ok(()) } ``` -------------------------------- ### Understand ActorCore Codebase with Claude Code (Bash) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/llm/claude.mdx Provides example `claude` commands to query Claude Code about the overall architecture, communication patterns, and lifecycle hooks within the ActorCore project. Helps users gain a high-level understanding. ```bash # Get an overview of ActorCore's architecture claude "explain the architecture of ActorCore and how the different topologies work" # Understand how actors communicate claude "explain how actors communicate with each other in the coordinate topology" # Learn about specific concepts claude "explain the lifecycle hooks for actors and when each one is called" ``` -------------------------------- ### Add New Features Prompts Source: https://github.com/rivet-gg/actor-core/blob/main/docs/llm/cursor.mdx Example prompts for Cursor to assist in creating new actors, adding authentication, and implementing error handling in ActorCore. ```Prompt # Create a new actor implementation Help me create a new actor for managing user sessions # Add authentication to an actor Show me how to add authentication to my actor's _onBeforeConnect method # Implement error handling Help me implement proper error handling for my actor's RPC methods ``` -------------------------------- ### Connecting to Actor Instance (TypeScript) Source: https://github.com/rivet-gg/actor-core/blob/main/docs/concepts/metadata.mdx Demonstrates connecting to a specific instance of the `chatRoom` actor using `actor-core/client`. It shows how to use the `client.chatRoom.get` method, passing parameters like `channel` and `teamId`, which are likely used by the actor framework to find or create the correct instance based on its tags. It also shows calling an action (`getChannelId`) on the connected instance. ```typescript import { createClient } from "actor-core/client"; import type { App } from "./src/index"; const client = createClient("http://localhost:6420"); // Connect to a specific channel const randomChannel = await client.chatRoom.get({ channel: "random" }); // Check the channel ID const channelId = await randomChannel.getChannelId(); console.log("Connected to channel:", channelId); // "random" // Or connect with multiple parameters const teamChannel = await client.chatRoom.get({ channel: "team-chat", teamId: "engineering" }); ``` -------------------------------- ### Initializing Notes Actor with actor-core Source: https://github.com/rivet-gg/actor-core/blob/main/docs/snippets/examples/database-js.mdx Initializes the `actor-core` actor instance named `notes`. It sets up the initial state containing an empty array of `Note` objects, defines the connection state creation logic, and registers the available actions for managing notes. ```typescript import { actor } from "actor-core"; import { authenticate } from "./my-utils"; export type Note = { id: string; content: string; updatedAt: number }; // User notes actor const notes = actor({ state: { notes: [] as Note[] }, // Authenticate createConnState: async (c, { params }) => { const token = params.token; const userId = await authenticate(token); return { userId }; }, actions: { // Get all notes getNotes: (c) => c.state.notes, // Update note or create if it doesn't exist updateNote: (c, { id, content }) => { const noteIndex = c.state.notes.findIndex(note => note.id === id); let note; if (noteIndex >= 0) { // Update existing note note = c.state.notes[noteIndex]; note.content = content; note.updatedAt = Date.now(); c.broadcast("noteUpdated", note); } else { // Create new note note = { id: id || `note-${Date.now()}`, content, updatedAt: Date.now() }; c.state.notes.push(note); c.broadcast("noteAdded", note); } return note; }, // Delete note deleteNote: (c, { id }) => { const noteIndex = c.state.notes.findIndex(note => note.id === id); if (noteIndex >= 0) { c.state.notes.splice(noteIndex, 1); c.broadcast("noteDeleted", { id }); } } } }); export default notes; ``` -------------------------------- ### Setting up ActorCore Server with Hono in Bun Source: https://github.com/rivet-gg/actor-core/blob/main/docs/integrations/hono.mdx This snippet demonstrates how to initialize an ActorCore application within a Hono server running on Bun. It shows how to define actors, configure the base path for the ActorCore router, mount the router onto the Hono app, and export the server configuration including the WebSocket handler required by Bun. It requires `hono`, `@actor-core/bun`, and the actor definitions (like `./counter`). ```typescript import { Hono } from "hono"; import { setup, createRouter } from "@actor-core/bun"; import counter from "./counter"; // Create your Hono app const honoApp = new Hono(); // Add your custom routes honoApp.get("/", (c) => c.text("Welcome to my app!")); honoApp.get("/hello", (c) => c.text("Hello, world!")); // Setup the ActorCore app const app = setup({ actors: { counter }, // IMPORTANT: Must specify the same basePath where your router is mounted basePath: "/my-path" }); // Create a router from the app const { router: actorRouter, webSocketHandler } = createRouter(app); // Mount the ActorCore router at /my-path honoApp.route("/my-path", actorRouter); // Export the app type for client usage export type App = typeof app; // Create and start the server export default { port: 6420, fetch: honoApp.fetch, // IMPORTANT: Pass the webSocketHandler to Bun websocket: webSocketHandler, }; ```