From ec84c521552aceea61d67d6e015a2f2d0100f39d Mon Sep 17 00:00:00 2001 From: -Puter <22245429+puterhimself@users.noreply.github.com> Date: Sun, 19 Jul 2026 06:29:51 +0530 Subject: [PATCH] Add AgentOS daemon control plane and maintenance tooling --- .../skills/ai-agent-workspace/BASE_SKILL.md | 1185 ++++++++++ .agents/skills/ai-agent-workspace/SKILL.md | 343 +++ .agents/skills/ai-agent-workspace/index.json | 904 ++++++++ .../skills/ai-agent-workspace/openapi.json | 1311 +++++++++++ .../reference/actors/access-control.md | 134 ++ .../reference/actors/actions.md | 384 ++++ .../reference/actors/appearance.md | 183 ++ .../reference/actors/authentication.md | 598 +++++ .../actors/communicating-between-actors.md | 336 +++ .../reference/actors/connections.md | 460 ++++ .../reference/actors/debugging.md | 644 ++++++ .../reference/actors/design-patterns.md | 616 +++++ .../reference/actors/destroy.md | 123 + .../reference/actors/errors.md | 434 ++++ .../reference/actors/events.md | 390 ++++ .../actors/fetch-and-websocket-handler.md | 10 + .../reference/actors/helper-types.md | 10 + .../reference/actors/http-api.md | 10 + .../reference/actors/input.md | 287 +++ .../reference/actors/inspector-tabs.md | 290 +++ .../reference/actors/keys.md | 261 +++ .../ai-agent-workspace/reference/actors/kv.md | 162 ++ .../reference/actors/lifecycle.md | 1145 ++++++++++ .../reference/actors/limits.md | 174 ++ .../reference/actors/metadata.md | 137 ++ .../reference/actors/queues.md | 496 ++++ .../reference/actors/quickstart/backend.md | 183 ++ .../reference/actors/quickstart/cloudflare.md | 263 +++ .../reference/actors/quickstart/effect.md | 239 ++ .../reference/actors/quickstart/next-js.md | 136 ++ .../reference/actors/quickstart/react.md | 157 ++ .../reference/actors/quickstart/rust.md | 249 ++ .../reference/actors/quickstart/supabase.md | 96 + .../reference/actors/request-handler.md | 256 +++ .../reference/actors/scaling.md | 10 + .../reference/actors/schedule.md | 103 + .../actors/sharing-and-joining-state.md | 10 + .../reference/actors/sqlite-drizzle.md | 260 +++ .../reference/actors/sqlite.md | 267 +++ .../reference/actors/state.md | 437 ++++ .../reference/actors/statuses.md | 36 + .../reference/actors/testing.md | 236 ++ .../reference/actors/troubleshooting.md | 154 ++ .../reference/actors/types.md | 106 + .../reference/actors/versions.md | 337 +++ .../reference/actors/websocket-handler.md | 330 +++ .../reference/actors/workflows.md | 2013 +++++++++++++++++ .../reference/agent-os/agent-to-agent.md | 111 + .../reference/agent-os/agents/pi.md | 80 + .../reference/agent-os/authentication.md | 81 + .../reference/agent-os/benchmarks.md | 10 + .../reference/agent-os/configuration.md | 68 + .../reference/agent-os/core.md | 270 +++ .../reference/agent-os/crash-course.md | 569 +++++ .../reference/agent-os/cron.md | 223 ++ .../reference/agent-os/deployment.md | 18 + .../reference/agent-os/events.md | 195 ++ .../reference/agent-os/filesystem.md | 243 ++ .../reference/agent-os/limitations.md | 35 + .../reference/agent-os/llm-credentials.md | 65 + .../reference/agent-os/llm-gateway.md | 17 + .../reference/agent-os/multiplayer.md | 190 ++ .../reference/agent-os/networking.md | 169 ++ .../reference/agent-os/permissions.md | 156 ++ .../reference/agent-os/persistence.md | 185 ++ .../reference/agent-os/processes.md | 253 +++ .../reference/agent-os/queues.md | 191 ++ .../reference/agent-os/quickstart.md | 91 + .../reference/agent-os/sandbox.md | 108 + .../reference/agent-os/security-model.md | 52 + .../reference/agent-os/security.md | 101 + .../reference/agent-os/sessions.md | 461 ++++ .../reference/agent-os/software.md | 56 + .../reference/agent-os/sqlite.md | 66 + .../reference/agent-os/system-prompt.md | 24 + .../reference/agent-os/tools.md | 151 ++ .../reference/agent-os/versus-sandbox.md | 54 + .../reference/agent-os/webhooks.md | 103 + .../reference/agent-os/workflows.md | 163 ++ .../ai-agent-workspace/reference/cli.md | 103 + .../reference/clients/javascript.md | 288 +++ .../reference/clients/react.md | 273 +++ .../reference/clients/swift.md | 454 ++++ .../reference/clients/swiftui.md | 359 +++ .../reference/cookbook/ai-agent-workspace.md | 181 ++ .../reference/cookbook/ai-agent.md | 128 ++ .../reference/cookbook/chat-room.md | 114 + .../cookbook/collaborative-text-editor.md | 157 ++ .../reference/cookbook/cron-jobs.md | 141 ++ .../reference/cookbook/live-cursors.md | 152 ++ .../reference/cookbook/multiplayer-game.md | 713 ++++++ .../reference/cookbook/per-tenant-database.md | 119 + .../reference/cookbook/vpc-air-gapped.md | 136 ++ .../reference/deploy/aws-ecs.md | 13 + .../reference/deploy/aws-lambda.md | 10 + .../reference/deploy/cloudflare.md | 53 + .../reference/deploy/freestyle.md | 136 ++ .../reference/deploy/gcp-cloud-run.md | 74 + .../reference/deploy/hetzner.md | 10 + .../reference/deploy/kubernetes.md | 121 + .../reference/deploy/railway.md | 45 + .../reference/deploy/rivet-compute.md | 106 + .../reference/deploy/supabase.md | 48 + .../reference/deploy/vercel.md | 138 ++ .../reference/deploy/vm-and-bare-metal.md | 96 + .../reference/general/actor-configuration.md | 41 + .../reference/general/architecture.md | 452 ++++ .../reference/general/cors.md | 74 + .../reference/general/docs-for-llms.md | 51 + .../reference/general/edge.md | 39 + .../reference/general/endpoints.md | 128 ++ .../general/environment-variables.md | 87 + .../reference/general/http-server.md | 156 ++ .../reference/general/logging.md | 151 ++ .../reference/general/pool-configuration.md | 119 + .../reference/general/production-checklist.md | 98 + .../general/registry-configuration.md | 106 + .../reference/general/runtime-modes.md | 143 ++ .../reference/general/wasm-vs-native-sdk.md | 87 + .../reference/self-hosting/configuration.md | 74 + .../reference/self-hosting/docker-compose.md | 188 ++ .../self-hosting/docker-container.md | 150 ++ .../reference/self-hosting/filesystem.md | 47 + .../reference/self-hosting/foundationdb.md | 35 + .../reference/self-hosting/install.md | 32 + .../reference/self-hosting/kubernetes.md | 236 ++ .../reference/self-hosting/multi-region.md | 10 + .../reference/self-hosting/postgres.md | 192 ++ .../self-hosting/production-checklist.md | 53 + .../reference/self-hosting/railway.md | 99 + .../reference/self-hosting/render.md | 131 ++ .../reference/self-hosting/tls.md | 22 + .agents/skills/ai-agent/BASE_SKILL.md | 537 +++++ .agents/skills/ai-agent/SKILL.md | 256 +++ .agents/skills/ai-agent/index.json | 694 ++++++ .agents/skills/ai-agent/openapi.json | 1311 +++++++++++ .../reference/actors/access-control.md | 48 + .../ai-agent/reference/actors/actions.md | 98 + .../reference/actors/actor-runtime-socket.md | 54 + .../ai-agent/reference/actors/appearance.md | 50 + .../reference/actors/authentication.md | 105 + .../actors/communicating-between-actors.md | 42 + .../ai-agent/reference/actors/connections.md | 119 + .../ai-agent/reference/actors/debugging.md | 644 ++++++ .../reference/actors/design-patterns.md | 163 ++ .../ai-agent/reference/actors/destroy.md | 71 + .../ai-agent/reference/actors/errors.md | 81 + .../ai-agent/reference/actors/events.md | 145 ++ .../actors/fetch-and-websocket-handler.md | 10 + .../ai-agent/reference/actors/helper-types.md | 10 + .../ai-agent/reference/actors/http-api.md | 10 + .../skills/ai-agent/reference/actors/input.md | 51 + .../reference/actors/inspector-tabs.md | 251 ++ .../skills/ai-agent/reference/actors/keys.md | 51 + .../skills/ai-agent/reference/actors/kv.md | 44 + .../ai-agent/reference/actors/lifecycle.md | 388 ++++ .../ai-agent/reference/actors/limits.md | 169 ++ .../ai-agent/reference/actors/metadata.md | 39 + .../ai-agent/reference/actors/queues.md | 122 + .../reference/actors/quickstart/backend.md | 64 + .../reference/actors/quickstart/cloudflare.md | 165 ++ .../reference/actors/quickstart/effect.md | 239 ++ .../reference/actors/quickstart/next-js.md | 117 + .../reference/actors/quickstart/react.md | 82 + .../reference/actors/quickstart/rust.md | 249 ++ .../reference/actors/quickstart/supabase.md | 109 + .../reference/actors/request-handler.md | 79 + .../ai-agent/reference/actors/scaling.md | 10 + .../ai-agent/reference/actors/schedule.md | 40 + .../actors/sharing-and-joining-state.md | 10 + .../reference/actors/sqlite-drizzle.md | 248 ++ .../ai-agent/reference/actors/sqlite.md | 127 ++ .../skills/ai-agent/reference/actors/state.md | 270 +++ .../ai-agent/reference/actors/statuses.md | 36 + .../ai-agent/reference/actors/testing.md | 51 + .../reference/actors/troubleshooting.md | 154 ++ .../skills/ai-agent/reference/actors/types.md | 46 + .../ai-agent/reference/actors/versions.md | 241 ++ .../reference/actors/websocket-handler.md | 201 ++ .../ai-agent/reference/actors/workflows.md | 228 ++ .agents/skills/ai-agent/reference/cli.md | 103 + .../ai-agent/reference/clients/javascript.md | 120 + .../ai-agent/reference/clients/react.md | 88 + .../skills/ai-agent/reference/clients/rust.md | 367 +++ .../ai-agent/reference/clients/swift.md | 454 ++++ .../ai-agent/reference/clients/swiftui.md | 359 +++ .../ai-agent/reference/cookbook/ai-agent.md | 127 ++ .../ai-agent/reference/cookbook/chat-room.md | 114 + .../cookbook/collaborative-text-editor.md | 157 ++ .../ai-agent/reference/cookbook/cron-jobs.md | 123 + .../reference/cookbook/live-cursors.md | 152 ++ .../reference/cookbook/multiplayer-game.md | 713 ++++++ .../reference/cookbook/per-tenant-database.md | 119 + .../reference/cookbook/vpc-air-gapped.md | 136 ++ .../ai-agent/reference/deploy/aws-ecs.md | 13 + .../ai-agent/reference/deploy/aws-lambda.md | 10 + .../ai-agent/reference/deploy/cloudflare.md | 53 + .../reference/deploy/container-runner.md | 95 + .../ai-agent/reference/deploy/freestyle.md | 136 ++ .../reference/deploy/gcp-cloud-run.md | 74 + .../ai-agent/reference/deploy/hetzner.md | 10 + .../ai-agent/reference/deploy/kubernetes.md | 121 + .../ai-agent/reference/deploy/railway.md | 45 + .../reference/deploy/rivet-compute.md | 144 ++ .../ai-agent/reference/deploy/supabase.md | 50 + .../ai-agent/reference/deploy/vercel.md | 138 ++ .../reference/deploy/vm-and-bare-metal.md | 96 + .../reference/general/actor-configuration.md | 19 + .../reference/general/architecture.md | 452 ++++ .../skills/ai-agent/reference/general/cors.md | 18 + .../reference/general/docs-for-llms.md | 51 + .../skills/ai-agent/reference/general/edge.md | 24 + .../ai-agent/reference/general/endpoints.md | 98 + .../general/environment-variables.md | 87 + .../ai-agent/reference/general/http-server.md | 96 + .../ai-agent/reference/general/logging.md | 74 + .../reference/general/pool-configuration.md | 119 + .../reference/general/production-checklist.md | 98 + .../general/registry-configuration.md | 32 + .../reference/general/runtime-modes.md | 99 + .../reference/general/wasm-vs-native-sdk.md | 79 + .../reference/self-hosting/configuration.md | 74 + .../reference/self-hosting/docker-compose.md | 188 ++ .../self-hosting/docker-container.md | 150 ++ .../reference/self-hosting/filesystem.md | 47 + .../reference/self-hosting/foundationdb.md | 35 + .../reference/self-hosting/install.md | 32 + .../reference/self-hosting/kubernetes.md | 236 ++ .../reference/self-hosting/multi-region.md | 10 + .../reference/self-hosting/postgres.md | 192 ++ .../self-hosting/production-checklist.md | 53 + .../reference/self-hosting/railway.md | 99 + .../ai-agent/reference/self-hosting/render.md | 131 ++ .../ai-agent/reference/self-hosting/tls.md | 22 + .agents/skills/chat-room/BASE_SKILL.md | 537 +++++ .agents/skills/chat-room/SKILL.md | 243 ++ .agents/skills/chat-room/index.json | 694 ++++++ .agents/skills/chat-room/openapi.json | 1311 +++++++++++ .../reference/actors/access-control.md | 48 + .../chat-room/reference/actors/actions.md | 98 + .../reference/actors/actor-runtime-socket.md | 54 + .../chat-room/reference/actors/appearance.md | 50 + .../reference/actors/authentication.md | 105 + .../actors/communicating-between-actors.md | 42 + .../chat-room/reference/actors/connections.md | 119 + .../chat-room/reference/actors/debugging.md | 644 ++++++ .../reference/actors/design-patterns.md | 163 ++ .../chat-room/reference/actors/destroy.md | 71 + .../chat-room/reference/actors/errors.md | 81 + .../chat-room/reference/actors/events.md | 145 ++ .../actors/fetch-and-websocket-handler.md | 10 + .../reference/actors/helper-types.md | 10 + .../chat-room/reference/actors/http-api.md | 10 + .../chat-room/reference/actors/input.md | 51 + .../reference/actors/inspector-tabs.md | 251 ++ .../skills/chat-room/reference/actors/keys.md | 51 + .../skills/chat-room/reference/actors/kv.md | 44 + .../chat-room/reference/actors/lifecycle.md | 388 ++++ .../chat-room/reference/actors/limits.md | 169 ++ .../chat-room/reference/actors/metadata.md | 39 + .../chat-room/reference/actors/queues.md | 122 + .../reference/actors/quickstart/backend.md | 64 + .../reference/actors/quickstart/cloudflare.md | 165 ++ .../reference/actors/quickstart/effect.md | 239 ++ .../reference/actors/quickstart/next-js.md | 117 + .../reference/actors/quickstart/react.md | 82 + .../reference/actors/quickstart/rust.md | 249 ++ .../reference/actors/quickstart/supabase.md | 109 + .../reference/actors/request-handler.md | 79 + .../chat-room/reference/actors/scaling.md | 10 + .../chat-room/reference/actors/schedule.md | 40 + .../actors/sharing-and-joining-state.md | 10 + .../reference/actors/sqlite-drizzle.md | 248 ++ .../chat-room/reference/actors/sqlite.md | 127 ++ .../chat-room/reference/actors/state.md | 270 +++ .../chat-room/reference/actors/statuses.md | 36 + .../chat-room/reference/actors/testing.md | 51 + .../reference/actors/troubleshooting.md | 154 ++ .../chat-room/reference/actors/types.md | 46 + .../chat-room/reference/actors/versions.md | 241 ++ .../reference/actors/websocket-handler.md | 201 ++ .../chat-room/reference/actors/workflows.md | 228 ++ .agents/skills/chat-room/reference/cli.md | 103 + .../chat-room/reference/clients/javascript.md | 120 + .../chat-room/reference/clients/react.md | 88 + .../chat-room/reference/clients/rust.md | 367 +++ .../chat-room/reference/clients/swift.md | 454 ++++ .../chat-room/reference/clients/swiftui.md | 359 +++ .../chat-room/reference/cookbook/ai-agent.md | 127 ++ .../chat-room/reference/cookbook/chat-room.md | 114 + .../cookbook/collaborative-text-editor.md | 157 ++ .../chat-room/reference/cookbook/cron-jobs.md | 123 + .../reference/cookbook/live-cursors.md | 152 ++ .../reference/cookbook/multiplayer-game.md | 713 ++++++ .../reference/cookbook/per-tenant-database.md | 119 + .../reference/cookbook/vpc-air-gapped.md | 136 ++ .../chat-room/reference/deploy/aws-ecs.md | 13 + .../chat-room/reference/deploy/aws-lambda.md | 10 + .../chat-room/reference/deploy/cloudflare.md | 53 + .../reference/deploy/container-runner.md | 95 + .../chat-room/reference/deploy/freestyle.md | 136 ++ .../reference/deploy/gcp-cloud-run.md | 74 + .../chat-room/reference/deploy/hetzner.md | 10 + .../chat-room/reference/deploy/kubernetes.md | 121 + .../chat-room/reference/deploy/railway.md | 45 + .../reference/deploy/rivet-compute.md | 144 ++ .../chat-room/reference/deploy/supabase.md | 50 + .../chat-room/reference/deploy/vercel.md | 138 ++ .../reference/deploy/vm-and-bare-metal.md | 96 + .../reference/general/actor-configuration.md | 19 + .../reference/general/architecture.md | 452 ++++ .../chat-room/reference/general/cors.md | 18 + .../reference/general/docs-for-llms.md | 51 + .../chat-room/reference/general/edge.md | 24 + .../chat-room/reference/general/endpoints.md | 98 + .../general/environment-variables.md | 87 + .../reference/general/http-server.md | 96 + .../chat-room/reference/general/logging.md | 74 + .../reference/general/pool-configuration.md | 119 + .../reference/general/production-checklist.md | 98 + .../general/registry-configuration.md | 32 + .../reference/general/runtime-modes.md | 99 + .../reference/general/wasm-vs-native-sdk.md | 79 + .../reference/self-hosting/configuration.md | 74 + .../reference/self-hosting/docker-compose.md | 188 ++ .../self-hosting/docker-container.md | 150 ++ .../reference/self-hosting/filesystem.md | 47 + .../reference/self-hosting/foundationdb.md | 35 + .../reference/self-hosting/install.md | 32 + .../reference/self-hosting/kubernetes.md | 236 ++ .../reference/self-hosting/multi-region.md | 10 + .../reference/self-hosting/postgres.md | 192 ++ .../self-hosting/production-checklist.md | 53 + .../reference/self-hosting/railway.md | 99 + .../reference/self-hosting/render.md | 131 ++ .../chat-room/reference/self-hosting/tls.md | 22 + .agents/skills/cron-jobs/BASE_SKILL.md | 537 +++++ .agents/skills/cron-jobs/SKILL.md | 252 +++ .agents/skills/cron-jobs/index.json | 694 ++++++ .agents/skills/cron-jobs/openapi.json | 1311 +++++++++++ .../reference/actors/access-control.md | 48 + .../cron-jobs/reference/actors/actions.md | 98 + .../reference/actors/actor-runtime-socket.md | 54 + .../cron-jobs/reference/actors/appearance.md | 50 + .../reference/actors/authentication.md | 105 + .../actors/communicating-between-actors.md | 42 + .../cron-jobs/reference/actors/connections.md | 119 + .../cron-jobs/reference/actors/debugging.md | 644 ++++++ .../reference/actors/design-patterns.md | 163 ++ .../cron-jobs/reference/actors/destroy.md | 71 + .../cron-jobs/reference/actors/errors.md | 81 + .../cron-jobs/reference/actors/events.md | 145 ++ .../actors/fetch-and-websocket-handler.md | 10 + .../reference/actors/helper-types.md | 10 + .../cron-jobs/reference/actors/http-api.md | 10 + .../cron-jobs/reference/actors/input.md | 51 + .../reference/actors/inspector-tabs.md | 251 ++ .../skills/cron-jobs/reference/actors/keys.md | 51 + .../skills/cron-jobs/reference/actors/kv.md | 44 + .../cron-jobs/reference/actors/lifecycle.md | 388 ++++ .../cron-jobs/reference/actors/limits.md | 169 ++ .../cron-jobs/reference/actors/metadata.md | 39 + .../cron-jobs/reference/actors/queues.md | 122 + .../reference/actors/quickstart/backend.md | 64 + .../reference/actors/quickstart/cloudflare.md | 165 ++ .../reference/actors/quickstart/effect.md | 239 ++ .../reference/actors/quickstart/next-js.md | 117 + .../reference/actors/quickstart/react.md | 82 + .../reference/actors/quickstart/rust.md | 249 ++ .../reference/actors/quickstart/supabase.md | 109 + .../reference/actors/request-handler.md | 79 + .../cron-jobs/reference/actors/scaling.md | 10 + .../cron-jobs/reference/actors/schedule.md | 40 + .../actors/sharing-and-joining-state.md | 10 + .../reference/actors/sqlite-drizzle.md | 248 ++ .../cron-jobs/reference/actors/sqlite.md | 127 ++ .../cron-jobs/reference/actors/state.md | 270 +++ .../cron-jobs/reference/actors/statuses.md | 36 + .../cron-jobs/reference/actors/testing.md | 51 + .../reference/actors/troubleshooting.md | 154 ++ .../cron-jobs/reference/actors/types.md | 46 + .../cron-jobs/reference/actors/versions.md | 241 ++ .../reference/actors/websocket-handler.md | 201 ++ .../cron-jobs/reference/actors/workflows.md | 228 ++ .agents/skills/cron-jobs/reference/cli.md | 103 + .../cron-jobs/reference/clients/javascript.md | 120 + .../cron-jobs/reference/clients/react.md | 88 + .../cron-jobs/reference/clients/rust.md | 367 +++ .../cron-jobs/reference/clients/swift.md | 454 ++++ .../cron-jobs/reference/clients/swiftui.md | 359 +++ .../cron-jobs/reference/cookbook/ai-agent.md | 127 ++ .../cron-jobs/reference/cookbook/chat-room.md | 114 + .../cookbook/collaborative-text-editor.md | 157 ++ .../cron-jobs/reference/cookbook/cron-jobs.md | 123 + .../reference/cookbook/live-cursors.md | 152 ++ .../reference/cookbook/multiplayer-game.md | 713 ++++++ .../reference/cookbook/per-tenant-database.md | 119 + .../reference/cookbook/vpc-air-gapped.md | 136 ++ .../cron-jobs/reference/deploy/aws-ecs.md | 13 + .../cron-jobs/reference/deploy/aws-lambda.md | 10 + .../cron-jobs/reference/deploy/cloudflare.md | 53 + .../reference/deploy/container-runner.md | 95 + .../cron-jobs/reference/deploy/freestyle.md | 136 ++ .../reference/deploy/gcp-cloud-run.md | 74 + .../cron-jobs/reference/deploy/hetzner.md | 10 + .../cron-jobs/reference/deploy/kubernetes.md | 121 + .../cron-jobs/reference/deploy/railway.md | 45 + .../reference/deploy/rivet-compute.md | 144 ++ .../cron-jobs/reference/deploy/supabase.md | 50 + .../cron-jobs/reference/deploy/vercel.md | 138 ++ .../reference/deploy/vm-and-bare-metal.md | 96 + .../reference/general/actor-configuration.md | 19 + .../reference/general/architecture.md | 452 ++++ .../cron-jobs/reference/general/cors.md | 18 + .../reference/general/docs-for-llms.md | 51 + .../cron-jobs/reference/general/edge.md | 24 + .../cron-jobs/reference/general/endpoints.md | 98 + .../general/environment-variables.md | 87 + .../reference/general/http-server.md | 96 + .../cron-jobs/reference/general/logging.md | 74 + .../reference/general/pool-configuration.md | 119 + .../reference/general/production-checklist.md | 98 + .../general/registry-configuration.md | 32 + .../reference/general/runtime-modes.md | 99 + .../reference/general/wasm-vs-native-sdk.md | 79 + .../reference/self-hosting/configuration.md | 74 + .../reference/self-hosting/docker-compose.md | 188 ++ .../self-hosting/docker-container.md | 150 ++ .../reference/self-hosting/filesystem.md | 47 + .../reference/self-hosting/foundationdb.md | 35 + .../reference/self-hosting/install.md | 32 + .../reference/self-hosting/kubernetes.md | 236 ++ .../reference/self-hosting/multi-region.md | 10 + .../reference/self-hosting/postgres.md | 192 ++ .../self-hosting/production-checklist.md | 53 + .../reference/self-hosting/railway.md | 99 + .../reference/self-hosting/render.md | 131 ++ .../cron-jobs/reference/self-hosting/tls.md | 22 + .../rivetkit-client-javascript/SKILL.md | 145 ++ .../rivetkit-client-javascript/index.json | 7 + .agents/skills/rivetkit-client-react/SKILL.md | 113 + .../skills/rivetkit-client-react/index.json | 7 + .agents/skills/rivetkit/SKILL.md | 537 +++++ .agents/skills/rivetkit/index.json | 694 ++++++ .agents/skills/rivetkit/openapi.json | 1311 +++++++++++ .../reference/actors/access-control.md | 48 + .../rivetkit/reference/actors/actions.md | 98 + .../reference/actors/actor-runtime-socket.md | 54 + .../rivetkit/reference/actors/appearance.md | 50 + .../reference/actors/authentication.md | 105 + .../actors/communicating-between-actors.md | 42 + .../rivetkit/reference/actors/connections.md | 119 + .../rivetkit/reference/actors/debugging.md | 644 ++++++ .../reference/actors/design-patterns.md | 163 ++ .../rivetkit/reference/actors/destroy.md | 71 + .../rivetkit/reference/actors/errors.md | 81 + .../rivetkit/reference/actors/events.md | 145 ++ .../actors/fetch-and-websocket-handler.md | 10 + .../rivetkit/reference/actors/helper-types.md | 10 + .../rivetkit/reference/actors/http-api.md | 10 + .../skills/rivetkit/reference/actors/input.md | 51 + .../reference/actors/inspector-tabs.md | 251 ++ .../skills/rivetkit/reference/actors/keys.md | 51 + .../skills/rivetkit/reference/actors/kv.md | 44 + .../rivetkit/reference/actors/lifecycle.md | 388 ++++ .../rivetkit/reference/actors/limits.md | 169 ++ .../rivetkit/reference/actors/metadata.md | 39 + .../rivetkit/reference/actors/queues.md | 122 + .../reference/actors/quickstart/backend.md | 64 + .../reference/actors/quickstart/cloudflare.md | 165 ++ .../reference/actors/quickstart/effect.md | 239 ++ .../reference/actors/quickstart/next-js.md | 117 + .../reference/actors/quickstart/react.md | 82 + .../reference/actors/quickstart/rust.md | 249 ++ .../reference/actors/quickstart/supabase.md | 109 + .../reference/actors/request-handler.md | 79 + .../rivetkit/reference/actors/scaling.md | 10 + .../rivetkit/reference/actors/schedule.md | 40 + .../actors/sharing-and-joining-state.md | 10 + .../reference/actors/sqlite-drizzle.md | 248 ++ .../rivetkit/reference/actors/sqlite.md | 127 ++ .../skills/rivetkit/reference/actors/state.md | 270 +++ .../rivetkit/reference/actors/statuses.md | 36 + .../rivetkit/reference/actors/testing.md | 51 + .../reference/actors/troubleshooting.md | 154 ++ .../skills/rivetkit/reference/actors/types.md | 46 + .../rivetkit/reference/actors/versions.md | 241 ++ .../reference/actors/websocket-handler.md | 201 ++ .../rivetkit/reference/actors/workflows.md | 228 ++ .agents/skills/rivetkit/reference/cli.md | 103 + .../rivetkit/reference/clients/javascript.md | 120 + .../rivetkit/reference/clients/react.md | 88 + .../skills/rivetkit/reference/clients/rust.md | 367 +++ .../rivetkit/reference/clients/swift.md | 454 ++++ .../rivetkit/reference/clients/swiftui.md | 359 +++ .../rivetkit/reference/cookbook/ai-agent.md | 127 ++ .../rivetkit/reference/cookbook/chat-room.md | 114 + .../cookbook/collaborative-text-editor.md | 157 ++ .../rivetkit/reference/cookbook/cron-jobs.md | 123 + .../reference/cookbook/live-cursors.md | 152 ++ .../reference/cookbook/multiplayer-game.md | 713 ++++++ .../reference/cookbook/per-tenant-database.md | 119 + .../reference/cookbook/vpc-air-gapped.md | 136 ++ .../rivetkit/reference/deploy/aws-ecs.md | 13 + .../rivetkit/reference/deploy/aws-lambda.md | 10 + .../rivetkit/reference/deploy/cloudflare.md | 53 + .../reference/deploy/container-runner.md | 95 + .../rivetkit/reference/deploy/freestyle.md | 136 ++ .../reference/deploy/gcp-cloud-run.md | 74 + .../rivetkit/reference/deploy/hetzner.md | 10 + .../rivetkit/reference/deploy/kubernetes.md | 121 + .../rivetkit/reference/deploy/railway.md | 45 + .../reference/deploy/rivet-compute.md | 144 ++ .../rivetkit/reference/deploy/supabase.md | 50 + .../rivetkit/reference/deploy/vercel.md | 138 ++ .../reference/deploy/vm-and-bare-metal.md | 96 + .../reference/general/actor-configuration.md | 19 + .../reference/general/architecture.md | 452 ++++ .../skills/rivetkit/reference/general/cors.md | 18 + .../reference/general/docs-for-llms.md | 51 + .../skills/rivetkit/reference/general/edge.md | 24 + .../rivetkit/reference/general/endpoints.md | 98 + .../general/environment-variables.md | 87 + .../rivetkit/reference/general/http-server.md | 96 + .../rivetkit/reference/general/logging.md | 74 + .../reference/general/pool-configuration.md | 119 + .../reference/general/production-checklist.md | 98 + .../general/registry-configuration.md | 32 + .../reference/general/runtime-modes.md | 99 + .../reference/general/wasm-vs-native-sdk.md | 79 + .../reference/self-hosting/configuration.md | 74 + .../reference/self-hosting/docker-compose.md | 188 ++ .../self-hosting/docker-container.md | 150 ++ .../reference/self-hosting/filesystem.md | 47 + .../reference/self-hosting/foundationdb.md | 35 + .../reference/self-hosting/install.md | 32 + .../reference/self-hosting/kubernetes.md | 236 ++ .../reference/self-hosting/multi-region.md | 10 + .../reference/self-hosting/postgres.md | 192 ++ .../self-hosting/production-checklist.md | 53 + .../reference/self-hosting/railway.md | 99 + .../rivetkit/reference/self-hosting/render.md | 131 ++ .../rivetkit/reference/self-hosting/tls.md | 22 + .agents/skills/sandbox-agent/SKILL.md | 370 +++ .../references/agent-sessions.md | 263 +++ .../sandbox-agent/references/agents/amp.md | 22 + .../sandbox-agent/references/agents/claude.md | 49 + .../sandbox-agent/references/agents/codex.md | 22 + .../sandbox-agent/references/agents/cursor.md | 34 + .../references/agents/opencode.md | 31 + .../sandbox-agent/references/agents/pi.md | 22 + .../sandbox-agent/references/ai/llms-txt.md | 17 + .../sandbox-agent/references/ai/skill.md | 31 + .../sandbox-agent/references/architecture.md | 65 + .../sandbox-agent/references/attachments.md | 57 + .../skills/sandbox-agent/references/cli.md | 299 +++ .../references/common-software.md | 508 +++++ .../sandbox-agent/references/computer-use.md | 809 +++++++ .../skills/sandbox-agent/references/cors.md | 52 + .../sandbox-agent/references/custom-tools.md | 149 ++ .../skills/sandbox-agent/references/daemon.md | 71 + .../references/deploy/agentcomputer.md | 62 + .../references/deploy/boxlite.md | 69 + .../references/deploy/cloudflare.md | 188 ++ .../references/deploy/computesdk.md | 83 + .../references/deploy/daytona.md | 70 + .../sandbox-agent/references/deploy/docker.md | 108 + .../sandbox-agent/references/deploy/e2b.md | 54 + .../sandbox-agent/references/deploy/local.md | 71 + .../sandbox-agent/references/deploy/modal.md | 57 + .../sandbox-agent/references/deploy/vercel.md | 52 + .../sandbox-agent/references/file-system.md | 144 ++ .../sandbox-agent/references/inspector.md | 66 + .../references/llm-credentials.md | 241 ++ .../references/manage-sessions.md | 260 +++ .../sandbox-agent/references/mcp-config.md | 82 + .../sandbox-agent/references/multiplayer.md | 144 ++ .../sandbox-agent/references/observability.md | 65 + .../references/opencode-compatibility.md | 123 + .../references/orchestration-architecture.md | 44 + .../sandbox-agent/references/processes.md | 242 ++ .../sandbox-agent/references/quickstart.md | 289 +++ .../references/react-components.md | 246 ++ .../sandbox-agent/references/sdk-overview.md | 279 +++ .../sandbox-agent/references/security.md | 187 ++ .../references/session-persistence.md | 122 + .../references/session-restoration.md | 35 + .../sandbox-agent/references/skills-config.md | 79 + .../sandbox-agent/references/telemetry.md | 27 + .../references/troubleshooting.md | 58 + .vscode/settings.json | 13 + AGENTS.md | 174 ++ README.md | 9 +- apps/daemon/.env.example | 7 + apps/daemon/package.json | 29 + apps/daemon/src/agent-os.ts | 74 + apps/daemon/src/convex.ts | 174 ++ apps/daemon/src/index.ts | 7 + apps/daemon/src/runtime.ts | 83 + apps/daemon/tsconfig.json | 8 + bun.lock | 462 +++- package.json | 5 + packages/agents/package.json | 3 +- packages/agents/src/agents/hello-world.ts | 6 - packages/agents/src/agents/zopu.ts | 11 + packages/backend/convex/_generated/api.d.ts | 6 + packages/backend/convex/daemonCommands.ts | 199 ++ packages/backend/convex/daemonRuntime.ts | 107 + packages/backend/convex/daemons.ts | 60 + packages/backend/convex/schema.ts | 60 + packages/env/package.json | 3 +- packages/env/src/server.ts | 22 + packages/primitives/package.json | 22 + packages/primitives/src/agent-os.ts | 64 + packages/primitives/src/index.ts | 1 + packages/primitives/tsconfig.json | 5 + scripts/subtree.ts | 321 +++ scripts/subtrees.json | 22 + scripts/tsconfig.json | 7 + scripts/update-docs.ts | 282 +++ skills-lock.json | 53 + 621 files changed, 97578 insertions(+), 15 deletions(-) create mode 100644 .agents/skills/ai-agent-workspace/BASE_SKILL.md create mode 100644 .agents/skills/ai-agent-workspace/SKILL.md create mode 100644 .agents/skills/ai-agent-workspace/index.json create mode 100644 .agents/skills/ai-agent-workspace/openapi.json create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/access-control.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/actions.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/appearance.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/authentication.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/communicating-between-actors.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/connections.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/debugging.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/design-patterns.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/destroy.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/errors.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/events.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/fetch-and-websocket-handler.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/helper-types.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/http-api.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/input.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/inspector-tabs.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/keys.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/kv.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/lifecycle.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/limits.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/metadata.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/queues.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/quickstart/backend.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/quickstart/cloudflare.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/quickstart/effect.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/quickstart/next-js.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/quickstart/react.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/quickstart/rust.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/quickstart/supabase.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/request-handler.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/scaling.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/schedule.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/sharing-and-joining-state.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/sqlite-drizzle.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/sqlite.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/state.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/statuses.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/testing.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/troubleshooting.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/types.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/versions.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/websocket-handler.md create mode 100644 .agents/skills/ai-agent-workspace/reference/actors/workflows.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/agent-to-agent.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/agents/pi.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/authentication.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/benchmarks.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/configuration.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/core.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/crash-course.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/cron.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/deployment.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/events.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/filesystem.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/limitations.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/llm-credentials.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/llm-gateway.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/multiplayer.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/networking.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/permissions.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/persistence.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/processes.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/queues.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/quickstart.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/sandbox.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/security-model.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/security.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/sessions.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/software.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/sqlite.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/system-prompt.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/tools.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/versus-sandbox.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/webhooks.md create mode 100644 .agents/skills/ai-agent-workspace/reference/agent-os/workflows.md create mode 100644 .agents/skills/ai-agent-workspace/reference/cli.md create mode 100644 .agents/skills/ai-agent-workspace/reference/clients/javascript.md create mode 100644 .agents/skills/ai-agent-workspace/reference/clients/react.md create mode 100644 .agents/skills/ai-agent-workspace/reference/clients/swift.md create mode 100644 .agents/skills/ai-agent-workspace/reference/clients/swiftui.md create mode 100644 .agents/skills/ai-agent-workspace/reference/cookbook/ai-agent-workspace.md create mode 100644 .agents/skills/ai-agent-workspace/reference/cookbook/ai-agent.md create mode 100644 .agents/skills/ai-agent-workspace/reference/cookbook/chat-room.md create mode 100644 .agents/skills/ai-agent-workspace/reference/cookbook/collaborative-text-editor.md create mode 100644 .agents/skills/ai-agent-workspace/reference/cookbook/cron-jobs.md create mode 100644 .agents/skills/ai-agent-workspace/reference/cookbook/live-cursors.md create mode 100644 .agents/skills/ai-agent-workspace/reference/cookbook/multiplayer-game.md create mode 100644 .agents/skills/ai-agent-workspace/reference/cookbook/per-tenant-database.md create mode 100644 .agents/skills/ai-agent-workspace/reference/cookbook/vpc-air-gapped.md create mode 100644 .agents/skills/ai-agent-workspace/reference/deploy/aws-ecs.md create mode 100644 .agents/skills/ai-agent-workspace/reference/deploy/aws-lambda.md create mode 100644 .agents/skills/ai-agent-workspace/reference/deploy/cloudflare.md create mode 100644 .agents/skills/ai-agent-workspace/reference/deploy/freestyle.md create mode 100644 .agents/skills/ai-agent-workspace/reference/deploy/gcp-cloud-run.md create mode 100644 .agents/skills/ai-agent-workspace/reference/deploy/hetzner.md create mode 100644 .agents/skills/ai-agent-workspace/reference/deploy/kubernetes.md create mode 100644 .agents/skills/ai-agent-workspace/reference/deploy/railway.md create mode 100644 .agents/skills/ai-agent-workspace/reference/deploy/rivet-compute.md create mode 100644 .agents/skills/ai-agent-workspace/reference/deploy/supabase.md create mode 100644 .agents/skills/ai-agent-workspace/reference/deploy/vercel.md create mode 100644 .agents/skills/ai-agent-workspace/reference/deploy/vm-and-bare-metal.md create mode 100644 .agents/skills/ai-agent-workspace/reference/general/actor-configuration.md create mode 100644 .agents/skills/ai-agent-workspace/reference/general/architecture.md create mode 100644 .agents/skills/ai-agent-workspace/reference/general/cors.md create mode 100644 .agents/skills/ai-agent-workspace/reference/general/docs-for-llms.md create mode 100644 .agents/skills/ai-agent-workspace/reference/general/edge.md create mode 100644 .agents/skills/ai-agent-workspace/reference/general/endpoints.md create mode 100644 .agents/skills/ai-agent-workspace/reference/general/environment-variables.md create mode 100644 .agents/skills/ai-agent-workspace/reference/general/http-server.md create mode 100644 .agents/skills/ai-agent-workspace/reference/general/logging.md create mode 100644 .agents/skills/ai-agent-workspace/reference/general/pool-configuration.md create mode 100644 .agents/skills/ai-agent-workspace/reference/general/production-checklist.md create mode 100644 .agents/skills/ai-agent-workspace/reference/general/registry-configuration.md create mode 100644 .agents/skills/ai-agent-workspace/reference/general/runtime-modes.md create mode 100644 .agents/skills/ai-agent-workspace/reference/general/wasm-vs-native-sdk.md create mode 100644 .agents/skills/ai-agent-workspace/reference/self-hosting/configuration.md create mode 100644 .agents/skills/ai-agent-workspace/reference/self-hosting/docker-compose.md create mode 100644 .agents/skills/ai-agent-workspace/reference/self-hosting/docker-container.md create mode 100644 .agents/skills/ai-agent-workspace/reference/self-hosting/filesystem.md create mode 100644 .agents/skills/ai-agent-workspace/reference/self-hosting/foundationdb.md create mode 100644 .agents/skills/ai-agent-workspace/reference/self-hosting/install.md create mode 100644 .agents/skills/ai-agent-workspace/reference/self-hosting/kubernetes.md create mode 100644 .agents/skills/ai-agent-workspace/reference/self-hosting/multi-region.md create mode 100644 .agents/skills/ai-agent-workspace/reference/self-hosting/postgres.md create mode 100644 .agents/skills/ai-agent-workspace/reference/self-hosting/production-checklist.md create mode 100644 .agents/skills/ai-agent-workspace/reference/self-hosting/railway.md create mode 100644 .agents/skills/ai-agent-workspace/reference/self-hosting/render.md create mode 100644 .agents/skills/ai-agent-workspace/reference/self-hosting/tls.md create mode 100644 .agents/skills/ai-agent/BASE_SKILL.md create mode 100644 .agents/skills/ai-agent/SKILL.md create mode 100644 .agents/skills/ai-agent/index.json create mode 100644 .agents/skills/ai-agent/openapi.json create mode 100644 .agents/skills/ai-agent/reference/actors/access-control.md create mode 100644 .agents/skills/ai-agent/reference/actors/actions.md create mode 100644 .agents/skills/ai-agent/reference/actors/actor-runtime-socket.md create mode 100644 .agents/skills/ai-agent/reference/actors/appearance.md create mode 100644 .agents/skills/ai-agent/reference/actors/authentication.md create mode 100644 .agents/skills/ai-agent/reference/actors/communicating-between-actors.md create mode 100644 .agents/skills/ai-agent/reference/actors/connections.md create mode 100644 .agents/skills/ai-agent/reference/actors/debugging.md create mode 100644 .agents/skills/ai-agent/reference/actors/design-patterns.md create mode 100644 .agents/skills/ai-agent/reference/actors/destroy.md create mode 100644 .agents/skills/ai-agent/reference/actors/errors.md create mode 100644 .agents/skills/ai-agent/reference/actors/events.md create mode 100644 .agents/skills/ai-agent/reference/actors/fetch-and-websocket-handler.md create mode 100644 .agents/skills/ai-agent/reference/actors/helper-types.md create mode 100644 .agents/skills/ai-agent/reference/actors/http-api.md create mode 100644 .agents/skills/ai-agent/reference/actors/input.md create mode 100644 .agents/skills/ai-agent/reference/actors/inspector-tabs.md create mode 100644 .agents/skills/ai-agent/reference/actors/keys.md create mode 100644 .agents/skills/ai-agent/reference/actors/kv.md create mode 100644 .agents/skills/ai-agent/reference/actors/lifecycle.md create mode 100644 .agents/skills/ai-agent/reference/actors/limits.md create mode 100644 .agents/skills/ai-agent/reference/actors/metadata.md create mode 100644 .agents/skills/ai-agent/reference/actors/queues.md create mode 100644 .agents/skills/ai-agent/reference/actors/quickstart/backend.md create mode 100644 .agents/skills/ai-agent/reference/actors/quickstart/cloudflare.md create mode 100644 .agents/skills/ai-agent/reference/actors/quickstart/effect.md create mode 100644 .agents/skills/ai-agent/reference/actors/quickstart/next-js.md create mode 100644 .agents/skills/ai-agent/reference/actors/quickstart/react.md create mode 100644 .agents/skills/ai-agent/reference/actors/quickstart/rust.md create mode 100644 .agents/skills/ai-agent/reference/actors/quickstart/supabase.md create mode 100644 .agents/skills/ai-agent/reference/actors/request-handler.md create mode 100644 .agents/skills/ai-agent/reference/actors/scaling.md create mode 100644 .agents/skills/ai-agent/reference/actors/schedule.md create mode 100644 .agents/skills/ai-agent/reference/actors/sharing-and-joining-state.md create mode 100644 .agents/skills/ai-agent/reference/actors/sqlite-drizzle.md create mode 100644 .agents/skills/ai-agent/reference/actors/sqlite.md create mode 100644 .agents/skills/ai-agent/reference/actors/state.md create mode 100644 .agents/skills/ai-agent/reference/actors/statuses.md create mode 100644 .agents/skills/ai-agent/reference/actors/testing.md create mode 100644 .agents/skills/ai-agent/reference/actors/troubleshooting.md create mode 100644 .agents/skills/ai-agent/reference/actors/types.md create mode 100644 .agents/skills/ai-agent/reference/actors/versions.md create mode 100644 .agents/skills/ai-agent/reference/actors/websocket-handler.md create mode 100644 .agents/skills/ai-agent/reference/actors/workflows.md create mode 100644 .agents/skills/ai-agent/reference/cli.md create mode 100644 .agents/skills/ai-agent/reference/clients/javascript.md create mode 100644 .agents/skills/ai-agent/reference/clients/react.md create mode 100644 .agents/skills/ai-agent/reference/clients/rust.md create mode 100644 .agents/skills/ai-agent/reference/clients/swift.md create mode 100644 .agents/skills/ai-agent/reference/clients/swiftui.md create mode 100644 .agents/skills/ai-agent/reference/cookbook/ai-agent.md create mode 100644 .agents/skills/ai-agent/reference/cookbook/chat-room.md create mode 100644 .agents/skills/ai-agent/reference/cookbook/collaborative-text-editor.md create mode 100644 .agents/skills/ai-agent/reference/cookbook/cron-jobs.md create mode 100644 .agents/skills/ai-agent/reference/cookbook/live-cursors.md create mode 100644 .agents/skills/ai-agent/reference/cookbook/multiplayer-game.md create mode 100644 .agents/skills/ai-agent/reference/cookbook/per-tenant-database.md create mode 100644 .agents/skills/ai-agent/reference/cookbook/vpc-air-gapped.md create mode 100644 .agents/skills/ai-agent/reference/deploy/aws-ecs.md create mode 100644 .agents/skills/ai-agent/reference/deploy/aws-lambda.md create mode 100644 .agents/skills/ai-agent/reference/deploy/cloudflare.md create mode 100644 .agents/skills/ai-agent/reference/deploy/container-runner.md create mode 100644 .agents/skills/ai-agent/reference/deploy/freestyle.md create mode 100644 .agents/skills/ai-agent/reference/deploy/gcp-cloud-run.md create mode 100644 .agents/skills/ai-agent/reference/deploy/hetzner.md create mode 100644 .agents/skills/ai-agent/reference/deploy/kubernetes.md create mode 100644 .agents/skills/ai-agent/reference/deploy/railway.md create mode 100644 .agents/skills/ai-agent/reference/deploy/rivet-compute.md create mode 100644 .agents/skills/ai-agent/reference/deploy/supabase.md create mode 100644 .agents/skills/ai-agent/reference/deploy/vercel.md create mode 100644 .agents/skills/ai-agent/reference/deploy/vm-and-bare-metal.md create mode 100644 .agents/skills/ai-agent/reference/general/actor-configuration.md create mode 100644 .agents/skills/ai-agent/reference/general/architecture.md create mode 100644 .agents/skills/ai-agent/reference/general/cors.md create mode 100644 .agents/skills/ai-agent/reference/general/docs-for-llms.md create mode 100644 .agents/skills/ai-agent/reference/general/edge.md create mode 100644 .agents/skills/ai-agent/reference/general/endpoints.md create mode 100644 .agents/skills/ai-agent/reference/general/environment-variables.md create mode 100644 .agents/skills/ai-agent/reference/general/http-server.md create mode 100644 .agents/skills/ai-agent/reference/general/logging.md create mode 100644 .agents/skills/ai-agent/reference/general/pool-configuration.md create mode 100644 .agents/skills/ai-agent/reference/general/production-checklist.md create mode 100644 .agents/skills/ai-agent/reference/general/registry-configuration.md create mode 100644 .agents/skills/ai-agent/reference/general/runtime-modes.md create mode 100644 .agents/skills/ai-agent/reference/general/wasm-vs-native-sdk.md create mode 100644 .agents/skills/ai-agent/reference/self-hosting/configuration.md create mode 100644 .agents/skills/ai-agent/reference/self-hosting/docker-compose.md create mode 100644 .agents/skills/ai-agent/reference/self-hosting/docker-container.md create mode 100644 .agents/skills/ai-agent/reference/self-hosting/filesystem.md create mode 100644 .agents/skills/ai-agent/reference/self-hosting/foundationdb.md create mode 100644 .agents/skills/ai-agent/reference/self-hosting/install.md create mode 100644 .agents/skills/ai-agent/reference/self-hosting/kubernetes.md create mode 100644 .agents/skills/ai-agent/reference/self-hosting/multi-region.md create mode 100644 .agents/skills/ai-agent/reference/self-hosting/postgres.md create mode 100644 .agents/skills/ai-agent/reference/self-hosting/production-checklist.md create mode 100644 .agents/skills/ai-agent/reference/self-hosting/railway.md create mode 100644 .agents/skills/ai-agent/reference/self-hosting/render.md create mode 100644 .agents/skills/ai-agent/reference/self-hosting/tls.md create mode 100644 .agents/skills/chat-room/BASE_SKILL.md create mode 100644 .agents/skills/chat-room/SKILL.md create mode 100644 .agents/skills/chat-room/index.json create mode 100644 .agents/skills/chat-room/openapi.json create mode 100644 .agents/skills/chat-room/reference/actors/access-control.md create mode 100644 .agents/skills/chat-room/reference/actors/actions.md create mode 100644 .agents/skills/chat-room/reference/actors/actor-runtime-socket.md create mode 100644 .agents/skills/chat-room/reference/actors/appearance.md create mode 100644 .agents/skills/chat-room/reference/actors/authentication.md create mode 100644 .agents/skills/chat-room/reference/actors/communicating-between-actors.md create mode 100644 .agents/skills/chat-room/reference/actors/connections.md create mode 100644 .agents/skills/chat-room/reference/actors/debugging.md create mode 100644 .agents/skills/chat-room/reference/actors/design-patterns.md create mode 100644 .agents/skills/chat-room/reference/actors/destroy.md create mode 100644 .agents/skills/chat-room/reference/actors/errors.md create mode 100644 .agents/skills/chat-room/reference/actors/events.md create mode 100644 .agents/skills/chat-room/reference/actors/fetch-and-websocket-handler.md create mode 100644 .agents/skills/chat-room/reference/actors/helper-types.md create mode 100644 .agents/skills/chat-room/reference/actors/http-api.md create mode 100644 .agents/skills/chat-room/reference/actors/input.md create mode 100644 .agents/skills/chat-room/reference/actors/inspector-tabs.md create mode 100644 .agents/skills/chat-room/reference/actors/keys.md create mode 100644 .agents/skills/chat-room/reference/actors/kv.md create mode 100644 .agents/skills/chat-room/reference/actors/lifecycle.md create mode 100644 .agents/skills/chat-room/reference/actors/limits.md create mode 100644 .agents/skills/chat-room/reference/actors/metadata.md create mode 100644 .agents/skills/chat-room/reference/actors/queues.md create mode 100644 .agents/skills/chat-room/reference/actors/quickstart/backend.md create mode 100644 .agents/skills/chat-room/reference/actors/quickstart/cloudflare.md create mode 100644 .agents/skills/chat-room/reference/actors/quickstart/effect.md create mode 100644 .agents/skills/chat-room/reference/actors/quickstart/next-js.md create mode 100644 .agents/skills/chat-room/reference/actors/quickstart/react.md create mode 100644 .agents/skills/chat-room/reference/actors/quickstart/rust.md create mode 100644 .agents/skills/chat-room/reference/actors/quickstart/supabase.md create mode 100644 .agents/skills/chat-room/reference/actors/request-handler.md create mode 100644 .agents/skills/chat-room/reference/actors/scaling.md create mode 100644 .agents/skills/chat-room/reference/actors/schedule.md create mode 100644 .agents/skills/chat-room/reference/actors/sharing-and-joining-state.md create mode 100644 .agents/skills/chat-room/reference/actors/sqlite-drizzle.md create mode 100644 .agents/skills/chat-room/reference/actors/sqlite.md create mode 100644 .agents/skills/chat-room/reference/actors/state.md create mode 100644 .agents/skills/chat-room/reference/actors/statuses.md create mode 100644 .agents/skills/chat-room/reference/actors/testing.md create mode 100644 .agents/skills/chat-room/reference/actors/troubleshooting.md create mode 100644 .agents/skills/chat-room/reference/actors/types.md create mode 100644 .agents/skills/chat-room/reference/actors/versions.md create mode 100644 .agents/skills/chat-room/reference/actors/websocket-handler.md create mode 100644 .agents/skills/chat-room/reference/actors/workflows.md create mode 100644 .agents/skills/chat-room/reference/cli.md create mode 100644 .agents/skills/chat-room/reference/clients/javascript.md create mode 100644 .agents/skills/chat-room/reference/clients/react.md create mode 100644 .agents/skills/chat-room/reference/clients/rust.md create mode 100644 .agents/skills/chat-room/reference/clients/swift.md create mode 100644 .agents/skills/chat-room/reference/clients/swiftui.md create mode 100644 .agents/skills/chat-room/reference/cookbook/ai-agent.md create mode 100644 .agents/skills/chat-room/reference/cookbook/chat-room.md create mode 100644 .agents/skills/chat-room/reference/cookbook/collaborative-text-editor.md create mode 100644 .agents/skills/chat-room/reference/cookbook/cron-jobs.md create mode 100644 .agents/skills/chat-room/reference/cookbook/live-cursors.md create mode 100644 .agents/skills/chat-room/reference/cookbook/multiplayer-game.md create mode 100644 .agents/skills/chat-room/reference/cookbook/per-tenant-database.md create mode 100644 .agents/skills/chat-room/reference/cookbook/vpc-air-gapped.md create mode 100644 .agents/skills/chat-room/reference/deploy/aws-ecs.md create mode 100644 .agents/skills/chat-room/reference/deploy/aws-lambda.md create mode 100644 .agents/skills/chat-room/reference/deploy/cloudflare.md create mode 100644 .agents/skills/chat-room/reference/deploy/container-runner.md create mode 100644 .agents/skills/chat-room/reference/deploy/freestyle.md create mode 100644 .agents/skills/chat-room/reference/deploy/gcp-cloud-run.md create mode 100644 .agents/skills/chat-room/reference/deploy/hetzner.md create mode 100644 .agents/skills/chat-room/reference/deploy/kubernetes.md create mode 100644 .agents/skills/chat-room/reference/deploy/railway.md create mode 100644 .agents/skills/chat-room/reference/deploy/rivet-compute.md create mode 100644 .agents/skills/chat-room/reference/deploy/supabase.md create mode 100644 .agents/skills/chat-room/reference/deploy/vercel.md create mode 100644 .agents/skills/chat-room/reference/deploy/vm-and-bare-metal.md create mode 100644 .agents/skills/chat-room/reference/general/actor-configuration.md create mode 100644 .agents/skills/chat-room/reference/general/architecture.md create mode 100644 .agents/skills/chat-room/reference/general/cors.md create mode 100644 .agents/skills/chat-room/reference/general/docs-for-llms.md create mode 100644 .agents/skills/chat-room/reference/general/edge.md create mode 100644 .agents/skills/chat-room/reference/general/endpoints.md create mode 100644 .agents/skills/chat-room/reference/general/environment-variables.md create mode 100644 .agents/skills/chat-room/reference/general/http-server.md create mode 100644 .agents/skills/chat-room/reference/general/logging.md create mode 100644 .agents/skills/chat-room/reference/general/pool-configuration.md create mode 100644 .agents/skills/chat-room/reference/general/production-checklist.md create mode 100644 .agents/skills/chat-room/reference/general/registry-configuration.md create mode 100644 .agents/skills/chat-room/reference/general/runtime-modes.md create mode 100644 .agents/skills/chat-room/reference/general/wasm-vs-native-sdk.md create mode 100644 .agents/skills/chat-room/reference/self-hosting/configuration.md create mode 100644 .agents/skills/chat-room/reference/self-hosting/docker-compose.md create mode 100644 .agents/skills/chat-room/reference/self-hosting/docker-container.md create mode 100644 .agents/skills/chat-room/reference/self-hosting/filesystem.md create mode 100644 .agents/skills/chat-room/reference/self-hosting/foundationdb.md create mode 100644 .agents/skills/chat-room/reference/self-hosting/install.md create mode 100644 .agents/skills/chat-room/reference/self-hosting/kubernetes.md create mode 100644 .agents/skills/chat-room/reference/self-hosting/multi-region.md create mode 100644 .agents/skills/chat-room/reference/self-hosting/postgres.md create mode 100644 .agents/skills/chat-room/reference/self-hosting/production-checklist.md create mode 100644 .agents/skills/chat-room/reference/self-hosting/railway.md create mode 100644 .agents/skills/chat-room/reference/self-hosting/render.md create mode 100644 .agents/skills/chat-room/reference/self-hosting/tls.md create mode 100644 .agents/skills/cron-jobs/BASE_SKILL.md create mode 100644 .agents/skills/cron-jobs/SKILL.md create mode 100644 .agents/skills/cron-jobs/index.json create mode 100644 .agents/skills/cron-jobs/openapi.json create mode 100644 .agents/skills/cron-jobs/reference/actors/access-control.md create mode 100644 .agents/skills/cron-jobs/reference/actors/actions.md create mode 100644 .agents/skills/cron-jobs/reference/actors/actor-runtime-socket.md create mode 100644 .agents/skills/cron-jobs/reference/actors/appearance.md create mode 100644 .agents/skills/cron-jobs/reference/actors/authentication.md create mode 100644 .agents/skills/cron-jobs/reference/actors/communicating-between-actors.md create mode 100644 .agents/skills/cron-jobs/reference/actors/connections.md create mode 100644 .agents/skills/cron-jobs/reference/actors/debugging.md create mode 100644 .agents/skills/cron-jobs/reference/actors/design-patterns.md create mode 100644 .agents/skills/cron-jobs/reference/actors/destroy.md create mode 100644 .agents/skills/cron-jobs/reference/actors/errors.md create mode 100644 .agents/skills/cron-jobs/reference/actors/events.md create mode 100644 .agents/skills/cron-jobs/reference/actors/fetch-and-websocket-handler.md create mode 100644 .agents/skills/cron-jobs/reference/actors/helper-types.md create mode 100644 .agents/skills/cron-jobs/reference/actors/http-api.md create mode 100644 .agents/skills/cron-jobs/reference/actors/input.md create mode 100644 .agents/skills/cron-jobs/reference/actors/inspector-tabs.md create mode 100644 .agents/skills/cron-jobs/reference/actors/keys.md create mode 100644 .agents/skills/cron-jobs/reference/actors/kv.md create mode 100644 .agents/skills/cron-jobs/reference/actors/lifecycle.md create mode 100644 .agents/skills/cron-jobs/reference/actors/limits.md create mode 100644 .agents/skills/cron-jobs/reference/actors/metadata.md create mode 100644 .agents/skills/cron-jobs/reference/actors/queues.md create mode 100644 .agents/skills/cron-jobs/reference/actors/quickstart/backend.md create mode 100644 .agents/skills/cron-jobs/reference/actors/quickstart/cloudflare.md create mode 100644 .agents/skills/cron-jobs/reference/actors/quickstart/effect.md create mode 100644 .agents/skills/cron-jobs/reference/actors/quickstart/next-js.md create mode 100644 .agents/skills/cron-jobs/reference/actors/quickstart/react.md create mode 100644 .agents/skills/cron-jobs/reference/actors/quickstart/rust.md create mode 100644 .agents/skills/cron-jobs/reference/actors/quickstart/supabase.md create mode 100644 .agents/skills/cron-jobs/reference/actors/request-handler.md create mode 100644 .agents/skills/cron-jobs/reference/actors/scaling.md create mode 100644 .agents/skills/cron-jobs/reference/actors/schedule.md create mode 100644 .agents/skills/cron-jobs/reference/actors/sharing-and-joining-state.md create mode 100644 .agents/skills/cron-jobs/reference/actors/sqlite-drizzle.md create mode 100644 .agents/skills/cron-jobs/reference/actors/sqlite.md create mode 100644 .agents/skills/cron-jobs/reference/actors/state.md create mode 100644 .agents/skills/cron-jobs/reference/actors/statuses.md create mode 100644 .agents/skills/cron-jobs/reference/actors/testing.md create mode 100644 .agents/skills/cron-jobs/reference/actors/troubleshooting.md create mode 100644 .agents/skills/cron-jobs/reference/actors/types.md create mode 100644 .agents/skills/cron-jobs/reference/actors/versions.md create mode 100644 .agents/skills/cron-jobs/reference/actors/websocket-handler.md create mode 100644 .agents/skills/cron-jobs/reference/actors/workflows.md create mode 100644 .agents/skills/cron-jobs/reference/cli.md create mode 100644 .agents/skills/cron-jobs/reference/clients/javascript.md create mode 100644 .agents/skills/cron-jobs/reference/clients/react.md create mode 100644 .agents/skills/cron-jobs/reference/clients/rust.md create mode 100644 .agents/skills/cron-jobs/reference/clients/swift.md create mode 100644 .agents/skills/cron-jobs/reference/clients/swiftui.md create mode 100644 .agents/skills/cron-jobs/reference/cookbook/ai-agent.md create mode 100644 .agents/skills/cron-jobs/reference/cookbook/chat-room.md create mode 100644 .agents/skills/cron-jobs/reference/cookbook/collaborative-text-editor.md create mode 100644 .agents/skills/cron-jobs/reference/cookbook/cron-jobs.md create mode 100644 .agents/skills/cron-jobs/reference/cookbook/live-cursors.md create mode 100644 .agents/skills/cron-jobs/reference/cookbook/multiplayer-game.md create mode 100644 .agents/skills/cron-jobs/reference/cookbook/per-tenant-database.md create mode 100644 .agents/skills/cron-jobs/reference/cookbook/vpc-air-gapped.md create mode 100644 .agents/skills/cron-jobs/reference/deploy/aws-ecs.md create mode 100644 .agents/skills/cron-jobs/reference/deploy/aws-lambda.md create mode 100644 .agents/skills/cron-jobs/reference/deploy/cloudflare.md create mode 100644 .agents/skills/cron-jobs/reference/deploy/container-runner.md create mode 100644 .agents/skills/cron-jobs/reference/deploy/freestyle.md create mode 100644 .agents/skills/cron-jobs/reference/deploy/gcp-cloud-run.md create mode 100644 .agents/skills/cron-jobs/reference/deploy/hetzner.md create mode 100644 .agents/skills/cron-jobs/reference/deploy/kubernetes.md create mode 100644 .agents/skills/cron-jobs/reference/deploy/railway.md create mode 100644 .agents/skills/cron-jobs/reference/deploy/rivet-compute.md create mode 100644 .agents/skills/cron-jobs/reference/deploy/supabase.md create mode 100644 .agents/skills/cron-jobs/reference/deploy/vercel.md create mode 100644 .agents/skills/cron-jobs/reference/deploy/vm-and-bare-metal.md create mode 100644 .agents/skills/cron-jobs/reference/general/actor-configuration.md create mode 100644 .agents/skills/cron-jobs/reference/general/architecture.md create mode 100644 .agents/skills/cron-jobs/reference/general/cors.md create mode 100644 .agents/skills/cron-jobs/reference/general/docs-for-llms.md create mode 100644 .agents/skills/cron-jobs/reference/general/edge.md create mode 100644 .agents/skills/cron-jobs/reference/general/endpoints.md create mode 100644 .agents/skills/cron-jobs/reference/general/environment-variables.md create mode 100644 .agents/skills/cron-jobs/reference/general/http-server.md create mode 100644 .agents/skills/cron-jobs/reference/general/logging.md create mode 100644 .agents/skills/cron-jobs/reference/general/pool-configuration.md create mode 100644 .agents/skills/cron-jobs/reference/general/production-checklist.md create mode 100644 .agents/skills/cron-jobs/reference/general/registry-configuration.md create mode 100644 .agents/skills/cron-jobs/reference/general/runtime-modes.md create mode 100644 .agents/skills/cron-jobs/reference/general/wasm-vs-native-sdk.md create mode 100644 .agents/skills/cron-jobs/reference/self-hosting/configuration.md create mode 100644 .agents/skills/cron-jobs/reference/self-hosting/docker-compose.md create mode 100644 .agents/skills/cron-jobs/reference/self-hosting/docker-container.md create mode 100644 .agents/skills/cron-jobs/reference/self-hosting/filesystem.md create mode 100644 .agents/skills/cron-jobs/reference/self-hosting/foundationdb.md create mode 100644 .agents/skills/cron-jobs/reference/self-hosting/install.md create mode 100644 .agents/skills/cron-jobs/reference/self-hosting/kubernetes.md create mode 100644 .agents/skills/cron-jobs/reference/self-hosting/multi-region.md create mode 100644 .agents/skills/cron-jobs/reference/self-hosting/postgres.md create mode 100644 .agents/skills/cron-jobs/reference/self-hosting/production-checklist.md create mode 100644 .agents/skills/cron-jobs/reference/self-hosting/railway.md create mode 100644 .agents/skills/cron-jobs/reference/self-hosting/render.md create mode 100644 .agents/skills/cron-jobs/reference/self-hosting/tls.md create mode 100644 .agents/skills/rivetkit-client-javascript/SKILL.md create mode 100644 .agents/skills/rivetkit-client-javascript/index.json create mode 100644 .agents/skills/rivetkit-client-react/SKILL.md create mode 100644 .agents/skills/rivetkit-client-react/index.json create mode 100644 .agents/skills/rivetkit/SKILL.md create mode 100644 .agents/skills/rivetkit/index.json create mode 100644 .agents/skills/rivetkit/openapi.json create mode 100644 .agents/skills/rivetkit/reference/actors/access-control.md create mode 100644 .agents/skills/rivetkit/reference/actors/actions.md create mode 100644 .agents/skills/rivetkit/reference/actors/actor-runtime-socket.md create mode 100644 .agents/skills/rivetkit/reference/actors/appearance.md create mode 100644 .agents/skills/rivetkit/reference/actors/authentication.md create mode 100644 .agents/skills/rivetkit/reference/actors/communicating-between-actors.md create mode 100644 .agents/skills/rivetkit/reference/actors/connections.md create mode 100644 .agents/skills/rivetkit/reference/actors/debugging.md create mode 100644 .agents/skills/rivetkit/reference/actors/design-patterns.md create mode 100644 .agents/skills/rivetkit/reference/actors/destroy.md create mode 100644 .agents/skills/rivetkit/reference/actors/errors.md create mode 100644 .agents/skills/rivetkit/reference/actors/events.md create mode 100644 .agents/skills/rivetkit/reference/actors/fetch-and-websocket-handler.md create mode 100644 .agents/skills/rivetkit/reference/actors/helper-types.md create mode 100644 .agents/skills/rivetkit/reference/actors/http-api.md create mode 100644 .agents/skills/rivetkit/reference/actors/input.md create mode 100644 .agents/skills/rivetkit/reference/actors/inspector-tabs.md create mode 100644 .agents/skills/rivetkit/reference/actors/keys.md create mode 100644 .agents/skills/rivetkit/reference/actors/kv.md create mode 100644 .agents/skills/rivetkit/reference/actors/lifecycle.md create mode 100644 .agents/skills/rivetkit/reference/actors/limits.md create mode 100644 .agents/skills/rivetkit/reference/actors/metadata.md create mode 100644 .agents/skills/rivetkit/reference/actors/queues.md create mode 100644 .agents/skills/rivetkit/reference/actors/quickstart/backend.md create mode 100644 .agents/skills/rivetkit/reference/actors/quickstart/cloudflare.md create mode 100644 .agents/skills/rivetkit/reference/actors/quickstart/effect.md create mode 100644 .agents/skills/rivetkit/reference/actors/quickstart/next-js.md create mode 100644 .agents/skills/rivetkit/reference/actors/quickstart/react.md create mode 100644 .agents/skills/rivetkit/reference/actors/quickstart/rust.md create mode 100644 .agents/skills/rivetkit/reference/actors/quickstart/supabase.md create mode 100644 .agents/skills/rivetkit/reference/actors/request-handler.md create mode 100644 .agents/skills/rivetkit/reference/actors/scaling.md create mode 100644 .agents/skills/rivetkit/reference/actors/schedule.md create mode 100644 .agents/skills/rivetkit/reference/actors/sharing-and-joining-state.md create mode 100644 .agents/skills/rivetkit/reference/actors/sqlite-drizzle.md create mode 100644 .agents/skills/rivetkit/reference/actors/sqlite.md create mode 100644 .agents/skills/rivetkit/reference/actors/state.md create mode 100644 .agents/skills/rivetkit/reference/actors/statuses.md create mode 100644 .agents/skills/rivetkit/reference/actors/testing.md create mode 100644 .agents/skills/rivetkit/reference/actors/troubleshooting.md create mode 100644 .agents/skills/rivetkit/reference/actors/types.md create mode 100644 .agents/skills/rivetkit/reference/actors/versions.md create mode 100644 .agents/skills/rivetkit/reference/actors/websocket-handler.md create mode 100644 .agents/skills/rivetkit/reference/actors/workflows.md create mode 100644 .agents/skills/rivetkit/reference/cli.md create mode 100644 .agents/skills/rivetkit/reference/clients/javascript.md create mode 100644 .agents/skills/rivetkit/reference/clients/react.md create mode 100644 .agents/skills/rivetkit/reference/clients/rust.md create mode 100644 .agents/skills/rivetkit/reference/clients/swift.md create mode 100644 .agents/skills/rivetkit/reference/clients/swiftui.md create mode 100644 .agents/skills/rivetkit/reference/cookbook/ai-agent.md create mode 100644 .agents/skills/rivetkit/reference/cookbook/chat-room.md create mode 100644 .agents/skills/rivetkit/reference/cookbook/collaborative-text-editor.md create mode 100644 .agents/skills/rivetkit/reference/cookbook/cron-jobs.md create mode 100644 .agents/skills/rivetkit/reference/cookbook/live-cursors.md create mode 100644 .agents/skills/rivetkit/reference/cookbook/multiplayer-game.md create mode 100644 .agents/skills/rivetkit/reference/cookbook/per-tenant-database.md create mode 100644 .agents/skills/rivetkit/reference/cookbook/vpc-air-gapped.md create mode 100644 .agents/skills/rivetkit/reference/deploy/aws-ecs.md create mode 100644 .agents/skills/rivetkit/reference/deploy/aws-lambda.md create mode 100644 .agents/skills/rivetkit/reference/deploy/cloudflare.md create mode 100644 .agents/skills/rivetkit/reference/deploy/container-runner.md create mode 100644 .agents/skills/rivetkit/reference/deploy/freestyle.md create mode 100644 .agents/skills/rivetkit/reference/deploy/gcp-cloud-run.md create mode 100644 .agents/skills/rivetkit/reference/deploy/hetzner.md create mode 100644 .agents/skills/rivetkit/reference/deploy/kubernetes.md create mode 100644 .agents/skills/rivetkit/reference/deploy/railway.md create mode 100644 .agents/skills/rivetkit/reference/deploy/rivet-compute.md create mode 100644 .agents/skills/rivetkit/reference/deploy/supabase.md create mode 100644 .agents/skills/rivetkit/reference/deploy/vercel.md create mode 100644 .agents/skills/rivetkit/reference/deploy/vm-and-bare-metal.md create mode 100644 .agents/skills/rivetkit/reference/general/actor-configuration.md create mode 100644 .agents/skills/rivetkit/reference/general/architecture.md create mode 100644 .agents/skills/rivetkit/reference/general/cors.md create mode 100644 .agents/skills/rivetkit/reference/general/docs-for-llms.md create mode 100644 .agents/skills/rivetkit/reference/general/edge.md create mode 100644 .agents/skills/rivetkit/reference/general/endpoints.md create mode 100644 .agents/skills/rivetkit/reference/general/environment-variables.md create mode 100644 .agents/skills/rivetkit/reference/general/http-server.md create mode 100644 .agents/skills/rivetkit/reference/general/logging.md create mode 100644 .agents/skills/rivetkit/reference/general/pool-configuration.md create mode 100644 .agents/skills/rivetkit/reference/general/production-checklist.md create mode 100644 .agents/skills/rivetkit/reference/general/registry-configuration.md create mode 100644 .agents/skills/rivetkit/reference/general/runtime-modes.md create mode 100644 .agents/skills/rivetkit/reference/general/wasm-vs-native-sdk.md create mode 100644 .agents/skills/rivetkit/reference/self-hosting/configuration.md create mode 100644 .agents/skills/rivetkit/reference/self-hosting/docker-compose.md create mode 100644 .agents/skills/rivetkit/reference/self-hosting/docker-container.md create mode 100644 .agents/skills/rivetkit/reference/self-hosting/filesystem.md create mode 100644 .agents/skills/rivetkit/reference/self-hosting/foundationdb.md create mode 100644 .agents/skills/rivetkit/reference/self-hosting/install.md create mode 100644 .agents/skills/rivetkit/reference/self-hosting/kubernetes.md create mode 100644 .agents/skills/rivetkit/reference/self-hosting/multi-region.md create mode 100644 .agents/skills/rivetkit/reference/self-hosting/postgres.md create mode 100644 .agents/skills/rivetkit/reference/self-hosting/production-checklist.md create mode 100644 .agents/skills/rivetkit/reference/self-hosting/railway.md create mode 100644 .agents/skills/rivetkit/reference/self-hosting/render.md create mode 100644 .agents/skills/rivetkit/reference/self-hosting/tls.md create mode 100644 .agents/skills/sandbox-agent/SKILL.md create mode 100644 .agents/skills/sandbox-agent/references/agent-sessions.md create mode 100644 .agents/skills/sandbox-agent/references/agents/amp.md create mode 100644 .agents/skills/sandbox-agent/references/agents/claude.md create mode 100644 .agents/skills/sandbox-agent/references/agents/codex.md create mode 100644 .agents/skills/sandbox-agent/references/agents/cursor.md create mode 100644 .agents/skills/sandbox-agent/references/agents/opencode.md create mode 100644 .agents/skills/sandbox-agent/references/agents/pi.md create mode 100644 .agents/skills/sandbox-agent/references/ai/llms-txt.md create mode 100644 .agents/skills/sandbox-agent/references/ai/skill.md create mode 100644 .agents/skills/sandbox-agent/references/architecture.md create mode 100644 .agents/skills/sandbox-agent/references/attachments.md create mode 100644 .agents/skills/sandbox-agent/references/cli.md create mode 100644 .agents/skills/sandbox-agent/references/common-software.md create mode 100644 .agents/skills/sandbox-agent/references/computer-use.md create mode 100644 .agents/skills/sandbox-agent/references/cors.md create mode 100644 .agents/skills/sandbox-agent/references/custom-tools.md create mode 100644 .agents/skills/sandbox-agent/references/daemon.md create mode 100644 .agents/skills/sandbox-agent/references/deploy/agentcomputer.md create mode 100644 .agents/skills/sandbox-agent/references/deploy/boxlite.md create mode 100644 .agents/skills/sandbox-agent/references/deploy/cloudflare.md create mode 100644 .agents/skills/sandbox-agent/references/deploy/computesdk.md create mode 100644 .agents/skills/sandbox-agent/references/deploy/daytona.md create mode 100644 .agents/skills/sandbox-agent/references/deploy/docker.md create mode 100644 .agents/skills/sandbox-agent/references/deploy/e2b.md create mode 100644 .agents/skills/sandbox-agent/references/deploy/local.md create mode 100644 .agents/skills/sandbox-agent/references/deploy/modal.md create mode 100644 .agents/skills/sandbox-agent/references/deploy/vercel.md create mode 100644 .agents/skills/sandbox-agent/references/file-system.md create mode 100644 .agents/skills/sandbox-agent/references/inspector.md create mode 100644 .agents/skills/sandbox-agent/references/llm-credentials.md create mode 100644 .agents/skills/sandbox-agent/references/manage-sessions.md create mode 100644 .agents/skills/sandbox-agent/references/mcp-config.md create mode 100644 .agents/skills/sandbox-agent/references/multiplayer.md create mode 100644 .agents/skills/sandbox-agent/references/observability.md create mode 100644 .agents/skills/sandbox-agent/references/opencode-compatibility.md create mode 100644 .agents/skills/sandbox-agent/references/orchestration-architecture.md create mode 100644 .agents/skills/sandbox-agent/references/processes.md create mode 100644 .agents/skills/sandbox-agent/references/quickstart.md create mode 100644 .agents/skills/sandbox-agent/references/react-components.md create mode 100644 .agents/skills/sandbox-agent/references/sdk-overview.md create mode 100644 .agents/skills/sandbox-agent/references/security.md create mode 100644 .agents/skills/sandbox-agent/references/session-persistence.md create mode 100644 .agents/skills/sandbox-agent/references/session-restoration.md create mode 100644 .agents/skills/sandbox-agent/references/skills-config.md create mode 100644 .agents/skills/sandbox-agent/references/telemetry.md create mode 100644 .agents/skills/sandbox-agent/references/troubleshooting.md create mode 100644 .vscode/settings.json create mode 100644 AGENTS.md create mode 100644 apps/daemon/.env.example create mode 100644 apps/daemon/package.json create mode 100644 apps/daemon/src/agent-os.ts create mode 100644 apps/daemon/src/convex.ts create mode 100644 apps/daemon/src/index.ts create mode 100644 apps/daemon/src/runtime.ts create mode 100644 apps/daemon/tsconfig.json delete mode 100644 packages/agents/src/agents/hello-world.ts create mode 100644 packages/agents/src/agents/zopu.ts create mode 100644 packages/backend/convex/daemonCommands.ts create mode 100644 packages/backend/convex/daemonRuntime.ts create mode 100644 packages/backend/convex/daemons.ts create mode 100644 packages/env/src/server.ts create mode 100644 packages/primitives/package.json create mode 100644 packages/primitives/src/agent-os.ts create mode 100644 packages/primitives/src/index.ts create mode 100644 packages/primitives/tsconfig.json create mode 100644 scripts/subtree.ts create mode 100644 scripts/subtrees.json create mode 100644 scripts/tsconfig.json create mode 100644 scripts/update-docs.ts create mode 100644 skills-lock.json diff --git a/.agents/skills/ai-agent-workspace/BASE_SKILL.md b/.agents/skills/ai-agent-workspace/BASE_SKILL.md new file mode 100644 index 0000000..fc89a84 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/BASE_SKILL.md @@ -0,0 +1,1185 @@ +--- +name: "rivetkit" +description: "RivetKit backend and Rivet Actor runtime guidance. Use for building, modifying, debugging, or testing Rivet Actors, registries, serverless/runner modes, deployment, or actor-based workflows." +--- + +# Rivet Actors + +Build high-performance, long-lived, in-memory processes on Rivet's actor runtime. Use this skill whenever HTTP endpoints, databases, or queues no longer meet the requirements for AI agents, realtime collaboration, workflow orchestration, or geo-distributed data. + +## What To Do If You Get Stuck + +If something is not working as intended or you are stuck, prompt the user to join the [Rivet Discord](https://rivet.dev/discord) or file an issue on the [Rivet GitHub](https://github.com/rivet-dev/rivet) to report an issue and get help. + +Provide the user with a pre-generated report with: + +- Symptoms + - If this is happening in local dev, deployed, or both + - The error you're seeing + - Relevant source code related to this +- What you've tried to solve it +- Environment + - RivetKit version + - Runtime (Node, Bun, etc) including version + - If applicable, provider in use (e.g. Vercel, Railway, etc) + - If applicable, HTTP router in use (e.g. Hono, Express, Elysia) + +## Debugging Actors + +Use the inspector HTTP API to examine running actors. These endpoints are accessible through the gateway at `/gateway/{actor_id}/inspector/*`. Key endpoints: + +- `GET /inspector/summary` - full actor snapshot (state, connections, RPCs, queue) +- `GET /inspector/state` / `PATCH /inspector/state` - read/write actor state +- `GET /inspector/connections` - active connections +- `GET /inspector/rpcs` - available actions +- `POST /inspector/action/{name}` - execute an action with `{"args": [...]}` +- `POST /inspector/database/execute` - run SQL with `{"sql": "...", "args": [...]}` or `{"sql": "...", "properties": {...}}` for reads or mutations +- `GET /inspector/queue?limit=50` - queue status +- `GET /inspector/traces?startMs=0&endMs=...&limit=1000` - trace spans (OTLP JSON) +- `GET /inspector/workflow-history` - workflow history and status as JSON (`nameRegistry`, `entries`, `entryMetadata`) +- `POST /inspector/workflow/replay` - replay a workflow from a specific step or from the beginning; returns `409 actor/workflow_in_flight` if the workflow is still running +- `GET /inspector/database/schema` - SQLite tables and views exposed by `c.db` +- `GET /inspector/database/rows?table=...&limit=100&offset=0` - paged SQLite rows for a table or view + +In local dev, no auth token is needed. In production, pass `Authorization: Bearer `, where the inspector token is the actor-specific token auto-generated on first start and persisted in the actor's internal KV at key `0x03`. The Rivet dashboard retrieves this token automatically; for direct API access, fetch it through the management KV endpoint. See the [debugging docs](https://rivet.dev/docs/actors/debugging) for details. + +## Citing Sources + +When providing information from Rivet documentation, cite the canonical URL so users can learn more. Each reference file includes its canonical URL in the header metadata. + +**How to cite:** + +- Use inline links for key concepts: "Use [actor keys](https://rivet.dev/docs/actors/keys) to uniquely identify instances." +- Add a "Learn more" link after explanations for complex topics + +**Finding canonical URLs:** + +The Reference Map below links to reference files. Each file's header contains: + +``` +> Canonical URL: https://rivet.dev/docs/actors/actions +``` + +Use that canonical URL when citing, not the reference file path. + +**Examples:** + +- Actions → `https://rivet.dev/docs/actors/actions` +- React client → `https://rivet.dev/docs/clients/react` +- Self-hosting on Kubernetes → `https://rivet.dev/docs/self-hosting/kubernetes` + +## Version Check + +Before starting any work, check if the user's project is on the latest version of RivetKit (latest: 2.3.0-rc.12). Look at the `rivetkit` version in the user's `package.json` (check both `dependencies` and `devDependencies`). If the installed version is older than 2.3.0-rc.12, inform the user and suggest upgrading: + +```bash +npm install rivetkit@2.3.0-rc.12 +``` + +If the user also uses `@rivetkit/react`, `@rivetkit/next-js`, or other `@rivetkit/*` client packages, suggest upgrading those too. Outdated versions may have known bugs or missing features that cause issues. + +## First Steps + +1. Install RivetKit (latest: 2.3.0-rc.12) + ```bash + npm install rivetkit@2.3.0-rc.12 + ``` +2. Define a registry with `setup({ use: { /* actors */ } })`. +3. Call `registry.start()` to start the server. For custom HTTP server integration, use `registry.handler()` with a router like Hono. For serverless deployments, use `registry.serve()`. For runner-only mode, use `registry.startRunner()`. +4. Verify `/api/rivet/metadata` returns 200 before deploying. +5. Configure Rivet Cloud or self-hosted engine + - You must configure versioning for production builds. This is not needed for local development. See [Versions & Upgrades](https://rivet.dev/docs/actors/versions). +6. Integrate clients (see client guides below for JavaScript, React, or Swift) +7. Prompt the user if they want to deploy. If so, go to Deploying Rivet Backends. + +For more information, read the quickstart guide relevant to the user's project. + +## Project Setup + +### .gitignore + +Every RivetKit project should have a `.gitignore`. Include at minimum: + +``` +node_modules/ +dist/ +.env +``` + +### .dockerignore + +Every project with a Dockerfile should have a `.dockerignore` to keep the image small and avoid leaking secrets: + +``` +node_modules/ +dist/ +.env +.git/ +``` + +### Dockerfile + +Use this as a base Dockerfile for deploying a RivetKit project. The `RIVET_RUNNER_VERSION` build arg is only needed when self-hosting or using a custom runner (not needed for Rivet Compute). It lets Rivet track which version of the actor is running and drain old actors on deploy. See https://rivet.dev/docs/actors/versions for details. + +```dockerfile +FROM node:24-alpine + +ARG RIVET_RUNNER_VERSION +ENV RIVET_RUNNER_VERSION=$RIVET_RUNNER_VERSION + +WORKDIR /app + +COPY package.json package-lock.json ./ +RUN npm ci + +COPY . . +RUN npm run build --if-present + +CMD ["node", "dist/index.js"] +``` + +Build with: + +```bash +docker build --build-arg RIVET_RUNNER_VERSION=$(date +%s) . +``` + +Adjust the `CMD` to match the project's entry point. If the project uses a different output directory or start command, update accordingly. + +## Error Handling Policy + +- Prefer fail-fast behavior by default. +- Avoid `try/catch` unless it is required for a real recovery path, cleanup boundary, or to add actionable context. +- Never swallow errors. If you add a `catch`, you must handle the error explicitly, at minimum by logging it. +- When you cannot recover, log context and rethrow. + +## State vs Vars: Persistence Rules + +**`c.vars` is ephemeral.** Data in `c.vars` is lost on every restart, crash, upgrade, or sleep/wake cycle. Only use `c.vars` for non-serializable objects (e.g., physics engines, WebSocket references, event emitters, caches) or truly transient runtime data (e.g., current input direction that doesn't matter after disconnect). + +**Persistent storage options.** Any data that must survive restarts belongs in one of these, NOT in `c.vars`: + +- **`c.state`** — CBOR-serializable data for small, bounded datasets. Ideal for configuration, counters, small player lists, phase flags, etc. Keep under 128 KB. Do not store unbounded or growing data here (e.g., chat logs, event histories, spawned entity lists that grow without limit). State is read/written as a single blob on every persistence cycle. +- **`c.kv`** — Key-value store for unbounded data. This is what `c.state` uses under the hood. Supports binary values. Use for larger or variable-size data like user inventories, world chunks, file blobs, or any collection that may grow over time. Keys are scoped to the actor instance. +- **`c.db`** — SQLite database for structured or complex data. Use when you need queries, indexes, joins, aggregations, or relational modeling. Ideal for leaderboards, match histories, player pools, or any data that benefits from SQL. + +**Common mistake:** Storing meaningful game/application data in `c.vars` instead of persisting it. For example, if users can spawn objects in a physics simulation, the spawn definitions (position, size, type) must be persisted in `c.state` (or `c.kv` if unbounded), even though the physics engine handles (non-serializable) live in `c.vars`. On restart, `run()` should recreate the runtime objects from the persisted data. + +## Deploying Rivet Backends + +Assume the user is deploying to Rivet Cloud, unless otherwise specified. If user is self-hosting, read the self-hosting guides below. + +1. Verify that Rivet Actors are working in local dev +2. Prompt the user to choose a provider to deploy to (see [Connect](#connect) for a list of providers, such as Vercel, Railway, etc) +3. Follow the deploy guide for that given provider. You will need to instruct the user when you need manual intervention. + +## API Reference + +The RivetKit OpenAPI specification is available in the skill directory at `openapi.json`. This file documents all HTTP endpoints for managing actors. + +## Misc Notes + +- The Rivet domain is rivet.dev, not rivet.gg + +## TypeScript Caveat: Actor Client Inference + +- In multi-file TypeScript projects, bidirectional actor calls can create a circular type dependency when both actors use `c.client()`. +- Symptoms usually include `c.state` becoming `unknown`, actor methods becoming possibly `undefined`, or `TS2322` / `TS2722` errors after the first cross-actor call. +- If an action returns the result of another actor call, prefer an explicit return type annotation on that action instead of relying on inference through `c.client()`. +- If explicit return types are not enough, use a narrower client or registry type for only the actors that action needs. +- As a last resort, pass `unknown` for the registry type and be explicit that this gives up type safety at that call site. + +## Features + +- **Long-Lived, Stateful Compute**: Each unit of compute is like a tiny server that remembers things between requests – no need to re-fetch data from a database or worry about timeouts. Like AWS Lambda, but with memory and no timeouts. +- **Blazing-Fast Reads & Writes**: State is stored on the same machine as your compute, so reads and writes are ultra-fast. No database round trips, no latency spikes. State is persisted to Rivet for long term storage, so it survives server restarts. +- **Realtime**: Update state and broadcast changes in realtime with WebSockets. No external pub/sub systems, no polling – just built-in low-latency events. +- **Infinitely Scalable**: Automatically scale from zero to millions of concurrent actors. Pay only for what you use with instant scaling and no cold starts. +- **Fault Tolerant**: Built-in error handling and recovery. Actors automatically restart on failure while preserving state integrity and continuing operations. + +## When to Use Rivet Actors + +- **AI agents & sandboxes**: multi-step toolchains, conversation memory, sandbox orchestration. +- **Multiplayer or collaborative apps**: CRDT docs, shared cursors, realtime dashboards, chat. +- **Workflow automation**: background jobs, cron, rate limiters, durable queues, backpressure control. +- **Data-intensive backends**: geo-distributed or per-tenant databases, in-memory caches, sharded SQL. +- **Networking workloads**: WebSocket servers, custom protocols, local-first sync, edge fanout. + +## Minimal Project + +### Backend + +**index.ts** + +```ts +import { actor, event, setup } from "rivetkit"; + +const counter = actor({ + state: { count: 0 }, + events: { + count: event(), + }, + actions: { + increment: (c, amount: number) => { + c.state.count += amount; + c.broadcast("count", c.state.count); + return c.state.count; + }, + }, +}); + +export const registry = setup({ + use: { counter }, +}); + +registry.start(); +``` + +### Client Docs + +Use the client SDK that matches your app: + +- [JavaScript Client](/docs/clients/javascript) +- [React Client](/docs/clients/react) +- [Swift Client](/docs/clients/swift) + +## Actor Quick Reference + +### In-Memory State + +Persistent data that survives restarts, crashes, and deployments. State is persisted on Rivet Cloud or Rivet self-hosted, so it survives restarts if the current process crashes or exits. + +### Static Initial State + +```ts +import { actor } from "rivetkit"; + +const counter = actor({ +state: { count: 0 }, +actions: { +increment: (c) => c.state.count += 1, +}, +}); + +```` + +### Dynamic Initial State + +```ts +import { actor } from "rivetkit"; + +interface CounterState { + count: number; +} + +const counter = actor({ + createState: (c, input: { start?: number }): CounterState => ({ + count: input.start ?? 0, + }), + actions: { + increment: (c) => c.state.count += 1, + }, +}); +```` + +[Documentation](/docs/actors/state) + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```ts +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +const chatRoom = actor({ + state: { messages: [] as string[] }, + actions: { + getRoomInfo: (c) => ({ org: c.key[0], room: c.key[1] }), + }, +}); + +const registry = setup({ use: { chatRoom } }); +const client = createClient("http://localhost:6420"); + +// Compound key: [org, room] +client.chatRoom.getOrCreate(["org-acme", "general"]); + +// Access key inside actor via c.key +``` + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +[Documentation](/docs/actors/keys) + +### Input + +Pass initialization data when creating actors. Input is only available in `createState` and `onCreate`, so store it in state if you need it later. + +```ts +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +const game = actor({ + state: { mode: "" }, + createState: (c, input: { mode: string }) => ({ + mode: input.mode, // Store input in state for later access + }), + actions: { + getMode: (c) => c.state.mode, + }, +}); + +const registry = setup({ use: { game } }); +const client = createClient("http://localhost:6420"); + +// Client usage +const gameHandle = client.game.getOrCreate(["game-1"], { + createWithInput: { mode: "ranked" }, +}); +``` + +[Documentation](/docs/actors/input) + +### Temporary Variables + +Temporary data that doesn't survive restarts. Use for non-serializable objects (event emitters, connections, etc). + +### Static Initial Vars + +```ts +import { actor } from "rivetkit"; + +const counter = actor({ +state: { count: 0 }, +vars: { lastAccess: 0 }, +actions: { +increment: (c) => { +c.vars.lastAccess = Date.now(); +return c.state.count += 1; +}, +}, +}); + +```` + +### Dynamic Initial Vars + +```ts +import { actor } from "rivetkit"; + +const counter = actor({ + state: { count: 0 }, + createVars: () => ({ + emitter: new EventTarget(), + }), + actions: { + increment: (c) => { + c.vars.emitter.dispatchEvent(new Event("change")); + return c.state.count += 1; + }, + }, +}); +```` + +[Documentation](/docs/actors/state) + +### Actions + +Actions are the primary way clients and other actors communicate with an actor. + +```ts +import { actor } from "rivetkit"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount: number) => (c.state.count += amount), + getCount: (c) => c.state.count, + }, +}); +``` + +[Documentation](/docs/actors/actions) + +### Events & Broadcasts + +Events enable real-time communication from actors to connected clients. + +```ts +import { actor, event } from "rivetkit"; + +const chatRoom = actor({ + state: { messages: [] as string[] }, + events: { + newMessage: event<{ text: string }>(), + }, + actions: { + sendMessage: (c, text: string) => { + // Broadcast to ALL connected clients + c.broadcast("newMessage", { text }); + }, + }, +}); +``` + +[Documentation](/docs/actors/events) + +### Connections + +Access the current connection via `c.conn` or all connected clients via `c.conns`. Use `c.conn.id` or `c.conn.state` to securely identify who is calling an action. `c.conn` is only available for actions invoked through a connected client; stateless actor-handle calls run without a connection, so guard against that. Connection state is initialized via `connState` or `createConnState`, which receives parameters passed by the client on connect. + +### Static Connection Initial State + +```ts +import { actor } from "rivetkit"; + +const chatRoom = actor({ +state: {}, +connState: { visitorId: 0 }, +onConnect: (c, conn) => { +conn.state.visitorId = Math.random(); +}, +actions: { +whoAmI: (c) => c.conn.state.visitorId, +}, +}); + +```` + +### Dynamic Connection Initial State + +```ts +import { actor } from "rivetkit"; + +const chatRoom = actor({ + state: {}, + // params passed from client + createConnState: (c, params: { userId: string }) => ({ + userId: params.userId, + }), + actions: { + // Access current connection's state and params + whoAmI: (c) => ({ + state: c.conn.state, + params: c.conn.params, + }), + // Iterate all connections with c.conns + notifyOthers: (c, text: string) => { + for (const conn of c.conns.values()) { + if (conn !== c.conn) conn.send("notification", { text }); + } + }, + }, +}); +```` + +[Documentation](/docs/actors/connections) + +### Queues + +Use queues to process durable messages in order inside a `run` loop. + +```ts +import { actor, queue } from "rivetkit"; + +const counter = actor({ + state: { value: 0 }, + queues: { + increment: queue<{ amount: number }>(), + }, + run: async (c) => { + for await (const message of c.queue.iter()) { + c.state.value += message.body.amount; + } + }, +}); +``` + +[Documentation](/docs/actors/queues) + +### Workflows + +Use workflows when your `run` logic needs durable, replayable multi-step execution. + +```ts +import { actor, queue } from "rivetkit"; +import { workflow } from "rivetkit/workflow"; + +const worker = actor({ + state: { processed: 0 }, + queues: { + tasks: queue<{ url: string }>(), + }, + run: workflow(async (ctx) => { + await ctx.loop("task-loop", async (loopCtx) => { + const message = await loopCtx.queue.next("wait-task"); + + await loopCtx.step("process-task", async () => { + await processTask(message.body.url); + loopCtx.state.processed += 1; + }); + }); + }), +}); + +async function processTask(url: string): Promise { + const res = await fetch(url, { method: "POST" }); + if (!res.ok) throw new Error(`Task failed: ${res.status}`); +} +``` + +[Documentation](/docs/actors/workflows) + +### Actor-to-Actor Communication + +Actors can call other actors using `c.client()`. + +```ts +import { actor, setup } from "rivetkit"; + +const inventory = actor({ + state: { stock: 100 }, + actions: { + reserve: (c, amount: number) => { + c.state.stock -= amount; + }, + }, +}); + +const order = actor({ + state: {}, + actions: { + process: async (c) => { + const client = c.client(); + await client.inventory.getOrCreate(["main"]).reserve(1); + }, + }, +}); + +const registry = setup({ use: { inventory, order } }); +``` + +[Documentation](/docs/actors/communicating-between-actors) + +### Scheduling + +Schedule actions to run after a delay or at a specific time. Schedules persist across restarts, upgrades, and crashes. + +```ts +import { actor, event } from "rivetkit"; + +const reminder = actor({ + state: { message: "" }, + events: { + reminder: event<{ message: string }>(), + }, + actions: { + // Schedule action to run after delay (ms) + setReminder: (c, message: string, delayMs: number) => { + c.state.message = message; + c.schedule.after(delayMs, "sendReminder"); + }, + // Schedule action to run at specific timestamp + setReminderAt: (c, message: string, timestamp: number) => { + c.state.message = message; + c.schedule.at(timestamp, "sendReminder"); + }, + sendReminder: (c) => { + c.broadcast("reminder", { message: c.state.message }); + }, + }, +}); +``` + +[Documentation](/docs/actors/schedule) + +### Destroying Actors + +Permanently delete an actor and its state using `c.destroy()`. + +```ts +import { actor } from "rivetkit"; + +const userAccount = actor({ + state: { email: "", name: "" }, + onDestroy: (c) => { + console.log(`Account ${c.state.email} deleted`); + }, + actions: { + deleteAccount: (c) => { + c.destroy(); + }, + }, +}); +``` + +[Documentation](/docs/actors/destroy) + +### Lifecycle Hooks + +Actors support hooks for initialization, background processing, connections, networking, and state changes. Use `run` for long-lived background loops, and use `c.aborted` or `c.abortSignal` for graceful shutdown. + +```ts +import { actor, event, queue } from "rivetkit"; + +interface RoomState { + users: Record; + name?: string; +} + +interface RoomInput { + roomName: string; +} + +interface ConnState { + userId: string; + joinedAt: number; +} + +const chatRoom = actor({ + events: { + stateChanged: event(), + }, + queues: { + work: queue<{ task: string }>(), + }, + + // State & vars initialization + createState: (c, input: RoomInput): RoomState => ({ + users: {}, + name: input.roomName, + }), + createVars: () => ({ startTime: Date.now() }), + + // Actor lifecycle + onCreate: (c) => console.log("created", c.key), + onDestroy: (c) => console.log("destroyed"), + onWake: (c) => console.log("actor started"), + onSleep: (c) => console.log("actor sleeping"), + run: async (c) => { + for await (const message of c.queue.iter()) { + console.log("processing", message.body.task); + } + }, + onStateChange: (c, newState) => c.broadcast("stateChanged", newState), + + // Connection lifecycle + createConnState: (c, params): ConnState => ({ + userId: (params as { userId: string }).userId, + joinedAt: Date.now(), + }), + onBeforeConnect: (c, params) => { + /* validate auth */ + }, + onConnect: (c, conn) => console.log("connected:", (conn.state as ConnState).userId), + onDisconnect: (c, conn) => console.log("disconnected:", (conn.state as ConnState).userId), + + // Networking + onRequest: (c, req) => new Response(JSON.stringify(c.state)), + onWebSocket: (c, socket) => socket.addEventListener("message", console.log), + + // Response transformation + onBeforeActionResponse: ( + c: unknown, + name: string, + args: unknown[], + output: Out, + ): Out => output, + + actions: {}, +}); +``` + +[Documentation](/docs/actors/lifecycle) + +### Context Types + +When writing helper functions outside the actor definition, use `*ContextOf` to extract the correct context type. Helpers like `ActionContextOf`, `CreateContextOf`, `ConnContextOf`, and `ConnInitContextOf` are exported from `"rivetkit"`. Do not manually define your own context interface. Always derive it from the actor definition. + +```ts +import { actor, ActionContextOf } from "rivetkit"; + +const gameRoom = actor({ + state: { players: [] as string[], score: 0 }, + actions: { + addPlayer: (c, playerId: string) => { + validatePlayer(c, playerId); + c.state.players.push(playerId); + }, + }, +}); + +// Good: derive context type from actor definition +function validatePlayer(c: ActionContextOf, playerId: string) { + if (c.state.players.includes(playerId)) { + throw new Error("Player already in room"); + } +} + +// Bad: don't manually define context types like this +// type MyContext = { state: { players: string[] }; ... }; +``` + +[Documentation](/docs/actors/types) + +### Errors + +Use `UserError` to throw errors that are safely returned to clients. Pass `metadata` to include structured data. Other errors are converted to generic "internal error" for security. + +### Actor + +```ts +import { actor, UserError } from "rivetkit"; + +const user = actor({ +state: { username: "" }, +actions: { +updateUsername: (c, username: string) => { +if (username.length < 3) { +throw new UserError("Username too short", { +code: "username_too_short", +metadata: { minLength: 3, actual: username.length }, +}); +} +c.state.username = username; +}, +}, +}); + +```` + +### Client + +```ts +import { actor, setup, UserError } from "rivetkit"; +import { createClient, ActorError } from "rivetkit/client"; + +const user = actor({ + state: { username: "" }, + actions: { + updateUsername: (c, username: string) => { + if (username.length < 3) { + throw new UserError("Username too short", { + code: "username_too_short", + metadata: { minLength: 3, actual: username.length }, + }); + } + c.state.username = username; + }, + }, +}); + +const registry = setup({ use: { user } }); +const client = createClient("http://localhost:6420"); + +try { + await client.user.getOrCreate([]).updateUsername("ab"); +} catch (error) { + if (error instanceof ActorError) { + console.log(error.code); // "username_too_short" + console.log(error.metadata); // { minLength: 3, actual: 2 } + } +} +```` + +[Documentation](/docs/actors/errors) + +### Low-Level HTTP & WebSocket Handlers + +For custom protocols or integrating libraries that need direct access to HTTP `Request`/`Response` or WebSocket connections, use `onRequest` and `onWebSocket`. + +[HTTP Handler Documentation](/docs/actors/request-handler) · [WebSocket Handler Documentation](/docs/actors/websocket-handler) + +### Icons & Names + +Customize how actors appear in the UI with display names and icons. It's recommended to always provide a name and icon to actors in order to make them easier to distinguish in the dashboard. + +```typescript +import { actor } from "rivetkit"; + +const chatRoom = actor({ + options: { + name: "Chat Room", + icon: "💬", // or FontAwesome: "comments", "chart-line", etc. + }, + // ... +}); +``` + +[Documentation](/docs/actors/appearance) + +## Client Documentation + +Find the full client guides here: + +- [JavaScript Client](/docs/clients/javascript) +- [React Client](/docs/clients/react) +- [Swift Client](/docs/clients/swift) + +## Common Patterns + +Actors scale naturally through isolated state and message-passing. Structure your applications with these patterns: + +[Documentation](/docs/actors/design-patterns) + +### Actor Per Entity + +Create one actor per user, document, or room. Use compound keys to scope entities: + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +// Single key: one actor per user +client.user.getOrCreate(["user-123"]); + +// Compound key: document scoped to an organization +client.document.getOrCreate(["org-acme", "doc-456"]); + +```` + +```ts index.ts +import { actor, setup } from "rivetkit"; + +export const user = actor({ + state: { name: "" }, + actions: {}, +}); + +export const document = actor({ + state: { content: "" }, + actions: {}, +}); + +export const registry = setup({ use: { user, document } }); + +registry.start(); +```` + +### Coordinator & Data Actors + +**Data actors** handle core logic (chat rooms, game sessions, user data). **Coordinator actors** track and manage collections of data actors—think of them as an index. + +```ts index.ts +import { actor, setup } from "rivetkit"; + +// Coordinator: tracks chat rooms within an organization +export const chatRoomList = actor({ +state: { rooms: [] as string[] }, +actions: { +addRoom: async (c, name: string) => { +// Create the chat room actor +const client = c.client(); +await client.chatRoom.create([c.key[0], name]); +c.state.rooms.push(name); +}, +listRooms: (c) => c.state.rooms, +}, +}); + +// Data actor: handles a single chat room +export const chatRoom = actor({ +state: { messages: [] as string[] }, +actions: { +send: (c, msg: string) => { c.state.messages.push(msg); }, +}, +}); + +export const registry = setup({ use: { chatRoomList, chatRoom } }); + +registry.start(); + +```` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +// Coordinator per org +const coordinator = client.chatRoomList.getOrCreate(["org-acme"]); +await coordinator.addRoom("general"); +await coordinator.addRoom("random"); + +// Access chat rooms created by coordinator +client.chatRoom.get(["org-acme", "general"]); +```` + +### Run Loop + +Use a `run` loop for continuous background work inside an actor. Process queue messages in order, run logic on intervals, stream AI responses, or coordinate long-running tasks. + +```ts +import { actor, queue, setup } from "rivetkit"; + +const counterWorker = actor({ + state: { value: 0 }, + queues: { + mutate: queue<{ delta: number }>(), + }, + run: async (c) => { + for await (const message of c.queue.iter()) { + c.state.value += message.body.delta; + } + }, + actions: { + getValue: (c) => c.state.value, + }, +}); + +const registry = setup({ use: { counterWorker } }); +``` + +### Workflow Loop + +Use this pattern for long-lived, durable workflows that initialize resources, process commands in a loop, then clean up. + +```ts +import { actor, queue, setup } from "rivetkit"; +import { Loop, workflow } from "rivetkit/workflow"; + +type WorkMessage = { amount: number }; +type ControlMessage = { type: "stop"; reason: string }; + +const worker = actor({ + state: { + phase: "idle" as "idle" | "running" | "stopped", + processed: 0, + total: 0, + stopReason: null as string | null, + }, + queues: { + work: queue(), + control: queue(), + }, + run: workflow(async (ctx) => { + await ctx.step("setup", async () => { + await fetch("https://api.example.com/workers/init", { + method: "POST", + }); + ctx.state.phase = "running"; + ctx.state.stopReason = null; + }); + + const stopReason = await ctx.loop("worker-loop", async (loopCtx) => { + const message = await loopCtx.queue.next("wait-command", { + names: ["work", "control"], + }); + + if (message.name === "work") { + await loopCtx.step("apply-work", async () => { + await fetch("https://api.example.com/workers/process", { + method: "POST", + body: JSON.stringify({ amount: message.body.amount }), + }); + loopCtx.state.processed += 1; + loopCtx.state.total += message.body.amount; + }); + return; + } + + return Loop.break((message.body as ControlMessage).reason); + }); + + await ctx.step("teardown", async () => { + await fetch("https://api.example.com/workers/shutdown", { + method: "POST", + }); + ctx.state.phase = "stopped"; + ctx.state.stopReason = stopReason; + }); + }), +}); + +const registry = setup({ use: { worker } }); +``` + +[Documentation](/docs/actors/workflows) + +### Actions vs Queues + +- **Actions** are not durable. Use them for realtime reads, ephemeral data, and low-latency communication like player input. +- **Queues** are durable. Use them to serialize mutations through the run loop, avoiding race conditions with SQLite and other local state. Callers can still wait for a response from queued work. + +### Authentication, Security, & CORS + +- Validate credentials in `onBeforeConnect` or `createConnState` and throw an error to reject unauthorized connections. +- Use `c.conn.state` to securely identify users in actions rather than trusting action parameters. +- For cross-origin access, validate the request origin in `onBeforeConnect`. + +[Authentication Documentation](/docs/actors/authentication) · [CORS Documentation](/docs/general/cors) + +### Versions & Upgrades + +When deploying new code, set a version number so Rivet can route new actors to the latest runner and optionally drain old ones. Use a build timestamp, git commit count, or CI build number as the version. It is very important to [configure versioning](/docs/actors/versions) before deploying to production. Without versioning, actors can regress by running on older runner versions, and existing actors will never be forced to migrate to new runners. They will continue running indefinitely on the old runners until they exit. + +[Documentation](/docs/actors/versions) + +### Anti-Patterns + +#### Never build a "god" actor + +Do not put all your logic in a single actor. A god actor serializes every operation through one bottleneck, kills parallelism, and makes the entire system fail as a unit. Split into focused actors per entity. + +#### Never create an actor per request + +Actors are long-lived and maintain state across requests. Creating a new actor for every incoming request throws away the core benefit of the model and wastes resources on actor creation and teardown. Use actors for persistent entities and regular functions for stateless work. + +## Reference Map + +### Actors + +- [Access Control](reference/actors/access-control.md) +- [Actions](reference/actors/actions.md) +- [Actor Keys](reference/actors/keys.md) +- [Actor Scheduling](reference/actors/schedule.md) +- [Actor Statuses](reference/actors/statuses.md) +- [Authentication](reference/actors/authentication.md) +- [Cloudflare Workers Quickstart](reference/actors/quickstart/cloudflare.md) +- [Communicating Between Actors](reference/actors/communicating-between-actors.md) +- [Connections](reference/actors/connections.md) +- [Custom Inspector Tabs](reference/actors/inspector-tabs.md) +- [Debugging](reference/actors/debugging.md) +- [Design Patterns](reference/actors/design-patterns.md) +- [Destroying Actors](reference/actors/destroy.md) +- [Effect.ts Quickstart (Beta)](reference/actors/quickstart/effect.md) +- [Errors](reference/actors/errors.md) +- [Fetch and WebSocket Handler](reference/actors/fetch-and-websocket-handler.md) +- [Helper Types](reference/actors/helper-types.md) +- [Icons & Names](reference/actors/appearance.md) +- [In-Memory State](reference/actors/state.md) +- [Input Parameters](reference/actors/input.md) +- [Lifecycle](reference/actors/lifecycle.md) +- [Limits](reference/actors/limits.md) +- [Low-Level HTTP Request Handler](reference/actors/request-handler.md) +- [Low-Level KV Storage](reference/actors/kv.md) +- [Low-Level WebSocket Handler](reference/actors/websocket-handler.md) +- [Metadata](reference/actors/metadata.md) +- [Next.js Quickstart](reference/actors/quickstart/next-js.md) +- [Node.js & Bun Quickstart](reference/actors/quickstart/backend.md) +- [Queues & Run Loops](reference/actors/queues.md) +- [React Quickstart](reference/actors/quickstart/react.md) +- [Realtime](reference/actors/events.md) +- [Rust Quickstart (Beta)](reference/actors/quickstart/rust.md) +- [Scaling & Concurrency](reference/actors/scaling.md) +- [Sharing and Joining State](reference/actors/sharing-and-joining-state.md) +- [SQLite](reference/actors/sqlite.md) +- [SQLite + Drizzle](reference/actors/sqlite-drizzle.md) +- [Supabase Functions Quickstart](reference/actors/quickstart/supabase.md) +- [Testing](reference/actors/testing.md) +- [Troubleshooting](reference/actors/troubleshooting.md) +- [Types](reference/actors/types.md) +- [Vanilla HTTP API](reference/actors/http-api.md) +- [Versions & Upgrades](reference/actors/versions.md) +- [Workflows](reference/actors/workflows.md) + +### Agent Os + +- [Agent-to-Agent Communication](reference/agent-os/agent-to-agent.md) +- [agentOS vs Sandbox](reference/agent-os/versus-sandbox.md) +- [Authentication](reference/agent-os/authentication.md) +- [Benchmarks](reference/agent-os/benchmarks.md) +- [Configuration](reference/agent-os/configuration.md) +- [Core Package](reference/agent-os/core.md) +- [Crash Course](reference/agent-os/crash-course.md) +- [Cron Jobs](reference/agent-os/cron.md) +- [Deployment](reference/agent-os/deployment.md) +- [Embedded LLM Gateway](reference/agent-os/llm-gateway.md) +- [Events](reference/agent-os/events.md) +- [Filesystem](reference/agent-os/filesystem.md) +- [Limitations](reference/agent-os/limitations.md) +- [LLM Credentials](reference/agent-os/llm-credentials.md) +- [Multiplayer](reference/agent-os/multiplayer.md) +- [Networking & Previews](reference/agent-os/networking.md) +- [Permissions](reference/agent-os/permissions.md) +- [Persistence & Sleep](reference/agent-os/persistence.md) +- [Pi](reference/agent-os/agents/pi.md) +- [Processes & Shell](reference/agent-os/processes.md) +- [Queues](reference/agent-os/queues.md) +- [Quickstart](reference/agent-os/quickstart.md) +- [Sandbox Mounting](reference/agent-os/sandbox.md) +- [Security & Auth](reference/agent-os/security.md) +- [Security Model](reference/agent-os/security-model.md) +- [Sessions](reference/agent-os/sessions.md) +- [Software](reference/agent-os/software.md) +- [SQLite](reference/agent-os/sqlite.md) +- [System Prompt](reference/agent-os/system-prompt.md) +- [Tools](reference/agent-os/tools.md) +- [Webhooks](reference/agent-os/webhooks.md) +- [Workflow Automation](reference/agent-os/workflows.md) + +### Cli + +- [CLI](reference/cli.md) + +### Clients + +- [Node.js & Bun](reference/clients/javascript.md) +- [React](reference/clients/react.md) +- [Swift](reference/clients/swift.md) +- [SwiftUI](reference/clients/swiftui.md) + +### Cookbook + +- [AI Agent](reference/cookbook/ai-agent.md) +- [AI Agent Workspaces](reference/cookbook/ai-agent-workspace.md) +- [Chat Room](reference/cookbook/chat-room.md) +- [Collaborative Text Editor](reference/cookbook/collaborative-text-editor.md) +- [Cron Jobs and Scheduled Tasks](reference/cookbook/cron-jobs.md) +- [Database per Tenant](reference/cookbook/per-tenant-database.md) +- [Deploying Rivet in a VPC or Air-Gapped Network](reference/cookbook/vpc-air-gapped.md) +- [Live Cursors and Presence](reference/cookbook/live-cursors.md) +- [Multiplayer Game](reference/cookbook/multiplayer-game.md) + +### Deploy + +- [Deploy To Amazon Web Services Lambda](reference/deploy/aws-lambda.md) +- [Deploying to AWS ECS](reference/deploy/aws-ecs.md) +- [Deploying to Cloudflare Workers](reference/deploy/cloudflare.md) +- [Deploying to Freestyle](reference/deploy/freestyle.md) +- [Deploying to Google Cloud Run](reference/deploy/gcp-cloud-run.md) +- [Deploying to Hetzner](reference/deploy/hetzner.md) +- [Deploying to Kubernetes](reference/deploy/kubernetes.md) +- [Deploying to Railway](reference/deploy/railway.md) +- [Deploying to Rivet Compute](reference/deploy/rivet-compute.md) +- [Deploying to Supabase Functions](reference/deploy/supabase.md) +- [Deploying to Vercel](reference/deploy/vercel.md) +- [Deploying to VMs & Bare Metal](reference/deploy/vm-and-bare-metal.md) + +### General + +- [Actor Configuration](reference/general/actor-configuration.md) +- [Architecture](reference/general/architecture.md) +- [Cross-Origin Resource Sharing](reference/general/cors.md) +- [Documentation for LLMs & AI](reference/general/docs-for-llms.md) +- [Edge Networking](reference/general/edge.md) +- [Endpoints](reference/general/endpoints.md) +- [Environment Variables](reference/general/environment-variables.md) +- [HTTP Server](reference/general/http-server.md) +- [Logging](reference/general/logging.md) +- [Pool Configuration](reference/general/pool-configuration.md) +- [Production Checklist](reference/general/production-checklist.md) +- [Registry Configuration](reference/general/registry-configuration.md) +- [Runtime Modes](reference/general/runtime-modes.md) +- [WASM vs Native SDK](reference/general/wasm-vs-native-sdk.md) + +### Self Hosting + +- [Configuration](reference/self-hosting/configuration.md) +- [Docker Compose](reference/self-hosting/docker-compose.md) +- [Docker Container](reference/self-hosting/docker-container.md) +- [File System](reference/self-hosting/filesystem.md) +- [FoundationDB (Enterprise)](reference/self-hosting/foundationdb.md) +- [Installing Rivet Engine](reference/self-hosting/install.md) +- [Kubernetes](reference/self-hosting/kubernetes.md) +- [Multi-Region](reference/self-hosting/multi-region.md) +- [PostgreSQL](reference/self-hosting/postgres.md) +- [Production Checklist](reference/self-hosting/production-checklist.md) +- [Railway Deployment](reference/self-hosting/railway.md) +- [Render Deployment](reference/self-hosting/render.md) +- [TLS & Certificates](reference/self-hosting/tls.md) + diff --git a/.agents/skills/ai-agent-workspace/SKILL.md b/.agents/skills/ai-agent-workspace/SKILL.md new file mode 100644 index 0000000..2119fc1 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/SKILL.md @@ -0,0 +1,343 @@ +--- +name: "ai-agent-workspace" +description: "Give every AI agent its own computer: a persistent workspace with a filesystem, processes, shells, networking, and agent sessions on a lightweight in-process OS." +--- + +# AI Agent Workspaces + +**IMPORTANT: Before doing anything, you MUST read `BASE_SKILL.md` in this skill's directory. It contains essential guidance on debugging, error handling, state management, deployment, and project setup. Those rules and patterns apply to all RivetKit work. Everything below assumes you have already read and understood it.** + +## Working Examples + +If you need a reference implementation, read the raw working example code in these templates: + +- [agent-os](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os) + + +Patterns for giving every AI agent its own computer with [agentOS](/docs/agent-os): one Rivet Actor per agent that owns a portable, lightweight in-process OS running on Wasm and V8. Use it for code interpreters that keep state between runs, agents that ship artifacts behind shareable preview URLs, per-user dev environments, and scheduled maintenance agents. agentOS is in preview and the API is subject to change. + +This entry is about giving an agent a workspace. For conversation memory, message queues, and streaming chat patterns, see [AI Agent](/cookbook/ai-agent/). + +## Starter Code + +The [agent-os](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os) collection is reference code, one sub-example per capability; treat it as patterns to copy into your project rather than a turnkey app. The [agent-os-e2e](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os-e2e) example is the complete end-to-end walkthrough. + +| Example | Starter Code | Use When | +| --- | --- | --- | +| Hello World | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/hello-world) | You want the minimal loop: boot a VM lazily on the first action, write a file, read it back. | +| Filesystem | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/filesystem) | The agent needs the full file surface: recursive listing, stat, move, delete, and custom mounts. | +| Git | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/git) | The agent works with real git repos inside the workspace: init, commit, branch, and clone via `exec`. | +| Processes | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/processes) | The agent runs shell commands with pipes and long-lived spawned programs. | +| Network | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/network) | The agent serves HTTP inside the VM and you need `vmFetch` or signed preview URLs. | +| Cron | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/cron) | The workspace runs scheduled commands or recurring agent work. | +| Tools | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/tools) | You want your backend functions exposed as CLI commands inside the workspace. | +| Agent Session | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/agent-session) | You drive a Pi coding agent session inside the workspace. Requires `ANTHROPIC_API_KEY`. | +| Sandbox Mounting | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/sandbox) | The agent needs native binaries or a real OS, mounted into the VM from a Docker-backed sandbox. Requires Docker. | +| End-to-End Walkthrough | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os-e2e) | You want one runnable script covering files, processes, preview URLs, and a streaming Pi agent session. | + +## Setup + +The whole backend is one registry with one `agentOs()` actor: + +```typescript +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +See the [Quickstart](/docs/agent-os/quickstart) for the client side and project layout. + +## Workspace Model + +- **One actor per workspace, key as identity.** `client.vm.getOrCreate(["my-agent"])` gives each agent its own workspace; key by user id for per-user dev environments. Each workspace has its own filesystem, processes, and networking with no shared state and no cross-contamination (see the [overview](/docs/agent-os)). +- **Software packages choose what is installed.** agentOS starts with no commands installed. The `software` option installs packages such as `@rivet-dev/agent-os-common` (a meta-package of Wasm command-line tools: coreutils, sed, grep, gawk, findutils, diffutils, tar, and gzip), `@rivet-dev/agent-os-git` (git), and `@rivet-dev/agent-os-pi` (the Pi coding agent). See [Software](/docs/agent-os/software). +- **The VM boots lazily and sleeps when idle.** The first action boots the VM (clients see a `vmBooted` event); when nothing is active, the actor sleeps and broadcasts `vmShutdown`, then wakes on the next action. + +What survives a sleep/wake cycle (see [Persistence](/docs/agent-os/persistence)): + +| Data | Across sleep/wake | +| --- | --- | +| Session transcripts and event history | Persist in actor SQLite as events stream. `listPersistedSessions` and `getSessionEvents` read them back without booting the VM, and `resumeSession` picks a session back up in a rebooted VM. | +| Signed preview URL tokens | Persist in actor SQLite. Requests are validated against the stored token and the VM reboots lazily to serve them, so preview URLs keep working after sleep. | +| Files | Persist when the mount is backed by a persistent driver (database-backed, S3, or a sandbox mount). In-memory mounts come back empty on wake. | +| Processes, shells, and cron jobs | Do not persist. Restart long-running processes and reschedule cron jobs on wake (recommended extension). | + +The actor holds itself awake while sessions, processes, shells, or hooks are active, then sleeps after a grace period. + +## Capability Tour + +| Area | Use It For | Key Actions | Docs | Example | +| --- | --- | --- | --- | --- | +| Filesystem | Give the agent a file tree to read and write | `readFile`, `writeFile`, `mkdir`, `readdir`, `move` | [Filesystem](/docs/agent-os/filesystem) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/filesystem) | +| Processes | Run commands and long-lived programs | `exec`, `spawn`, `waitProcess`, `killProcess` | [Processes](/docs/agent-os/processes) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/processes) | +| Shells | Interactive terminals with streamed output | `openShell`, `writeShell`, `resizeShell`, `closeShell` | [Processes](/docs/agent-os/processes) | No standalone example | +| Networking and preview URLs | Reach services inside the VM and share them externally | `vmFetch`, `createSignedPreviewUrl`, `expireSignedPreviewUrl` | [Networking](/docs/agent-os/networking) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/network) | +| Cron | Scheduled commands and recurring agent sessions | `scheduleCron`, `listCronJobs`, `cancelCronJob` | [Cron](/docs/agent-os/cron) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/cron) | +| Agent sessions | Drive a coding agent inside the workspace | `createSession`, `sendPrompt`, `resumeSession`, `closeSession` | [Sessions](/docs/agent-os/sessions) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/agent-session) | + +Two details worth knowing up front: + +- `createSignedPreviewUrl` returns a relative path plus the token and expiry. Build the full URL with the client handle's `getGatewayUrl()` method; it is a client method, not an actor action. +- Schedule cron jobs through the actor with the `exec` and `session` action types only. Callback cron actions are defined in server code and do not serialize through `listCronJobs`. + +## Driving a Coding Agent Session + +Only the Pi agent (`@rivet-dev/agent-os-pi`) is currently supported as a session agent; Amp, Claude Code, Codex, and OpenCode are coming soon. See [Sessions](/docs/agent-os/sessions). + +1. `createSession("pi", { env: { ANTHROPIC_API_KEY } })` returns a `sessionId`. The VM does not inherit the host `process.env`, so API keys are passed explicitly per session or kept server-side through the [LLM gateway](/docs/agent-os/llm-gateway). +2. Open a realtime connection and subscribe to `sessionEvent` to stream the agent's output, such as message chunks, as it works. +3. `sendPrompt(sessionId, ...)` starts a turn; `cancelPrompt` stops one in flight. +4. When the agent asks to use a tool, clients receive a `permissionRequest` event and answer with `respondPermission`, or the server auto-approves with the `onPermissionRequest` config hook (see [Permissions](/docs/agent-os/permissions)). +5. Transcripts are persisted automatically in the universal transcript format (Agent Communication Protocol, ACP). After sleep, `resumeSession` continues a session in the rebooted VM, and `listPersistedSessions` plus `getSessionEvents` read history without booting the VM at all. + +## Host Tools + +Expose your backend functions to the agent as CLI commands inside the workspace. Define a toolkit with `toolKit()` and `hostTool()` (Zod-schema'd JavaScript functions on the host), pass it via `agentOs({ options: { toolKits: [...] } })`, and it is installed as a command such as `agentos-weather forecast --city Paris --days 3` and injected into the agent's system prompt. The agent calls your backend with no HTTP endpoints or MCP servers to stand up, and CLI-shaped tools are code mode compatible for large token savings. See [Tools](/docs/agent-os/tools) and the [tools example](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/tools). + +## When to Mount a Full Sandbox + +agentOS is not a replacement for sandboxes; it is designed to work alongside them. When a workspace needs native binaries, browsers, compilation, or desktop automation, use sandbox mounting: start a Docker-backed sandbox with `SandboxAgent.start({ sandbox: docker() })`, project its filesystem into the VM as a native directory (for example `/sandbox`) with `createSandboxFs`, and expose sandbox process control as host tools with `createSandboxToolkit`. Filesystem actions like `writeFile` and `readFile` project transparently through the mount while heavy workloads run in the container. + +See [Sandbox Mounting](/docs/agent-os/sandbox) for the hybrid model and [agentOS vs Sandboxes](/docs/agent-os/versus-sandbox) for when each side wins: the lightweight VM has a near-zero cold start (~6 ms) and installs with `npm install`, while sandboxes are full Linux environments billed per second of uptime. + +## Architecture + +| Topic | Summary | +| --- | --- | +| Topology | One `vm[workspaceId]` actor per agent or per user; the actor key is the workspace identity. | +| Ingress | Actor actions for files, processes, networking, cron, and sessions; a realtime connection for streamed events. | +| Streaming | `sessionEvent` per agent event, `processOutput` and `processExit` for spawned processes, `shellData` for interactive shells. | +| Persistence | Session transcripts, event history, and preview tokens in actor SQLite; files persist through persistent mounts. | + +**Actors** + +- **Key**: `vm[workspaceId]`, for example `client.vm.getOrCreate(["my-agent"])` +- **Responsibility**: Owns one workspace. Boots the VM lazily on the first action, serves all capability actions, proxies signed preview URL requests into the VM's virtual network, and persists sessions and tokens to actor SQLite. +- **Actions** (grouped; the most load-bearing of each area) + - Filesystem: `readFile`, `writeFile`, `mkdir`, `readdir`, `readdirRecursive`, `stat`, `exists`, `move`, `deleteFile` + - Processes: `exec`, `spawn`, `writeProcessStdin`, `waitProcess`, `listProcesses`, `killProcess` + - Shells: `openShell`, `writeShell`, `resizeShell`, `closeShell` + - Network: `vmFetch`, `createSignedPreviewUrl`, `expireSignedPreviewUrl` + - Cron: `scheduleCron`, `listCronJobs`, `cancelCronJob` + - Sessions: `createSession`, `sendPrompt`, `cancelPrompt`, `respondPermission`, `resumeSession`, `closeSession`, `destroySession`, `listPersistedSessions`, `getSessionEvents` +- **Queues** + - None +- **Events** + - `vmBooted` + - `vmShutdown` + - `sessionEvent` + - `permissionRequest` + - `processOutput` + - `processExit` + - `shellData` + - `cronEvent` +- **State** + - SQLite + - `agent_os_sessions` and `agent_os_session_events` (session metadata plus seq-ordered transcript events) + - `agent_os_preview_tokens` (signed preview URL tokens with expiry) + - `agent_os_fs_entries` (file content for database-backed mounts) + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant A as vm actor + participant V as agentOS VM + participant P as Pi session + + C->>A: getOrCreate(["my-agent"]) + C->>A: writeFile("/tmp/hello.txt", ...) + Note over A,V: first action boots the VM + A-->>C: vmBooted + C->>A: exec("echo hello | tr a-z A-Z") + A->>V: run command + V-->>A: {exitCode: 0, stdout} + C->>A: spawn("node", ["/tmp/server.mjs"]) + C->>A: createSignedPreviewUrl(8080, 60) + A-->>C: {path, token, expiresAt} + C->>A: fetch(gatewayUrl + path) + Note over A: token checked in SQLite, request proxied into the VM network + C->>A: createSession("pi", {env}) + A->>P: start session + C->>A: sendPrompt(sessionId, ...) + loop streamed agent output + P-->>A: agent event + A-->>C: sessionEvent + end + Note over A: idle, sleeps after grace period (vmShutdown) + C->>A: resumeSession(sessionId) + Note over A,V: wake reboots the VM, restoring transcripts, preview tokens, and persistent mounts +``` + +## Security Checklist + +- **Authenticate connections**: Add the `onBeforeConnect` hook in the `agentOs()` config so only authorized callers reach a workspace. Signed preview URL requests deliberately skip it because the token is the credential; browsers navigating a preview URL cannot supply actor connection params. +- **Gate agent tool use with permissions**: Session permission requests broadcast as `permissionRequest` events for human-in-the-loop approval via `respondPermission`, or run a server-side `onPermissionRequest` policy for automated pipelines. See [Permissions](/docs/agent-os/permissions). +- **Treat preview URLs as bearer credentials**: Tokens are randomly generated 32-character values with a default expiry of 1 hour and a maximum of 24; revoke early with `expireSignedPreviewUrl`. Preview responses carry permissive CORS headers, so do not serve private data on a preview port without app-level auth. +- **Keep LLM credentials off the browser**: Create sessions from trusted server code with the key in `createSession` env, or keep keys entirely server-side with the [LLM gateway](/docs/agent-os/llm-gateway). Session keys are injected into the session environment inside the VM and are never stored in actor config or SQLite. +- **Treat mounted sandboxes as their own trust boundary**: A mounted sandbox is a full Linux environment outside the workspace's Wasm and V8 isolate. Scope what its network and filesystem can reach before projecting it into an agent's VM. +- **Set resource and cost limits**: Cap per-workspace memory and CPU (`maxMemoryMb`, `maxCpuPercent`, see [Security](/docs/agent-os/security)). Active sessions, processes, and shells hold the actor awake, so add per-workspace session caps and token budgets as a recommended extension. + +## Reference Map + +### Actors + +- [Access Control](reference/actors/access-control.md) +- [Actions](reference/actors/actions.md) +- [Actor Keys](reference/actors/keys.md) +- [Actor Scheduling](reference/actors/schedule.md) +- [Actor Statuses](reference/actors/statuses.md) +- [Authentication](reference/actors/authentication.md) +- [Cloudflare Workers Quickstart](reference/actors/quickstart/cloudflare.md) +- [Communicating Between Actors](reference/actors/communicating-between-actors.md) +- [Connections](reference/actors/connections.md) +- [Custom Inspector Tabs](reference/actors/inspector-tabs.md) +- [Debugging](reference/actors/debugging.md) +- [Design Patterns](reference/actors/design-patterns.md) +- [Destroying Actors](reference/actors/destroy.md) +- [Effect.ts Quickstart (Beta)](reference/actors/quickstart/effect.md) +- [Errors](reference/actors/errors.md) +- [Fetch and WebSocket Handler](reference/actors/fetch-and-websocket-handler.md) +- [Helper Types](reference/actors/helper-types.md) +- [Icons & Names](reference/actors/appearance.md) +- [In-Memory State](reference/actors/state.md) +- [Input Parameters](reference/actors/input.md) +- [Lifecycle](reference/actors/lifecycle.md) +- [Limits](reference/actors/limits.md) +- [Low-Level HTTP Request Handler](reference/actors/request-handler.md) +- [Low-Level KV Storage](reference/actors/kv.md) +- [Low-Level WebSocket Handler](reference/actors/websocket-handler.md) +- [Metadata](reference/actors/metadata.md) +- [Next.js Quickstart](reference/actors/quickstart/next-js.md) +- [Node.js & Bun Quickstart](reference/actors/quickstart/backend.md) +- [Queues & Run Loops](reference/actors/queues.md) +- [React Quickstart](reference/actors/quickstart/react.md) +- [Realtime](reference/actors/events.md) +- [Rust Quickstart (Beta)](reference/actors/quickstart/rust.md) +- [Scaling & Concurrency](reference/actors/scaling.md) +- [Sharing and Joining State](reference/actors/sharing-and-joining-state.md) +- [SQLite](reference/actors/sqlite.md) +- [SQLite + Drizzle](reference/actors/sqlite-drizzle.md) +- [Supabase Functions Quickstart](reference/actors/quickstart/supabase.md) +- [Testing](reference/actors/testing.md) +- [Troubleshooting](reference/actors/troubleshooting.md) +- [Types](reference/actors/types.md) +- [Vanilla HTTP API](reference/actors/http-api.md) +- [Versions & Upgrades](reference/actors/versions.md) +- [Workflows](reference/actors/workflows.md) + +### Agent Os + +- [Agent-to-Agent Communication](reference/agent-os/agent-to-agent.md) +- [agentOS vs Sandbox](reference/agent-os/versus-sandbox.md) +- [Authentication](reference/agent-os/authentication.md) +- [Benchmarks](reference/agent-os/benchmarks.md) +- [Configuration](reference/agent-os/configuration.md) +- [Core Package](reference/agent-os/core.md) +- [Crash Course](reference/agent-os/crash-course.md) +- [Cron Jobs](reference/agent-os/cron.md) +- [Deployment](reference/agent-os/deployment.md) +- [Embedded LLM Gateway](reference/agent-os/llm-gateway.md) +- [Events](reference/agent-os/events.md) +- [Filesystem](reference/agent-os/filesystem.md) +- [Limitations](reference/agent-os/limitations.md) +- [LLM Credentials](reference/agent-os/llm-credentials.md) +- [Multiplayer](reference/agent-os/multiplayer.md) +- [Networking & Previews](reference/agent-os/networking.md) +- [Permissions](reference/agent-os/permissions.md) +- [Persistence & Sleep](reference/agent-os/persistence.md) +- [Pi](reference/agent-os/agents/pi.md) +- [Processes & Shell](reference/agent-os/processes.md) +- [Queues](reference/agent-os/queues.md) +- [Quickstart](reference/agent-os/quickstart.md) +- [Sandbox Mounting](reference/agent-os/sandbox.md) +- [Security & Auth](reference/agent-os/security.md) +- [Security Model](reference/agent-os/security-model.md) +- [Sessions](reference/agent-os/sessions.md) +- [Software](reference/agent-os/software.md) +- [SQLite](reference/agent-os/sqlite.md) +- [System Prompt](reference/agent-os/system-prompt.md) +- [Tools](reference/agent-os/tools.md) +- [Webhooks](reference/agent-os/webhooks.md) +- [Workflow Automation](reference/agent-os/workflows.md) + +### Cli + +- [CLI](reference/cli.md) + +### Clients + +- [Node.js & Bun](reference/clients/javascript.md) +- [React](reference/clients/react.md) +- [Swift](reference/clients/swift.md) +- [SwiftUI](reference/clients/swiftui.md) + +### Cookbook + +- [AI Agent](reference/cookbook/ai-agent.md) +- [AI Agent Workspaces](reference/cookbook/ai-agent-workspace.md) +- [Chat Room](reference/cookbook/chat-room.md) +- [Collaborative Text Editor](reference/cookbook/collaborative-text-editor.md) +- [Cron Jobs and Scheduled Tasks](reference/cookbook/cron-jobs.md) +- [Database per Tenant](reference/cookbook/per-tenant-database.md) +- [Deploying Rivet in a VPC or Air-Gapped Network](reference/cookbook/vpc-air-gapped.md) +- [Live Cursors and Presence](reference/cookbook/live-cursors.md) +- [Multiplayer Game](reference/cookbook/multiplayer-game.md) + +### Deploy + +- [Deploy To Amazon Web Services Lambda](reference/deploy/aws-lambda.md) +- [Deploying to AWS ECS](reference/deploy/aws-ecs.md) +- [Deploying to Cloudflare Workers](reference/deploy/cloudflare.md) +- [Deploying to Freestyle](reference/deploy/freestyle.md) +- [Deploying to Google Cloud Run](reference/deploy/gcp-cloud-run.md) +- [Deploying to Hetzner](reference/deploy/hetzner.md) +- [Deploying to Kubernetes](reference/deploy/kubernetes.md) +- [Deploying to Railway](reference/deploy/railway.md) +- [Deploying to Rivet Compute](reference/deploy/rivet-compute.md) +- [Deploying to Supabase Functions](reference/deploy/supabase.md) +- [Deploying to Vercel](reference/deploy/vercel.md) +- [Deploying to VMs & Bare Metal](reference/deploy/vm-and-bare-metal.md) + +### General + +- [Actor Configuration](reference/general/actor-configuration.md) +- [Architecture](reference/general/architecture.md) +- [Cross-Origin Resource Sharing](reference/general/cors.md) +- [Documentation for LLMs & AI](reference/general/docs-for-llms.md) +- [Edge Networking](reference/general/edge.md) +- [Endpoints](reference/general/endpoints.md) +- [Environment Variables](reference/general/environment-variables.md) +- [HTTP Server](reference/general/http-server.md) +- [Logging](reference/general/logging.md) +- [Pool Configuration](reference/general/pool-configuration.md) +- [Production Checklist](reference/general/production-checklist.md) +- [Registry Configuration](reference/general/registry-configuration.md) +- [Runtime Modes](reference/general/runtime-modes.md) +- [WASM vs Native SDK](reference/general/wasm-vs-native-sdk.md) + +### Self Hosting + +- [Configuration](reference/self-hosting/configuration.md) +- [Docker Compose](reference/self-hosting/docker-compose.md) +- [Docker Container](reference/self-hosting/docker-container.md) +- [File System](reference/self-hosting/filesystem.md) +- [FoundationDB (Enterprise)](reference/self-hosting/foundationdb.md) +- [Installing Rivet Engine](reference/self-hosting/install.md) +- [Kubernetes](reference/self-hosting/kubernetes.md) +- [Multi-Region](reference/self-hosting/multi-region.md) +- [PostgreSQL](reference/self-hosting/postgres.md) +- [Production Checklist](reference/self-hosting/production-checklist.md) +- [Railway Deployment](reference/self-hosting/railway.md) +- [Render Deployment](reference/self-hosting/render.md) +- [TLS & Certificates](reference/self-hosting/tls.md) + diff --git a/.agents/skills/ai-agent-workspace/index.json b/.agents/skills/ai-agent-workspace/index.json new file mode 100644 index 0000000..b9a4231 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/index.json @@ -0,0 +1,904 @@ +{ + "name": "ai-agent-workspace", + "description": "Give every AI agent its own computer: a persistent workspace with a filesystem, processes, shells, networking, and agent sessions on a lightweight in-process OS.", + "skill_url": "/metadata/skills/ai-agent-workspace/SKILL.md", + "generated_at": "2026-06-15T20:24:02.496Z", + "references": [ + { + "name": "actors/access-control", + "title": "Access Control", + "description": "Authorize actions, queue publishes, and event subscriptions with explicit hooks.", + "canonical_url": "https://rivet.dev/docs/actors/access-control", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/access-control.md" + }, + { + "name": "actors/actions", + "title": "Actions", + "description": "Actions are how your backend, frontend, or other actors can communicate with actors.", + "canonical_url": "https://rivet.dev/docs/actors/actions", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/actions.md" + }, + { + "name": "general/actor-configuration", + "title": "Actor Configuration", + "description": "This page documents the configuration options available when defining a RivetKit actor. The actor configuration is passed to the `actor()` function.", + "canonical_url": "https://rivet.dev/docs/general/actor-configuration", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/general/actor-configuration.md" + }, + { + "name": "actors/keys", + "title": "Actor Keys", + "description": "Actor keys uniquely identify actor instances within each actor type. Keys are used for addressing which specific actor to communicate with.", + "canonical_url": "https://rivet.dev/docs/actors/keys", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/keys.md" + }, + { + "name": "actors/schedule", + "title": "Actor Scheduling", + "description": "Schedule actor actions in the future with persistent timers that survive restarts and upgrades.", + "canonical_url": "https://rivet.dev/docs/actors/schedule", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/schedule.md" + }, + { + "name": "actors/statuses", + "title": "Actor Statuses", + "description": "Understand the lifecycle statuses of Rivet Actors, what they mean, how they appear in the API, and how to troubleshoot common issues.", + "canonical_url": "https://rivet.dev/docs/actors/statuses", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/statuses.md" + }, + { + "name": "agent-os/agent-to-agent", + "title": "Agent-to-Agent Communication", + "description": "Use host tools to let agents communicate with each other.", + "canonical_url": "https://rivet.dev/docs/agent-os/agent-to-agent", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/agent-to-agent.md" + }, + { + "name": "agent-os/versus-sandbox", + "title": "agentOS vs Sandbox", + "description": "When to use the lightweight agentOS VM, a full sandbox, or both together.", + "canonical_url": "https://rivet.dev/docs/agent-os/versus-sandbox", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/versus-sandbox.md" + }, + { + "name": "cookbook/ai-agent", + "title": "AI Agent", + "description": "Build an AI agent backend with persistent memory: one Rivet Actor per conversation, queued message handling, and streaming LLM responses as realtime events.", + "canonical_url": "https://rivet.dev/cookbook/ai-agent", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/cookbook/ai-agent.md" + }, + { + "name": "cookbook/ai-agent-workspace", + "title": "AI Agent Workspaces", + "description": "Give every AI agent its own computer: a persistent workspace with a filesystem, processes, shells, networking, and agent sessions on a lightweight in-process OS.", + "canonical_url": "https://rivet.dev/cookbook/ai-agent-workspace", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/cookbook/ai-agent-workspace.md" + }, + { + "name": "general/architecture", + "title": "Architecture", + "description": "- rivetkit is the typescript library used for both local development & to connect your application to rivet - a rivetkit instance is called a \"runner.\" you can run multiple runners to scale rivetkit horiziotnally. read omre about runners below.", + "canonical_url": "https://rivet.dev/docs/general/architecture", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/general/architecture.md" + }, + { + "name": "actors/authentication", + "title": "Authentication", + "description": "Secure your actors with authentication and authorization.", + "canonical_url": "https://rivet.dev/docs/actors/authentication", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/authentication.md" + }, + { + "name": "agent-os/authentication", + "title": "Authentication", + "description": "Authenticate connections to agentOS actors using hooks.", + "canonical_url": "https://rivet.dev/docs/agent-os/authentication", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/authentication.md" + }, + { + "name": "agent-os/benchmarks", + "title": "Benchmarks", + "description": "Performance benchmarks comparing agentOS to traditional sandbox providers.", + "canonical_url": "https://rivet.dev/docs/agent-os/benchmarks", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/benchmarks.md" + }, + { + "name": "cookbook/chat-room", + "title": "Chat Room", + "description": "Build a realtime chat room backend with Rivet Actors: one actor per room, SQLite-backed message history, and WebSocket broadcast to every connected client.", + "canonical_url": "https://rivet.dev/cookbook/chat-room", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/cookbook/chat-room.md" + }, + { + "name": "cli", + "title": "CLI", + "description": "Reference for the optional rivet CLI: deploy to Rivet Compute and run local dev for serverless platforms.", + "canonical_url": "https://rivet.dev/docs/cli", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/cli.md" + }, + { + "name": "actors/quickstart/cloudflare", + "title": "Cloudflare Workers Quickstart", + "description": "Set up a Rivet project locally targeting Cloudflare Workers.", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/cloudflare", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/quickstart/cloudflare.md" + }, + { + "name": "cookbook/collaborative-text-editor", + "title": "Collaborative Text Editor", + "description": "Build a collaborative text editor backend with Yjs CRDTs and Rivet Actors: per-document actors relay sync and awareness updates and persist snapshots.", + "canonical_url": "https://rivet.dev/cookbook/collaborative-text-editor", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/cookbook/collaborative-text-editor.md" + }, + { + "name": "actors/communicating-between-actors", + "title": "Communicating Between Actors", + "description": "Learn how actors can call other actors and share data", + "canonical_url": "https://rivet.dev/docs/actors/communicating-between-actors", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/communicating-between-actors.md" + }, + { + "name": "agent-os/configuration", + "title": "Configuration", + "description": "Configure the agentOS VM options, preview settings, and lifecycle hooks.", + "canonical_url": "https://rivet.dev/docs/agent-os/configuration", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/configuration.md" + }, + { + "name": "self-hosting/configuration", + "title": "Configuration", + "description": "Rivet Engine can be configured through environment variables or configuration files.", + "canonical_url": "https://rivet.dev/docs/self-hosting/configuration", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/self-hosting/configuration.md" + }, + { + "name": "actors/connections", + "title": "Connections", + "description": "Connections represent client connections to your actor. They provide a way to handle client authentication, manage connection-specific data, and control the connection lifecycle.", + "canonical_url": "https://rivet.dev/docs/actors/connections", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/connections.md" + }, + { + "name": "agent-os/core", + "title": "Core Package", + "description": "Use @rivet-dev/agent-os-core standalone for direct VM control without the Rivet Actor runtime.", + "canonical_url": "https://rivet.dev/docs/agent-os/core", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/core.md" + }, + { + "name": "agent-os/crash-course", + "title": "Crash Course", + "description": "Run coding agents inside isolated VMs with full filesystem, process, and network control.", + "canonical_url": "https://rivet.dev/docs/agent-os/crash-course", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/crash-course.md" + }, + { + "name": "agent-os/cron", + "title": "Cron Jobs", + "description": "Schedule recurring commands and agent sessions in agentOS VMs.", + "canonical_url": "https://rivet.dev/docs/agent-os/cron", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/cron.md" + }, + { + "name": "cookbook/cron-jobs", + "title": "Cron Jobs and Scheduled Tasks", + "description": "Durable cron jobs with Rivet Actors: schedule.after and schedule.at timers survive restarts and crashes, plus re-arming recurring jobs and idempotent handlers.", + "canonical_url": "https://rivet.dev/cookbook/cron-jobs", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/cookbook/cron-jobs.md" + }, + { + "name": "general/cors", + "title": "Cross-Origin Resource Sharing", + "description": "Cross-Origin Resource Sharing (CORS) controls which origins (domains) can access your actors. When actors are exposed to the public internet, proper origin validation is critical to prevent security breaches and denial of service attacks.", + "canonical_url": "https://rivet.dev/docs/general/cors", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/general/cors.md" + }, + { + "name": "actors/inspector-tabs", + "title": "Custom Inspector Tabs", + "description": "Ship your own UI tabs alongside a Rivet Actor — embedded directly in the dashboard inspector.", + "canonical_url": "https://rivet.dev/docs/actors/inspector-tabs", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/inspector-tabs.md" + }, + { + "name": "cookbook/per-tenant-database", + "title": "Database per Tenant", + "description": "Multi-tenant data isolation with one Rivet Actor per tenant: the actor key is the tenant id, so each tenant gets its own isolated dataset and migrations.", + "canonical_url": "https://rivet.dev/cookbook/per-tenant-database", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/cookbook/per-tenant-database.md" + }, + { + "name": "actors/debugging", + "title": "Debugging", + "description": "Inspect and debug running Rivet Actors, runners, and provider configs using management, runner, and actor inspector HTTP APIs.", + "canonical_url": "https://rivet.dev/docs/actors/debugging", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/debugging.md" + }, + { + "name": "deploy/aws-lambda", + "title": "Deploy To Amazon Web Services Lambda", + "description": "_AWS Lambda is coming soon_", + "canonical_url": "https://rivet.dev/docs/deploy/aws-lambda", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/deploy/aws-lambda.md" + }, + { + "name": "cookbook/vpc-air-gapped", + "title": "Deploying Rivet in a VPC or Air-Gapped Network", + "description": "Run Rivet entirely inside your own perimeter: single-binary or Docker Compose install, file system storage with no database infrastructure, and no outbound telemetry by default.", + "canonical_url": "https://rivet.dev/cookbook/vpc-air-gapped", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/cookbook/vpc-air-gapped.md" + }, + { + "name": "deploy/aws-ecs", + "title": "Deploying to AWS ECS", + "description": "Run your backend on Amazon ECS with Fargate.", + "canonical_url": "https://rivet.dev/docs/deploy/aws-ecs", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/deploy/aws-ecs.md" + }, + { + "name": "deploy/cloudflare", + "title": "Deploying to Cloudflare Workers", + "description": "Deploy an existing Rivet project to Cloudflare Workers.", + "canonical_url": "https://rivet.dev/docs/deploy/cloudflare", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/deploy/cloudflare.md" + }, + { + "name": "deploy/freestyle", + "title": "Deploying to Freestyle", + "description": "Deploy RivetKit app to Freestyle.sh, a cloud platform for running AI-generated code with built-in security and scalability.", + "canonical_url": "https://rivet.dev/docs/deploy/freestyle", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/deploy/freestyle.md" + }, + { + "name": "deploy/gcp-cloud-run", + "title": "Deploying to Google Cloud Run", + "description": "Deploy your RivetKit app to Google Cloud Run.", + "canonical_url": "https://rivet.dev/docs/deploy/gcp-cloud-run", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/deploy/gcp-cloud-run.md" + }, + { + "name": "deploy/hetzner", + "title": "Deploying to Hetzner", + "description": "Please see the VM & Bare Metal guide.", + "canonical_url": "https://rivet.dev/docs/deploy/hetzner", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/deploy/hetzner.md" + }, + { + "name": "deploy/kubernetes", + "title": "Deploying to Kubernetes", + "description": "Deploy your RivetKit app to any Kubernetes cluster.", + "canonical_url": "https://rivet.dev/docs/deploy/kubernetes", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/deploy/kubernetes.md" + }, + { + "name": "deploy/railway", + "title": "Deploying to Railway", + "description": "Deploy your RivetKit app to Railway.", + "canonical_url": "https://rivet.dev/docs/deploy/railway", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/deploy/railway.md" + }, + { + "name": "deploy/rivet-compute", + "title": "Deploying to Rivet Compute", + "description": "Run your backend on Rivet Compute.", + "canonical_url": "https://rivet.dev/docs/deploy/rivet-compute", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/deploy/rivet-compute.md" + }, + { + "name": "deploy/supabase", + "title": "Deploying to Supabase Functions", + "description": "Deploy an existing Rivet project to Supabase Edge Functions.", + "canonical_url": "https://rivet.dev/docs/deploy/supabase", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/deploy/supabase.md" + }, + { + "name": "deploy/vercel", + "title": "Deploying to Vercel", + "description": "Deploy your Next.js Rivet app to Vercel.", + "canonical_url": "https://rivet.dev/docs/deploy/vercel", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/deploy/vercel.md" + }, + { + "name": "deploy/vm-and-bare-metal", + "title": "Deploying to VMs & Bare Metal", + "description": "Deploy your RivetKit app to any Linux VM or bare metal host.", + "canonical_url": "https://rivet.dev/docs/deploy/vm-and-bare-metal", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/deploy/vm-and-bare-metal.md" + }, + { + "name": "agent-os/deployment", + "title": "Deployment", + "description": "Choose the right deployment option for agentOS.", + "canonical_url": "https://rivet.dev/docs/agent-os/deployment", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/deployment.md" + }, + { + "name": "actors/design-patterns", + "title": "Design Patterns", + "description": "Common patterns and anti-patterns for building scalable actor systems.", + "canonical_url": "https://rivet.dev/docs/actors/design-patterns", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/design-patterns.md" + }, + { + "name": "actors/destroy", + "title": "Destroying Actors", + "description": "Actors can be permanently destroyed. Common use cases include:", + "canonical_url": "https://rivet.dev/docs/actors/destroy", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/destroy.md" + }, + { + "name": "self-hosting/docker-compose", + "title": "Docker Compose", + "description": "Deploy Rivet Engine with docker-compose for multi-container setups.", + "canonical_url": "https://rivet.dev/docs/self-hosting/docker-compose", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/self-hosting/docker-compose.md" + }, + { + "name": "self-hosting/docker-container", + "title": "Docker Container", + "description": "Run Rivet Engine in a single Docker container.", + "canonical_url": "https://rivet.dev/docs/self-hosting/docker-container", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/self-hosting/docker-container.md" + }, + { + "name": "general/docs-for-llms", + "title": "Documentation for LLMs & AI", + "description": "Rivet provides optimized documentation formats specifically designed for Large Language Models (LLMs) and AI integration tools.", + "canonical_url": "https://rivet.dev/docs/general/docs-for-llms", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/general/docs-for-llms.md" + }, + { + "name": "general/edge", + "title": "Edge Networking", + "description": "Actors automatically run near your users on your provider's global network.", + "canonical_url": "https://rivet.dev/docs/general/edge", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/general/edge.md" + }, + { + "name": "actors/quickstart/effect", + "title": "Effect.ts Quickstart (Beta)", + "description": "Build a Rivet Actor with the Effect SDK", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/effect", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/quickstart/effect.md" + }, + { + "name": "agent-os/llm-gateway", + "title": "Embedded LLM Gateway", + "description": "Route, meter, and manage LLM API calls from agents.", + "canonical_url": "https://rivet.dev/docs/agent-os/llm-gateway", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/llm-gateway.md" + }, + { + "name": "general/endpoints", + "title": "Endpoints", + "description": "Configure how your backend connects to Rivet and how clients reach your actors.", + "canonical_url": "https://rivet.dev/docs/general/endpoints", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/general/endpoints.md" + }, + { + "name": "general/environment-variables", + "title": "Environment Variables", + "description": "This page documents all environment variables that configure RivetKit behavior.", + "canonical_url": "https://rivet.dev/docs/general/environment-variables", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/general/environment-variables.md" + }, + { + "name": "actors/errors", + "title": "Errors", + "description": "Rivet provides robust error handling with security built in by default. Errors are handled differently based on whether they should be exposed to clients or kept private.", + "canonical_url": "https://rivet.dev/docs/actors/errors", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/errors.md" + }, + { + "name": "agent-os/events", + "title": "Events", + "description": "Full event catalog with payload shapes for agentOS.", + "canonical_url": "https://rivet.dev/docs/agent-os/events", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/events.md" + }, + { + "name": "actors/fetch-and-websocket-handler", + "title": "Fetch and WebSocket Handler", + "description": "These docs have moved to [Low-Level WebSocket Handler](/docs/actors/websocket-handler) and [Low-Level Request Handler](/docs/actors/request-handler).", + "canonical_url": "https://rivet.dev/docs/actors/fetch-and-websocket-handler", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/fetch-and-websocket-handler.md" + }, + { + "name": "self-hosting/filesystem", + "title": "File System", + "description": "The file system backend stores all data on the local disk. This is suitable for single-node deployments, development, and testing.", + "canonical_url": "https://rivet.dev/docs/self-hosting/filesystem", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/self-hosting/filesystem.md" + }, + { + "name": "agent-os/filesystem", + "title": "Filesystem", + "description": "Read, write, mount, and manage files inside agentOS.", + "canonical_url": "https://rivet.dev/docs/agent-os/filesystem", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/filesystem.md" + }, + { + "name": "self-hosting/foundationdb", + "title": "FoundationDB (Enterprise)", + "description": "FoundationDB is the recommended storage backend for scalable production Rivet deployments.", + "canonical_url": "https://rivet.dev/docs/self-hosting/foundationdb", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/self-hosting/foundationdb.md" + }, + { + "name": "actors/helper-types", + "title": "Helper Types", + "description": "This page has moved to [Types](/docs/actors/types).", + "canonical_url": "https://rivet.dev/docs/actors/helper-types", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/helper-types.md" + }, + { + "name": "general/http-server", + "title": "HTTP Server", + "description": "Different ways to run your RivetKit HTTP server.", + "canonical_url": "https://rivet.dev/docs/general/http-server", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/general/http-server.md" + }, + { + "name": "actors/appearance", + "title": "Icons & Names", + "description": "Customize actors with display names and icons for the Rivet inspector and dashboard.", + "canonical_url": "https://rivet.dev/docs/actors/appearance", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/appearance.md" + }, + { + "name": "actors/state", + "title": "In-Memory State", + "description": "Actors store state in memory for instant reads and writes. State can be persisted automatically or kept ephemeral.", + "canonical_url": "https://rivet.dev/docs/actors/state", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/state.md" + }, + { + "name": "actors/input", + "title": "Input Parameters", + "description": "Pass initialization data to actors when creating instances", + "canonical_url": "https://rivet.dev/docs/actors/input", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/input.md" + }, + { + "name": "self-hosting/install", + "title": "Installing Rivet Engine", + "description": "Install Rivet Engine using Docker, binaries, or a source build.", + "canonical_url": "https://rivet.dev/docs/self-hosting/install", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/self-hosting/install.md" + }, + { + "name": "self-hosting/kubernetes", + "title": "Kubernetes", + "description": "Deploy production-ready Rivet Engine to Kubernetes with PostgreSQL storage.", + "canonical_url": "https://rivet.dev/docs/self-hosting/kubernetes", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/self-hosting/kubernetes.md" + }, + { + "name": "actors/lifecycle", + "title": "Lifecycle", + "description": "Learn about actor lifecycle hooks for initialization, state management, and cleanup.", + "canonical_url": "https://rivet.dev/docs/actors/lifecycle", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/lifecycle.md" + }, + { + "name": "agent-os/limitations", + "title": "Limitations", + "description": "What the agentOS VM does not support, and how to work around it.", + "canonical_url": "https://rivet.dev/docs/agent-os/limitations", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/limitations.md" + }, + { + "name": "actors/limits", + "title": "Limits", + "description": "Limits and constraints for Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/actors/limits", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/limits.md" + }, + { + "name": "cookbook/live-cursors", + "title": "Live Cursors and Presence", + "description": "Live cursors and multiplayer presence with Rivet Actors: per-connection cursor state, realtime updates over events or raw WebSockets, and throttling.", + "canonical_url": "https://rivet.dev/cookbook/live-cursors", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/cookbook/live-cursors.md" + }, + { + "name": "agent-os/llm-credentials", + "title": "LLM Credentials", + "description": "Pass LLM API keys to agent sessions securely.", + "canonical_url": "https://rivet.dev/docs/agent-os/llm-credentials", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/llm-credentials.md" + }, + { + "name": "general/logging", + "title": "Logging", + "description": "Actors provide a built-in way to log complex data to the console.", + "canonical_url": "https://rivet.dev/docs/general/logging", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/general/logging.md" + }, + { + "name": "actors/request-handler", + "title": "Low-Level HTTP Request Handler", + "description": "Actors can handle HTTP requests through the `onRequest` handler.", + "canonical_url": "https://rivet.dev/docs/actors/request-handler", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/request-handler.md" + }, + { + "name": "actors/kv", + "title": "Low-Level KV Storage", + "description": "Use the built-in key-value store on ActorContext for durable string and binary data alongside actor state.", + "canonical_url": "https://rivet.dev/docs/actors/kv", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/kv.md" + }, + { + "name": "actors/websocket-handler", + "title": "Low-Level WebSocket Handler", + "description": "Actors can handle WebSocket connections through the `onWebSocket` handler.", + "canonical_url": "https://rivet.dev/docs/actors/websocket-handler", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/websocket-handler.md" + }, + { + "name": "actors/metadata", + "title": "Metadata", + "description": "Metadata provides information about the currently running actor.", + "canonical_url": "https://rivet.dev/docs/actors/metadata", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/metadata.md" + }, + { + "name": "self-hosting/multi-region", + "title": "Multi-Region", + "description": "Rivet Engine supports scaling transparently across multiple regions.", + "canonical_url": "https://rivet.dev/docs/self-hosting/multi-region", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/self-hosting/multi-region.md" + }, + { + "name": "agent-os/multiplayer", + "title": "Multiplayer", + "description": "Connect multiple clients to the same agentOS actor for collaborative agent workflows.", + "canonical_url": "https://rivet.dev/docs/agent-os/multiplayer", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/multiplayer.md" + }, + { + "name": "cookbook/multiplayer-game", + "title": "Multiplayer Game", + "description": "Pragmatic patterns for building multiplayer games: matchmaking, tick loops, realtime state, interest management, and validation.", + "canonical_url": "https://rivet.dev/cookbook/multiplayer-game", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/cookbook/multiplayer-game.md" + }, + { + "name": "agent-os/networking", + "title": "Networking & Previews", + "description": "Proxy HTTP requests into agentOS VMs and create shareable preview URLs.", + "canonical_url": "https://rivet.dev/docs/agent-os/networking", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/networking.md" + }, + { + "name": "actors/quickstart/next-js", + "title": "Next.js Quickstart", + "description": "Get started with Rivet Actors in Next.js", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/next-js", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/quickstart/next-js.md" + }, + { + "name": "clients/javascript", + "title": "Node.js & Bun", + "description": "Connect JavaScript apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/javascript", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/clients/javascript.md" + }, + { + "name": "actors/quickstart/backend", + "title": "Node.js & Bun Quickstart", + "description": "Get started with Rivet Actors in Node.js and Bun", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/backend", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/quickstart/backend.md" + }, + { + "name": "agent-os/permissions", + "title": "Permissions", + "description": "Approve or deny agent tool use with human-in-the-loop or auto-approve patterns.", + "canonical_url": "https://rivet.dev/docs/agent-os/permissions", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/permissions.md" + }, + { + "name": "agent-os/persistence", + "title": "Persistence & Sleep", + "description": "How agentOS persists data and manages sleep/wake cycles.", + "canonical_url": "https://rivet.dev/docs/agent-os/persistence", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/persistence.md" + }, + { + "name": "agent-os/agents/pi", + "title": "Pi", + "description": "Run the Pi coding agent inside a VM with extensions and custom configuration.", + "canonical_url": "https://rivet.dev/docs/agent-os/agents/pi", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/agents/pi.md" + }, + { + "name": "general/pool-configuration", + "title": "Pool Configuration", + "description": "Reference for runner pool configuration, including drain behavior, actor eviction rate limiting, and serverless-specific options.", + "canonical_url": "https://rivet.dev/docs/general/pool-configuration", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/general/pool-configuration.md" + }, + { + "name": "self-hosting/postgres", + "title": "PostgreSQL", + "description": "Configure PostgreSQL for self-hosted Rivet deployments.", + "canonical_url": "https://rivet.dev/docs/self-hosting/postgres", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/self-hosting/postgres.md" + }, + { + "name": "agent-os/processes", + "title": "Processes & Shell", + "description": "Execute commands, spawn long-running processes, and open interactive shells in agentOS VMs.", + "canonical_url": "https://rivet.dev/docs/agent-os/processes", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/processes.md" + }, + { + "name": "general/production-checklist", + "title": "Production Checklist", + "description": "Checklist for deploying Rivet Actors to production.", + "canonical_url": "https://rivet.dev/docs/general/production-checklist", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/general/production-checklist.md" + }, + { + "name": "self-hosting/production-checklist", + "title": "Production Checklist", + "description": "Checklist for deploying a self-hosted Rivet Engine to production.", + "canonical_url": "https://rivet.dev/docs/self-hosting/production-checklist", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/self-hosting/production-checklist.md" + }, + { + "name": "agent-os/queues", + "title": "Queues", + "description": "Serialize agent work with durable queues for backpressure and rate limiting.", + "canonical_url": "https://rivet.dev/docs/agent-os/queues", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/queues.md" + }, + { + "name": "actors/queues", + "title": "Queues & Run Loops", + "description": "Use actor-local durable queues for serial run loops and request/response workflows.", + "canonical_url": "https://rivet.dev/docs/actors/queues", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/queues.md" + }, + { + "name": "agent-os/quickstart", + "title": "Quickstart", + "description": "Set up an agentOS actor, create a session, and run your first coding agent.", + "canonical_url": "https://rivet.dev/docs/agent-os/quickstart", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/quickstart.md" + }, + { + "name": "self-hosting/railway", + "title": "Railway Deployment", + "description": "Railway provides a simple platform for deploying Rivet Engine with automatic scaling and managed infrastructure.", + "canonical_url": "https://rivet.dev/docs/self-hosting/railway", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/self-hosting/railway.md" + }, + { + "name": "clients/react", + "title": "React", + "description": "Connect React apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/react", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/clients/react.md" + }, + { + "name": "actors/quickstart/react", + "title": "React Quickstart", + "description": "Build realtime React applications with Rivet Actors", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/react", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/quickstart/react.md" + }, + { + "name": "actors/events", + "title": "Realtime", + "description": "Events enable realtime communication from actors to clients. While clients use actions to send data to actors, events allow actors to push updates to connected clients instantly.", + "canonical_url": "https://rivet.dev/docs/actors/events", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/events.md" + }, + { + "name": "general/registry-configuration", + "title": "Registry Configuration", + "description": "This page documents the configuration options available when setting up a RivetKit registry. The registry configuration is passed to the `setup()` function.", + "canonical_url": "https://rivet.dev/docs/general/registry-configuration", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/general/registry-configuration.md" + }, + { + "name": "self-hosting/render", + "title": "Render Deployment", + "description": "Deploy Rivet Engine to Render with managed PostgreSQL and automatic HTTPS, using the experimental PostgreSQL backend.", + "canonical_url": "https://rivet.dev/docs/self-hosting/render", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/self-hosting/render.md" + }, + { + "name": "general/runtime-modes", + "title": "Runtime Modes", + "description": "RivetKit supports two runtime modes for running your actors:", + "canonical_url": "https://rivet.dev/docs/general/runtime-modes", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/general/runtime-modes.md" + }, + { + "name": "actors/quickstart/rust", + "title": "Rust Quickstart (Beta)", + "description": "Build a Rivet Actor in Rust", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/rust", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/quickstart/rust.md" + }, + { + "name": "agent-os/sandbox", + "title": "Sandbox Mounting", + "description": "Extend agentOS with full sandboxes for heavy workloads like browsers, desktop automation, and compilation.", + "canonical_url": "https://rivet.dev/docs/agent-os/sandbox", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/sandbox.md" + }, + { + "name": "actors/scaling", + "title": "Scaling & Concurrency", + "description": "This page has moved to [design patterns](/docs/actors/design-patterns).", + "canonical_url": "https://rivet.dev/docs/actors/scaling", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/scaling.md" + }, + { + "name": "agent-os/security", + "title": "Security & Auth", + "description": "Configure resource limits, network control, authentication, and filesystem isolation for agentOS.", + "canonical_url": "https://rivet.dev/docs/agent-os/security", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/security.md" + }, + { + "name": "agent-os/security-model", + "title": "Security Model", + "description": "Trust boundaries, isolation guarantees, and the agentOS threat model.", + "canonical_url": "https://rivet.dev/docs/agent-os/security-model", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/security-model.md" + }, + { + "name": "agent-os/sessions", + "title": "Sessions", + "description": "Create agent sessions, send prompts, stream responses, and replay event history.", + "canonical_url": "https://rivet.dev/docs/agent-os/sessions", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/sessions.md" + }, + { + "name": "actors/sharing-and-joining-state", + "title": "Sharing and Joining State", + "description": "This page has moved to [design patterns](/docs/actors/design-patterns).", + "canonical_url": "https://rivet.dev/docs/actors/sharing-and-joining-state", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/sharing-and-joining-state.md" + }, + { + "name": "agent-os/software", + "title": "Software", + "description": "Install software packages and configure the commands available inside agentOS.", + "canonical_url": "https://rivet.dev/docs/agent-os/software", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/software.md" + }, + { + "name": "actors/sqlite", + "title": "SQLite", + "description": "Use embedded SQLite in Rivet Actors with raw SQL queries.", + "canonical_url": "https://rivet.dev/docs/actors/sqlite", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/sqlite.md" + }, + { + "name": "agent-os/sqlite", + "title": "SQLite", + "description": "Give agents access to a persistent SQLite database via host tools.", + "canonical_url": "https://rivet.dev/docs/agent-os/sqlite", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/sqlite.md" + }, + { + "name": "actors/sqlite-drizzle", + "title": "SQLite + Drizzle", + "description": "Use Drizzle ORM with embedded SQLite in Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/actors/sqlite-drizzle", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/sqlite-drizzle.md" + }, + { + "name": "actors/quickstart/supabase", + "title": "Supabase Functions Quickstart", + "description": "Set up a Rivet project locally targeting Supabase Edge Functions.", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/supabase", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/quickstart/supabase.md" + }, + { + "name": "clients/swift", + "title": "Swift", + "description": "Connect Swift apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/swift", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/clients/swift.md" + }, + { + "name": "clients/swiftui", + "title": "SwiftUI", + "description": "Build SwiftUI apps with Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/swiftui", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/clients/swiftui.md" + }, + { + "name": "agent-os/system-prompt", + "title": "System Prompt", + "description": "How agentOS injects context into agent sessions.", + "canonical_url": "https://rivet.dev/docs/agent-os/system-prompt", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/system-prompt.md" + }, + { + "name": "actors/testing", + "title": "Testing", + "description": "Rivet provides a straightforward testing framework to build reliable and maintainable applications. This guide covers how to write effective tests for your actor-based services.", + "canonical_url": "https://rivet.dev/docs/actors/testing", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/testing.md" + }, + { + "name": "self-hosting/tls", + "title": "TLS & Certificates", + "description": "How Rivet validates TLS root certificates.", + "canonical_url": "https://rivet.dev/docs/self-hosting/tls", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/self-hosting/tls.md" + }, + { + "name": "agent-os/tools", + "title": "Tools", + "description": "Expose custom tools to agents as CLI commands inside the VM.", + "canonical_url": "https://rivet.dev/docs/agent-os/tools", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/tools.md" + }, + { + "name": "actors/troubleshooting", + "title": "Troubleshooting", + "description": "Common issues with Rivet Actors and how to resolve them.", + "canonical_url": "https://rivet.dev/docs/actors/troubleshooting", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/troubleshooting.md" + }, + { + "name": "actors/types", + "title": "Types", + "description": "TypeScript types for working with Rivet Actors. This page covers context types used in lifecycle hooks and actions, as well as helper types for extracting types from actor definitions.", + "canonical_url": "https://rivet.dev/docs/actors/types", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/types.md" + }, + { + "name": "actors/http-api", + "title": "Vanilla HTTP API", + "description": "Use the low-level HTTP handler to send and receive requests from actors.", + "canonical_url": "https://rivet.dev/docs/actors/http-api", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/http-api.md" + }, + { + "name": "actors/versions", + "title": "Versions & Upgrades", + "description": "When you deploy new code, Rivet ensures actors are upgraded seamlessly without downtime.", + "canonical_url": "https://rivet.dev/docs/actors/versions", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/versions.md" + }, + { + "name": "general/wasm-vs-native-sdk", + "title": "WASM vs Native SDK", + "description": "RivetKit runs your actors on a native or a WebAssembly runtime depending on your platform.", + "canonical_url": "https://rivet.dev/docs/general/wasm-vs-native-sdk", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/general/wasm-vs-native-sdk.md" + }, + { + "name": "agent-os/webhooks", + "title": "Webhooks", + "description": "Trigger agent workflows from external webhooks using Hono and queues.", + "canonical_url": "https://rivet.dev/docs/agent-os/webhooks", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/webhooks.md" + }, + { + "name": "agent-os/workflows", + "title": "Workflow Automation", + "description": "Orchestrate multi-step agent tasks with durable workflows.", + "canonical_url": "https://rivet.dev/docs/agent-os/workflows", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/agent-os/workflows.md" + }, + { + "name": "actors/workflows", + "title": "Workflows", + "description": "Build durable, replayable run loops in Rivet Actors with steps, queue waits, timers, and rollback.", + "canonical_url": "https://rivet.dev/docs/actors/workflows", + "reference_url": "/metadata/skills/ai-agent-workspace/reference/actors/workflows.md" + } + ] +} \ No newline at end of file diff --git a/.agents/skills/ai-agent-workspace/openapi.json b/.agents/skills/ai-agent-workspace/openapi.json new file mode 100644 index 0000000..ca482f7 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/openapi.json @@ -0,0 +1,1311 @@ +{ + "openapi": "3.0.0", + "info": { + "version": "2.2.0", + "title": "RivetKit API" + }, + "components": { + "schemas": {}, + "parameters": {} + }, + "paths": { + "/actors": { + "get": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": false, + "name": "name", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "actor_ids", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "key", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "actors": { + "type": "array", + "items": { + "type": "object", + "properties": { + "actor_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "namespace_id": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "create_ts": { + "type": "number" + }, + "connectable_ts": { + "type": "number", + "nullable": true + }, + "destroy_ts": { + "type": "number", + "nullable": true + }, + "sleep_ts": { + "type": "number", + "nullable": true + }, + "start_ts": { + "type": "number", + "nullable": true + }, + "error": { + "nullable": true + } + }, + "required": [ + "actor_id", + "name", + "key", + "namespace_id", + "runner_name_selector", + "create_ts" + ] + } + } + }, + "required": [ + "actors" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + }, + "put": { + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "datacenter": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "crash_policy": { + "type": "string" + }, + "input": { + "type": "string", + "nullable": true + } + }, + "required": [ + "name", + "key", + "runner_name_selector", + "crash_policy" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "actor": { + "type": "object", + "properties": { + "actor_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "namespace_id": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "create_ts": { + "type": "number" + }, + "connectable_ts": { + "type": "number", + "nullable": true + }, + "destroy_ts": { + "type": "number", + "nullable": true + }, + "sleep_ts": { + "type": "number", + "nullable": true + }, + "start_ts": { + "type": "number", + "nullable": true + }, + "error": { + "nullable": true + } + }, + "required": [ + "actor_id", + "name", + "key", + "namespace_id", + "runner_name_selector", + "create_ts" + ] + }, + "created": { + "type": "boolean" + } + }, + "required": [ + "actor", + "created" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + }, + "post": { + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "datacenter": { + "type": "string" + }, + "name": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "crash_policy": { + "type": "string" + }, + "key": { + "type": "string", + "nullable": true + }, + "input": { + "type": "string", + "nullable": true + } + }, + "required": [ + "name", + "runner_name_selector", + "crash_policy" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "actor": { + "type": "object", + "properties": { + "actor_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "namespace_id": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "create_ts": { + "type": "number" + }, + "connectable_ts": { + "type": "number", + "nullable": true + }, + "destroy_ts": { + "type": "number", + "nullable": true + }, + "sleep_ts": { + "type": "number", + "nullable": true + }, + "start_ts": { + "type": "number", + "nullable": true + }, + "error": { + "nullable": true + } + }, + "required": [ + "actor_id", + "name", + "key", + "namespace_id", + "runner_name_selector", + "create_ts" + ] + } + }, + "required": [ + "actor" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/actors/names": { + "get": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "namespace", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "names": { + "type": "object", + "additionalProperties": { + "type": "object", + "properties": { + "metadata": { + "type": "object", + "additionalProperties": { + "nullable": true + } + } + }, + "required": [ + "metadata" + ] + } + } + }, + "required": [ + "names" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/actors/{actor_id}/kv/keys/{key}": { + "get": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "actor_id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "key", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "value": { + "type": "string", + "nullable": true + } + }, + "required": [ + "value" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/gateway/{actorId}/health": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + } + ], + "responses": { + "200": { + "description": "Health check", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + } + } + } + }, + "/gateway/{actorId}/action/{action}": { + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "action", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The name of the action to execute" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "args": {} + }, + "required": [ + "args" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Action executed successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "output": {} + }, + "required": [ + "output" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Invalid action" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/gateway/{actorId}/request/{path}": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "put": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "delete": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "patch": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "head": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "options": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + } + }, + "/gateway/{actorId}/inspector/state": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Current actor state", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": {} + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + }, + "patch": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": {} + }, + "required": [ + "state" + ] + } + } + } + }, + "responses": { + "200": { + "description": "State updated", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "ok": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/connections": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Current actor connections", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "connections": { + "type": "array", + "items": { + "type": "object" + } + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/rpcs": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Available actor actions/RPCs", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "rpcs": { + "type": "object" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/action/{name}": { + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The name of the action to execute" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "args": { + "type": "array", + "items": {} + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Action executed successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "output": {} + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/queue": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 50 + }, + "description": "Maximum number of queue messages to return" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Queue status", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "size": { + "type": "integer" + }, + "maxSize": { + "type": "integer" + }, + "truncated": { + "type": "boolean" + }, + "messages": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "createdAtMs": { + "type": "integer" + } + } + } + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/traces": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "startMs", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 0 + }, + "description": "Start of time range in epoch milliseconds" + }, + { + "name": "endMs", + "in": "query", + "required": false, + "schema": { + "type": "integer" + }, + "description": "End of time range in epoch milliseconds. Defaults to now." + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 1000 + }, + "description": "Maximum number of spans to return" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Trace spans in OTLP JSON format", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "otlp": { + "type": "object" + }, + "clamped": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/workflow-history": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Workflow history and status", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "history": {}, + "isWorkflowEnabled": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/workflow/replay": { + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "entryId": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Workflow history after scheduling a replay", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "history": {}, + "isWorkflowEnabled": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/summary": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Full actor inspector summary", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": {}, + "connections": { + "type": "array", + "items": { + "type": "object" + } + }, + "rpcs": { + "type": "object" + }, + "queueSize": { + "type": "integer" + }, + "isStateEnabled": { + "type": "boolean" + }, + "isDatabaseEnabled": { + "type": "boolean" + }, + "isWorkflowEnabled": { + "type": "boolean" + }, + "workflowHistory": {} + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + } + } +} \ No newline at end of file diff --git a/.agents/skills/ai-agent-workspace/reference/actors/access-control.md b/.agents/skills/ai-agent-workspace/reference/actors/access-control.md new file mode 100644 index 0000000..b39bfda --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/access-control.md @@ -0,0 +1,134 @@ +# Access Control + +> Source: `src/content/docs/actors/access-control.mdx` +> Canonical URL: https://rivet.dev/docs/actors/access-control +> Description: Authorize actions, queue publishes, and event subscriptions with explicit hooks. + +--- +Use access control to decide what authenticated clients are allowed to do. + +This is authorization, not authentication: + +- Use [authentication](/docs/actors/authentication) to identify who is calling. +- Use access-control rules to decide what they can do after connecting. + +## Permission Surfaces + +RivetKit authorization is explicit per surface: + +- `onBeforeConnect` rejects unauthenticated or malformed connections. +- Action handlers (`actions.*`) enforce action permissions. +- `queues..canPublish` allows or denies inbound queue publishes. +- `events..canSubscribe` allows or denies event subscriptions. + +## Fail By Default + +Use deny-by-default rules everywhere: + +1. Keep `onBeforeConnect` strict and reject invalid credentials. +2. In each action, explicitly allow expected roles and throw `forbidden` otherwise. +3. In `canPublish` and `canSubscribe`, return `true` only for allowed roles and end with `return false`. + +```ts +import { actor, event, queue, UserError } from "rivetkit"; + +type ConnParams = { + authToken: string; +}; + +type ConnState = { + userId: string; + role: "member" | "admin"; +}; + +async function authenticate( + authToken: string, +): Promise { + if (authToken === "admin-token") { + return { userId: "admin-1", role: "admin" }; + } + if (authToken === "member-token") { + return { userId: "member-1", role: "member" }; + } + return null; +} + +export const chatRoom = actor({ + state: { messages: [] as Array<{ userId: string; text: string }> }, + + onBeforeConnect: async (_c, params: ConnParams) => { + if (!params.authToken) { + throw new UserError("Forbidden", { code: "forbidden" }); + } + + const session = await authenticate(params.authToken); + if (!session) { + throw new UserError("Forbidden", { code: "forbidden" }); + } + }, + + createConnState: async (_c, params: ConnParams): Promise => { + const session = await authenticate(params.authToken); + if (!session) { + throw new UserError("Forbidden", { code: "forbidden" }); + } + return session; + }, + + events: { + messages: event<{ userId: string; text: string }>(), + moderationLog: event<{ entry: string }>({ + canSubscribe: (c) => { + if (c.conn?.state.role === "admin") { + return true; + } + return false; + }, + }), + }, + + queues: { + moderationJobs: queue<{ action: "ban"; userId: string }>({ + canPublish: (c) => { + if (c.conn?.state.role === "admin") { + return true; + } + return false; + }, + }), + }, + + actions: { + sendMessage: (c, text: string) => { + const role = c.conn?.state.role; + const userId = c.conn?.state.userId; + + if (!userId || (role !== "member" && role !== "admin")) { + throw new UserError("Forbidden", { code: "forbidden" }); + } + + const message = { userId, text }; + c.state.messages.push(message); + c.broadcast("messages", message); + }, + }, +}); +``` + +## Return Value Contract + +`canPublish` and `canSubscribe` must return a boolean: + +- `true`: allow +- `false`: deny with `forbidden` + +Returning `undefined`, `null`, or any non-boolean throws an internal error. + +## Notes + +- `canPublish` only applies to queue names defined in `queues`. +- Incoming queue messages for undefined queues are ignored and the publish succeeds as completed. +- `canSubscribe` only applies to event names defined in `events`. +- Broadcasting an event not defined in `events` still publishes to subscribers. + +_Source doc path: /docs/actors/access-control_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/actions.md b/.agents/skills/ai-agent-workspace/reference/actors/actions.md new file mode 100644 index 0000000..cbda021 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/actions.md @@ -0,0 +1,384 @@ +# Actions + +> Source: `src/content/docs/actors/actions.mdx` +> Canonical URL: https://rivet.dev/docs/actors/actions +> Description: Actions are how your backend, frontend, or other actors can communicate with actors. + +--- +Actions are very lightweight. They can be called thousands of times per second safely. Actions are executed via HTTP requests or via WebSockets if [using `.connect()`](/docs/actors/connections). + +For advanced use cases that require direct access to HTTP requests or WebSocket connections, see [raw HTTP and WebSocket handling](/docs/actors/fetch-and-websocket-handler). + +By default, actions run in parallel. If you need advanced control over concurrency, use [queues](/docs/actors/queues). + +## Writing Actions + +Actions are defined in the `actions` object when creating an actor: + +```typescript +import { actor } from "rivetkit"; + +const mathUtils = actor({ + state: {}, + actions: { + // This is an action + multiplyByTwo: (c, x: number) => { + return x * 2; + } + } +}); +``` + +Each action receives a context object (commonly named `c`) as its first parameter, which provides access to state, connections, and other utilities. Additional parameters follow after that. + +## Calling Actions + +Actions can be called in different ways depending on your use case: + +### Frontend (createClient) + +```typescript frontend.ts +import { createClient } from "rivetkit/client"; +import { actor, setup } from "rivetkit"; + +// Define actor +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount: number) => { + c.state.count += amount; + return c.state.count; + } + } +}); + +// Create registry +const registry = setup({ use: { counter } }); + +// Create client +const client = createClient("http://localhost:6420"); +const counterActor = await client.counter.getOrCreate(); +const result = await counterActor.increment(42); +console.log(result); // The value returned by the action +``` + +Learn more about [communicating with actors from the frontend](/docs/actors/communicating-between-actors). + +### Backend (registry.handler) + +```typescript server.ts +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; +import { Hono } from "hono"; + +// Define actor +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount: number) => { + c.state.count += amount; + return c.state.count; + } + } +}); + +// Create registry +const registry = setup({ use: { counter } }); + +// Create client +const client = createClient("http://localhost:6420"); + +const app = new Hono(); + +// Mount Rivet handler +app.all("/api/rivet/*", (c) => registry.handler(c.req.raw)); + +// Use the client to call actions on a request +app.get("/foo", async (c) => { + const counterActor = client.counter.getOrCreate(); + const result = await counterActor.increment(42); + return c.text(String(result)); +}); + +export default app; +``` + +Learn more about [communicating with actors from the backend](/docs/actors/communicating-between-actors). + +### Actor-to-Actor (c.client()) + +```typescript actor.ts +import { actor, setup } from "rivetkit"; + +// Define counter actor +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount: number) => { + c.state.count += amount; + return c.state.count; + } + } +}); + +// Define actorA that calls counter +const actorA = actor({ + state: {}, + actions: { + callOtherActor: async (c) => { + const client = c.client(); + const counterActor = await client.counter.getOrCreate(); + return await counterActor.increment(10); + } + } +}); + +// Create registry +export const registry = setup({ use: { counter, actorA } }); +``` + +Learn more about [communicating between actors](/docs/actors/communicating-between-actors). + +Calling actions from the client are async and require an `await`, even if the action itself is not async. + +### Type Safety + +The actor client includes type safety out of the box. When you use `createClient()`, TypeScript automatically infers action parameter and return types: + +```typescript index.ts +import { actor, setup } from "rivetkit"; + +// Create simple counter +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, count: number) => { + c.state.count += count; + return c.state.count; + } + } +}); + +// Create and export the registry +export const registry = setup({ + use: { counter } +}); +``` + +```typescript client.ts +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +// Define the actor inline for type inference +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, count: number) => { + c.state.count += count; + return c.state.count; + } + } +}); + +const registry = setup({ use: { counter } }); +const client = createClient("http://localhost:6420"); + +// Type-safe client usage +const counterActor = await client.counter.get(); +await counterActor.increment(123); // OK +// await counterActor.increment("non-number type"); // TypeScript error +// await counterActor.nonexistentMethod(123); // TypeScript error +``` + +## Error Handling + +Actors provide robust error handling out of the box for actions. + +### User Errors + +`UserError` can be used to return rich error data to the client. You can provide: + +- A human-readable message +- A machine-readable code that's useful for matching errors in a try-catch (optional) +- A metadata object for providing richer error context (optional) + +For example: + +```typescript actor.ts +import { actor, UserError } from "rivetkit"; + +const user = actor({ + state: { username: "" }, + actions: { + updateUsername: (c, username: string) => { + // Validate username + if (username.length > 32) { + // Throw a simple error with a message + throw new UserError("Username is too long", { + code: "username_too_long", + metadata: { + maxLength: 32 + } + }); + } + + // Update username + c.state.username = username; + } + } +}); +``` + +```typescript client.ts +import { actor, setup, UserError } from "rivetkit"; +import { ActorError, createClient } from "rivetkit/client"; + +// Define the user actor +const user = actor({ + state: { username: "" }, + actions: { + updateUsername: (c, username: string) => { + if (username.length > 32) { + throw new UserError("Username is too long", { + code: "username_too_long", + metadata: { maxLength: 32 } + }); + } + c.state.username = username; + } + } +}); + +const registry = setup({ use: { user } }); +const client = createClient("http://localhost:6420"); +const userActor = await client.user.getOrCreate(); + +try { + await userActor.updateUsername("extremely_long_username_that_exceeds_limit"); +} catch (error) { + if (error instanceof ActorError) { + console.log("Message", error.message); // "Username is too long" + console.log("Code", error.code); // "username_too_long" + console.log("Metadata", error.metadata); // { maxLength: 32 } + } +} +``` + +### Internal Errors + +All other errors will return an error with the code `internal_error` to the client. This helps keep your application secure, as errors can sometimes expose sensitive information. + +## Schema Validation + +If passing data to an actor from the frontend, use a library like [Zod](https://zod.dev/) to validate input data. + +For example, to validate action parameters: + +```typescript actor.ts +import { actor, UserError } from "rivetkit"; +import { z } from "zod"; + +// Define schema for action parameters +const IncrementSchema = z.object({ + count: z.number().int().positive() +}); + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, params: unknown) => { + // Validate parameters + const result = IncrementSchema.safeParse(params); + if (!result.success) { + throw new UserError("Invalid parameters", { + code: "invalid_params", + metadata: { errors: result.error.issues } + }); + } + c.state.count += result.data.count; + return c.state.count; + } + } +}); +``` + +## Streaming Data + +Actions have a single return value. To stream realtime data in response to an action, use [events](/docs/actors/events). + +## Canceling Long-Running Actions + +For operations that should be cancelable on-demand, create your own `AbortController`. Chain it with `c.abortSignal` so actor shutdown also cancels the operation. + +```typescript +import { actor } from "rivetkit"; + +const chatActor = actor({ + createVars: () => ({ controller: null as AbortController | null }), + + actions: { + generate: async (c, prompt: string) => { + const controller = new AbortController(); + c.vars.controller = controller; + c.abortSignal.addEventListener("abort", () => controller.abort()); + + const response = await fetch("https://api.example.com/generate", { + method: "POST", + body: JSON.stringify({ prompt }), + signal: controller.signal + }); + + return await response.json(); + }, + + cancel: (c) => { + c.vars.controller?.abort(); + } + } +}); +``` + +See [Actor Shutdown Abort Signal](/docs/actors/lifecycle#actor-shutdown-abort-signal) for automatically canceling operations when the actor stops. + +## Using `ActionContext` Externally + +When writing complex logic for actions, you may want to extract parts of your implementation into separate helper functions. When doing this, you'll need a way to properly type the context parameter. + +Rivet provides the `ActionContextOf` utility type for exactly this purpose: + +```typescript +import { actor, ActionContextOf } from "rivetkit"; + +const counter = actor({ + state: { count: 0 }, + + actions: { + increment: (c) => { + incrementCount(c); + } + } +}); + +// Simple helper function with typed context +function incrementCount(c: ActionContextOf) { + c.state.count += 1; +} +``` + +See [types](/docs/actors/types) for more details on using `ActionContextOf` and other utility types. + +## Debugging + +- `GET /inspector/rpcs` lists all available actions on an actor. +- `POST /inspector/action/:name` executes an action with JSON args and returns output. +- In non-dev mode, inspector endpoints require authorization. + +## API Reference + +- [`Actions`](/typedoc/interfaces/rivetkit.mod.Actions.html) - Interface for defining actions +- [`ActionContext`](/typedoc/interfaces/rivetkit.mod.ActionContext.html) - Context available in action handlers +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining actors with actions +- [`ActorHandle`](/typedoc/types/rivetkit.client_mod.ActorHandle.html) - Handle for calling actions from client +- [`ActorActionFunction`](/typedoc/types/rivetkit.client_mod.ActorActionFunction.html) - Type for action functions + +_Source doc path: /docs/actors/actions_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/appearance.md b/.agents/skills/ai-agent-workspace/reference/actors/appearance.md new file mode 100644 index 0000000..9f769b2 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/appearance.md @@ -0,0 +1,183 @@ +# Icons & Names + +> Source: `src/content/docs/actors/appearance.mdx` +> Canonical URL: https://rivet.dev/docs/actors/appearance +> Description: Customize actors with display names and icons for the Rivet inspector and dashboard. + +--- +# Icons & Names + +Actors can be customized with a display name and icon that appear in the Rivet inspector & dashboard. This helps identify actors at a glance when managing your application. + +## Configuration + +Set the `name` and `icon` properties in your actor's `options`: + +```typescript +import { actor } from "rivetkit"; + +const chatRoom = actor({ + options: { + name: "Chat Room", // Human-friendly display name + icon: "comments", // FontAwesome icon name + }, + state: { messages: [] }, + actions: { + // ... + } +}); +``` + +## Icon Formats + +The `icon` property accepts two formats: + +### Emoji + +Use any emoji character directly: + +```typescript +import { actor } from "rivetkit"; + +const notificationService = actor({ + options: { + name: "Notifications", + icon: "🔔", + }, + // ... +}); +``` + +### FontAwesome Icons + +Use [FontAwesome](https://fontawesome.com/search) icon names without the "fa" prefix: + +```typescript +import { actor } from "rivetkit"; + +const gameServer = actor({ + options: { + name: "Game Server", + icon: "gamepad", + }, + // ... +}); + +const analyticsWorker = actor({ + options: { + name: "Analytics", + icon: "chart-line", + }, + // ... +}); +``` + +## Default Behavior + +If no `icon` is specified, actors display the default actor icon. If no `name` is specified, the actor's registry key (e.g., `chatRoom`, `gameServer`) is displayed instead. + +## Examples + +Here are some common patterns: + +```typescript +import { actor } from "rivetkit"; + +// Chat/messaging actors +const chatRoom = actor({ + options: { name: "Chat Room", icon: "comments" }, + // ... +}); + +// Game-related actors +const matchmaker = actor({ + options: { name: "Matchmaker", icon: "users" }, + // ... +}); + +const gameSession = actor({ + options: { name: "Game Session", icon: "gamepad" }, + // ... +}); + +// Data processing actors +const dataProcessor = actor({ + options: { name: "Data Processor", icon: "microchip" }, + // ... +}); + +// Using emojis for quick identification +const alertService = actor({ + options: { name: "Alerts", icon: "🚨" }, + // ... +}); +``` + +## Advanced: Run Handler Metadata + +For library developers creating reusable run handlers, you can bundle icon and name metadata directly with the `run` property. This allows libraries to provide sensible defaults without requiring users to configure them manually. + +Instead of returning a function from your run handler factory, return an object with `name`, `icon`, and `run`: + +```typescript +import type { RunConfig } from "rivetkit"; + +type MyOptions = { + mode?: "safe" | "fast"; +}; + +function myCustomRunHandler(_options: MyOptions): RunConfig { + const run: RunConfig["run"] = async (_c) => { + // Your run handler logic... + }; + + return { + name: "My Custom Handler", + icon: "bolt", + run, + }; +} +``` + +Users can then use this directly: + +```typescript +import { actor } from "rivetkit"; + +const myCustomRunHandler = (_options: Record) => ({ + name: "My Custom Handler", + icon: "bolt", + run: async () => {}, +}); + +const myActor = actor({ + run: myCustomRunHandler({ /* options */ }), + // Picks up "My Custom Handler" name and "bolt" icon in registry metadata +}); +``` + +This run-handler metadata is currently applied through the registry and serverless metadata paths. The native runtime and inspector config read the actor's `options.name` and `options.icon` directly, so set those explicitly if you need the name or icon to appear everywhere. + +Actor-level `options.name` and `options.icon` always take precedence, allowing users to override library defaults: + +```typescript +import { actor } from "rivetkit"; + +const myCustomRunHandler = (_options: Record) => ({ + name: "My Custom Handler", + icon: "bolt", + run: async () => {}, +}); + +const myActor = actor({ + options: { + name: "Custom Name", // Overrides "My Custom Handler" + icon: "rocket", // Overrides "bolt" + }, + run: myCustomRunHandler({ /* options */ }), +}); +``` + +The built-in `workflow()` helper uses this pattern to automatically display the workflow icon for workflow-based actors. + +_Source doc path: /docs/actors/appearance_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/authentication.md b/.agents/skills/ai-agent-workspace/reference/actors/authentication.md new file mode 100644 index 0000000..ff6eb90 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/authentication.md @@ -0,0 +1,598 @@ +# Authentication + +> Source: `src/content/docs/actors/authentication.mdx` +> Canonical URL: https://rivet.dev/docs/actors/authentication +> Description: Secure your actors with authentication and authorization. + +--- +## Do You Need Authentication? + +### Rivet Cloud + + Actors are private by default on Rivet Cloud. Only requests with the publishable token can interact with actors. + + - **Backend-only actors**: If your publishable token is only included in your backend, then authentication is not necessary. + - **Frontend-accessible actors**: If your publishable token is included in your frontend, then implementing authentication is recommended. + +### Self-Hosted + + Actors are public by default on self-hosted Rivet. Anyone can access them without a token. + + - **Only accessible within private network**: If Rivet is only accessible within your private network, then authentication is not necessary. + - **Rivet exposed to the public internet**: If Rivet is configured to accept traffic from the public internet, then implementing authentication is recommended. + +## Authentication Connections + +Authentication is configured through either: + +- `onBeforeConnect` for simple pass/fail validation +- `createConnState` when you need to access user data in your actions via `c.conn.state` + +## Access Control + +After a connection is authenticated, use [Access Control](/docs/actors/access-control) to enforce authorization: + +- Check permissions in action handlers. +- Use `queues..canPublish` to gate inbound queue publishes. +- Use `events..canSubscribe` to gate event subscriptions. + +### `onBeforeConnect` + +The `onBeforeConnect` hook validates credentials before allowing a connection. Throw an error to reject the connection. + +```typescript +import { actor, UserError } from "rivetkit"; + +interface ConnParams { + authToken: string; +} + +// Example token validation function +async function validateToken(token: string, roomKey: string[]): Promise { + // In production, verify JWT or call auth service + return token.length > 0 && roomKey.length > 0; +} + +interface Message { + text: string; + timestamp: number; +} + +const chatRoom = actor({ + state: { messages: [] as Message[] }, + + onBeforeConnect: async (c, params: ConnParams) => { + const roomName = c.key; + const isValid = await validateToken(params.authToken, roomName); + if (!isValid) { + throw new UserError("Forbidden", { code: "forbidden" }); + } + }, + + actions: { + sendMessage: (c, text: string) => { + c.state.messages.push({ text, timestamp: Date.now() }); + }, + }, +}); +``` + +### `createConnState` + +Use `createConnState` to extract user data from credentials and store it in connection state. This data is accessible in actions via `c.conn.state`. Like `onBeforeConnect`, throwing an error will reject the connection. See [connections](/docs/actors/connections) for more details. + +```typescript +import { actor, UserError } from "rivetkit"; + +interface ConnParams { + authToken: string; +} + +interface ConnState { + userId: string; + role: string; +} + +interface Message { + userId: string; + text: string; + timestamp: number; +} + +// Example token validation function +async function validateToken(token: string, roomKey: string[]): Promise<{ sub: string; role: string } | null> { + // In production, verify JWT or call auth service + if (token.length > 0 && roomKey.length > 0) { + return { sub: "user-123", role: "member" }; + } + return null; +} + +const chatRoom = actor({ + state: { messages: [] as Message[] }, + + createConnState: async (c, params: ConnParams): Promise => { + const roomName = c.key; + const payload = await validateToken(params.authToken, roomName); + if (!payload) { + throw new UserError("Forbidden", { code: "forbidden" }); + } + return { + userId: payload.sub, + role: payload.role, + }; + }, + + actions: { + sendMessage: (c, text: string) => { + // Access user data via c.conn.state + const { userId, role } = c.conn.state; + + if (role !== "member") { + throw new UserError("Insufficient permissions", { code: "insufficient_permissions" }); + } + + c.state.messages.push({ userId, text, timestamp: Date.now() }); + c.broadcast("newMessage", { userId, text }); + }, + }, +}); +``` + +## Available Auth Data + +Authentication hooks have access to several properties: + +| Property | Description | +|----------|-------------| +| `params` | Custom data passed by the client when connecting (see [connection params](/docs/actors/connections#extracting-data-from-connection-params)) | +| `c.request` | The underlying HTTP request object | +| `c.request.headers` | Request headers for tokens, API keys (does not work for `.connect()`) | +| `c.state` | Actor state for authorization decisions (see [state](/docs/actors/state)) | +| `c.key` | The actor's key (see [keys](/docs/actors/keys)) | + +It's recommended to use `params` instead of `c.request.headers` whenever possible since it works for both HTTP & WebSocket connections. + +## Client Usage + +### Passing Credentials + +Pass authentication data when connecting. Use `getParams` when you need a fresh JWT for every connection or reconnect: + +```typescript Connection +import { createClient } from "rivetkit/client"; + +async function getAuthToken(): Promise { + return "jwt-token-here"; +} + +const client = createClient(); +const chat = client.chatRoom.getOrCreate(["general"], { + getParams: async () => ({ + authToken: await getAuthToken(), + }), +}); + +// Authentication will happen on connect by reading connection parameters +const connection = chat.connect(); +``` + +```typescript Stateless-Action +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const chat = client.chatRoom.getOrCreate(["general"], { + params: { authToken: "jwt-token-here" }, +}); + +// Authentication will happen when calling the action by reading input +// parameters +await chat.sendMessage("Hello, world!"); +``` + +```typescript HTTP-Headers +import { createClient } from "rivetkit/client"; + +// This only works for stateless actions, not WebSockets +const client = createClient({ + headers: { + Authorization: "Bearer my-token", + }, +}); + +const chat = client.chatRoom.getOrCreate(["general"]); + +// Authentication will happen when calling the action by reading headers +await chat.sendMessage("Hello, world!"); +``` + +### Handling Errors + +Authentication errors use the same system as regular errors. See [errors](/docs/actors/errors) for more details. + +```typescript Connection +import { actor, setup } from "rivetkit"; +import { ActorError, createClient } from "rivetkit/client"; + +// Define actor with protected action +const myActor = actor({ + state: {}, + actions: { + protectedAction: (c) => ({ success: true }) + } +}); + +const registry = setup({ use: { myActor } }); +const client = createClient("http://localhost:6420"); +const actorHandle = await client.myActor.getOrCreate(); + +// Helper to show errors +function showError(message: string) { + console.error(message); +} + +const conn = actorHandle.connect(); +conn.onError((error: ActorError) => { + if (error.code === "forbidden") { + window.location.href = "/login"; + } else if (error.code === "insufficient_permissions") { + showError("You don't have permission for this action"); + } +}); +``` + +```typescript Stateless-Action +import { actor, setup } from "rivetkit"; +import { ActorError, createClient } from "rivetkit/client"; + +// Define actor with protected action +const myActor = actor({ + state: {}, + actions: { + protectedAction: (c) => ({ success: true }) + } +}); + +const registry = setup({ use: { myActor } }); +const client = createClient("http://localhost:6420"); +const actorHandle = await client.myActor.getOrCreate(); + +// Helper to show errors +function showError(message: string) { + console.error(message); +} + +try { + const result = await actorHandle.protectedAction(); +} catch (error) { + if (error instanceof ActorError && error.code === "forbidden") { + window.location.href = "/login"; + } else if (error instanceof ActorError && error.code === "insufficient_permissions") { + showError("You don't have permission for this action"); + } +} +``` + +## Examples + +### JWT + +Validate JSON Web Tokens and extract user claims: + +```typescript +import { actor, UserError } from "rivetkit"; + +interface ConnParams { + token: string; +} + +interface ConnState { + userId: string; + role: string; + permissions: string[]; +} + +interface JwtPayload { + sub: string; + role: string; + permissions?: string[]; +} + +// Example JWT verification function - in production use a JWT library +function verifyJwt(token: string, secret: string): JwtPayload { + // This is a simplified example - use jsonwebtoken or similar in production + const parts = token.split("."); + if (parts.length !== 3) throw new Error("Invalid token"); + const payload = JSON.parse(atob(parts[1])) as JwtPayload; + return payload; +} + +const jwtActor = actor({ + state: {}, + + createConnState: (c, params: ConnParams): ConnState => { + try { + const payload = verifyJwt(params.token, process.env.JWT_SECRET || "secret"); + return { + userId: payload.sub, + role: payload.role, + permissions: payload.permissions || [], + }; + } catch { + throw new UserError("Invalid or expired token", { code: "invalid_token" }); + } + }, + + actions: { + protectedAction: (c) => { + if (!c.conn.state.permissions.includes("write")) { + throw new UserError("Write permission required", { code: "forbidden" }); + } + return { success: true }; + }, + }, +}); +``` + +### External Auth Provider + +Validate credentials against an external authentication service: + +```typescript +import { actor, UserError } from "rivetkit"; + +interface ConnParams { + apiKey: string; +} + +interface ConnState { + userId: string; + tier: string; +} + +const apiActor = actor({ + state: {}, + + createConnState: async (c, params: ConnParams): Promise => { + const response = await fetch(`https://api.my-auth-provider.com/validate`, { + method: "POST", + headers: { "X-API-Key": params.apiKey }, + }); + + if (!response.ok) { + throw new UserError("Invalid API key", { code: "invalid_api_key" }); + } + + const data = await response.json(); + return { userId: data.id, tier: data.tier }; + }, + + actions: { + premiumAction: (c) => { + if (c.conn.state.tier !== "premium") { + throw new UserError("Premium subscription required", { code: "forbidden" }); + } + return "Premium content"; + }, + }, +}); +``` + +### Using `c.state` In Authorization + +Access actor state via `c.state` and the actor's key via `c.key` to make authorization decisions: + +```typescript +import { actor, UserError } from "rivetkit"; + +interface ConnParams { + userId?: string; +} + +const userProfile = actor({ + state: { + ownerId: "user-123", + isPrivate: true, + }, + + onBeforeConnect: (c, params: ConnParams) => { + // Use actor state to check access permissions + if (c.state.isPrivate && params.userId !== c.state.ownerId) { + throw new UserError("Access denied to private profile", { code: "forbidden" }); + } + }, + + actions: { + getProfile: (c) => ({ ownerId: c.state.ownerId }), + }, +}); +``` + +### Role-Based Access Control + +Create helper functions for common authorization patterns: + +```typescript +import { actor, UserError } from "rivetkit"; + +const ROLE_HIERARCHY = { user: 1, moderator: 2, admin: 3 }; + +interface ConnState { + role: keyof typeof ROLE_HIERARCHY; + permissions: string[]; +} + +// Example token validation function +async function validateToken(token: string): Promise<{ role: keyof typeof ROLE_HIERARCHY; permissions: string[] }> { + // In production, verify JWT or call auth service + return { role: "user", permissions: ["read", "edit_posts"] }; +} + +function requireRole(requiredRole: keyof typeof ROLE_HIERARCHY) { + return (c: { conn: { state: ConnState } }) => { + const userRole = c.conn.state.role; + if (ROLE_HIERARCHY[userRole] < ROLE_HIERARCHY[requiredRole]) { + throw new UserError(`${requiredRole} role required`, { code: "forbidden" }); + } + }; +} + +function requirePermission(permission: string) { + return (c: { conn: { state: ConnState } }) => { + if (!c.conn.state.permissions?.includes(permission)) { + throw new UserError(`Permission '${permission}' required`, { code: "forbidden" }); + } + }; +} + +const forumActor = actor({ + state: {}, + + createConnState: async (c, params: { token: string }): Promise => { + const user = await validateToken(params.token); + return { role: user.role, permissions: user.permissions }; + }, + + actions: { + deletePost: (c, postId: string) => { + requireRole("moderator")(c); + // Delete post... + }, + + editPost: (c, postId: string, content: string) => { + requirePermission("edit_posts")(c); + // Edit post... + }, + }, +}); +``` + +### Rate Limiting + +Use `c.vars` to track connection attempts and rate limit by user: + +```typescript +import { actor, UserError } from "rivetkit"; + +interface ConnParams { + authToken: string; +} + +interface RateLimitEntry { + count: number; + resetAt: number; +} + +// Example token validation function +async function validateToken(token: string): Promise<{ userId: string }> { + // In production, verify JWT or call auth service + return { userId: "user-123" }; +} + +const rateLimitedActor = actor({ + state: {}, + createVars: () => ({ rateLimits: {} as Record }), + + onBeforeConnect: async (c, params: ConnParams) => { + // Extract user ID + const { userId } = await validateToken(params.authToken); + + // Check rate limit + const now = Date.now(); + const limit = c.vars.rateLimits[userId]; + + if (limit && limit.resetAt > now && limit.count >= 10) { + throw new UserError("Too many requests, try again later", { code: "rate_limited" }); + } + + // Update rate limit + if (!limit || limit.resetAt <= now) { + c.vars.rateLimits[userId] = { count: 1, resetAt: now + 60_000 }; + } else { + limit.count++; + } + }, + + actions: { + getData: (c) => ({ success: true }), + }, +}); +``` + +The limits in this example are [ephemeral](/docs/actors/state#ephemeral-variables). If you wish to persist rate limits, you can optionally replace `vars` with `state`. + +### Caching Tokens + +Cache validated tokens in `c.vars` to avoid redundant validation on repeated connections. See [ephemeral variables](/docs/actors/state#ephemeral-variables) for more details. + +```typescript +import { actor, UserError } from "rivetkit"; + +interface ConnParams { + authToken: string; +} + +interface ConnState { + userId: string; + role: string; +} + +interface TokenCache { + [token: string]: { + userId: string; + role: string; + expiresAt: number; + }; +} + +// Example token validation function +async function validateToken(token: string): Promise<{ sub: string; role: string } | null> { + // In production, verify JWT or call auth service + if (token.length > 0) { + return { sub: "user-123", role: "member" }; + } + return null; +} + +const cachedAuthActor = actor({ + state: {}, + createVars: () => ({ tokenCache: {} as TokenCache }), + + createConnState: async (c, params: ConnParams): Promise => { + const token = params.authToken; + + // Check cache first + const cached = c.vars.tokenCache[token]; + if (cached && cached.expiresAt > Date.now()) { + return { userId: cached.userId, role: cached.role }; + } + + // Validate token (expensive operation) + const payload = await validateToken(token); + if (!payload) { + throw new UserError("Invalid token", { code: "invalid_token" }); + } + + // Cache the result + c.vars.tokenCache[token] = { + userId: payload.sub, + role: payload.role, + expiresAt: Date.now() + 5 * 60 * 1000, // 5 minutes + }; + + return { userId: payload.sub, role: payload.role }; + }, + + actions: { + getData: (c) => ({ userId: c.conn.state.userId }), + }, +}); +``` + +## API Reference + +- [`AuthIntent`](/typedoc/types/rivetkit.mod.AuthIntent.html) - Authentication intent type +- [`OnBeforeConnectContext`](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html) - Context for auth checks +- [`OnConnectContext`](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html) - Context after connection + +_Source doc path: /docs/actors/authentication_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/communicating-between-actors.md b/.agents/skills/ai-agent-workspace/reference/actors/communicating-between-actors.md new file mode 100644 index 0000000..2e8205a --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/communicating-between-actors.md @@ -0,0 +1,336 @@ +# Communicating Between Actors + +> Source: `src/content/docs/actors/communicating-between-actors.mdx` +> Canonical URL: https://rivet.dev/docs/actors/communicating-between-actors +> Description: Learn how actors can call other actors and share data + +--- +Actors can communicate with each other using the server-side actor client, enabling complex workflows and data sharing between different actor instances. + +We recommend reading the [clients documentation](/docs/clients) first. This guide focuses specifically on communication between actors. + +## Using the Server-Side Actor Client + +The server-side actor client allows actors to call other actors within the same registry. Access it via `c.client()` in your actor context: + +If two actors call each other and their return types are inferred from the other actor's response, you may hit circular type errors (`TS2322`, `TS2722`, or `c.state` becoming `unknown`). Fix this by writing explicit return types on those actions. + +```typescript +import { actor, setup } from "rivetkit"; + +interface Order { + id: string; + customerId: string; + quantity: number; + amount: number; +} + +interface ProcessedOrder extends Order { + status: string; + paymentResult: { transactionId: string }; +} + +const inventory = actor({ + state: { stock: 100 }, + actions: { + reserveStock: (c, quantity: number) => { + c.state.stock -= quantity; + return { reserved: quantity }; + } + } +}); + +const payment = actor({ + state: {}, + actions: { + processPayment: (c, amount: number) => ({ transactionId: "tx-123" }) + } +}); + +const orderProcessor = actor({ + state: { orders: [] as ProcessedOrder[] }, + + actions: { + processOrder: async (c, order: Order) => { + const client = c.client(); + + // Reserve the stock + const inventoryHandle = client.inventory.getOrCreate(["main"]); + await inventoryHandle.reserveStock(order.quantity); + + // Process payment through payment actor + const paymentHandle = client.payment.getOrCreate([order.customerId]); + const result = await paymentHandle.processPayment(order.amount); + + // Update order state + c.state.orders.push({ ...order, status: "completed", paymentResult: result }); + + return { success: true, orderId: order.id }; + } + } +}); + +const registry = setup({ use: { inventory, payment, orderProcessor } }); +``` + +## Use Cases and Patterns + +### Actor Orchestration + +Use a coordinator actor to manage complex workflows: + +```typescript +import { actor, setup } from "rivetkit"; + +interface WorkflowResult { + workflowId: string; + result: { finalized: boolean }; + completedAt: number; +} + +const dataProcessor = actor({ + state: {}, + actions: { + initialize: (c, workflowId: string) => ({ workflowId, data: "initialized" }) + } +}); + +const validator = actor({ + state: {}, + actions: { + validate: (c, data: { workflowId: string; data: string }) => ({ valid: true, data }) + } +}); + +const finalizer = actor({ + state: {}, + actions: { + finalize: (c, validationResult: { valid: boolean }) => ({ finalized: validationResult.valid }) + } +}); + +const workflowActor = actor({ + state: { workflows: [] as WorkflowResult[] }, + + actions: { + executeWorkflow: async (c, workflowId: string) => { + const client = c.client(); + + // Step 1: Initialize data + const dataProcessorHandle = client.dataProcessor.getOrCreate(["main"]); + const data = await dataProcessorHandle.initialize(workflowId); + + // Step 2: Process through multiple actors + const validatorHandle = client.validator.getOrCreate(["main"]); + const validationResult = await validatorHandle.validate(data); + + // Step 3: Finalize + const finalizerHandle = client.finalizer.getOrCreate(["main"]); + const result = await finalizerHandle.finalize(validationResult); + + c.state.workflows.push({ workflowId, result, completedAt: Date.now() }); + return result; + } + } +}); + +const registry = setup({ use: { dataProcessor, validator, finalizer, workflowActor } }); +``` + +### Data Aggregation + +Collect data from multiple actors: + +```typescript +import { actor, setup } from "rivetkit"; + +interface Stats { + count: number; + total: number; +} + +interface Report { + id: string; + type: string; + data: { users: Stats; orders: Stats; system: Stats }; + generatedAt: number; +} + +const userMetrics = actor({ + state: {}, + actions: { + getStats: (c): Stats => ({ count: 100, total: 500 }) + } +}); + +const orderMetrics = actor({ + state: {}, + actions: { + getStats: (c): Stats => ({ count: 50, total: 10000 }) + } +}); + +const systemMetrics = actor({ + state: {}, + actions: { + getStats: (c): Stats => ({ count: 5, total: 99 }) + } +}); + +const analyticsActor = actor({ + state: { reports: [] as Report[] }, + + actions: { + generateReport: async (c, reportType: string) => { + const client = c.client(); + + // Collect data from multiple sources + const userMetricsHandle = client.userMetrics.getOrCreate(["main"]); + const orderMetricsHandle = client.orderMetrics.getOrCreate(["main"]); + const systemMetricsHandle = client.systemMetrics.getOrCreate(["main"]); + + const [users, orders, system] = await Promise.all([ + userMetricsHandle.getStats(), + orderMetricsHandle.getStats(), + systemMetricsHandle.getStats() + ]); + + const report: Report = { + id: crypto.randomUUID(), + type: reportType, + data: { users, orders, system }, + generatedAt: Date.now() + }; + + c.state.reports.push(report); + return report; + } + } +}); + +const registry = setup({ use: { userMetrics, orderMetrics, systemMetrics, analyticsActor } }); +``` + +### Event-Driven Architecture + +Use connections to listen for events from other actors: + +```typescript +import { actor, setup } from "rivetkit"; + +interface User { + id: string; + name: string; +} + +interface Order { + id: string; + amount: number; +} + +interface AuditLog { + event: string; + data: User | Order; + timestamp: number; +} + +const userActor = actor({ + state: {}, + actions: { + createUser: (c, name: string) => { + const user = { id: crypto.randomUUID(), name }; + c.broadcast("userCreated", user); + return user; + } + } +}); + +const orderActor = actor({ + state: {}, + actions: { + completeOrder: (c, amount: number) => { + const order = { id: crypto.randomUUID(), amount }; + c.broadcast("orderCompleted", order); + return order; + } + } +}); + +const auditLogActor = actor({ + state: { logs: [] as AuditLog[] }, + + actions: { + startAuditing: async (c) => { + const client = c.client(); + + // Connect to multiple actors to listen for events + const userActorConn = client.userActor.getOrCreate(["main"]).connect(); + const orderActorConn = client.orderActor.getOrCreate(["main"]).connect(); + + // Listen for user events + userActorConn.on("userCreated", (user: User) => { + c.state.logs.push({ + event: "userCreated", + data: user, + timestamp: Date.now() + }); + }); + + // Listen for order events + orderActorConn.on("orderCompleted", (order: Order) => { + c.state.logs.push({ + event: "orderCompleted", + data: order, + timestamp: Date.now() + }); + }); + + return { status: "auditing started" }; + } + } +}); + +const registry = setup({ use: { userActor, orderActor, auditLogActor } }); +``` + +### Batch Operations + +Process multiple items in parallel: + +```typescript +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +interface Item { + type: string; + data: string; +} + +const processor = actor({ + state: {}, + actions: { + process: (c, item: Item) => ({ processed: true, item }) + } +}); + +const registry = setup({ use: { processor } }); +const client = createClient("http://localhost:6420"); + +// Process items in parallel +const items: Item[] = [ + { type: "typeA", data: "data1" }, + { type: "typeB", data: "data2" } +]; + +const results = await Promise.all( + items.map(item => client.processor.getOrCreate([item.type]).process(item)) +); +``` + +## API Reference + +- [`ActorHandle`](/typedoc/types/rivetkit.client_mod.ActorHandle.html) - Handle for calling other actors +- [`Client`](/typedoc/types/rivetkit.mod.Client.html) - Client type for actor communication +- [`ActorAccessor`](/typedoc/interfaces/rivetkit.client_mod.ActorAccessor.html) - Accessor for getting actor handles + +_Source doc path: /docs/actors/communicating-between-actors_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/connections.md b/.agents/skills/ai-agent-workspace/reference/actors/connections.md new file mode 100644 index 0000000..bcac8dc --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/connections.md @@ -0,0 +1,460 @@ +# Connections + +> Source: `src/content/docs/actors/connections.mdx` +> Canonical URL: https://rivet.dev/docs/actors/connections +> Description: Connections represent client connections to your actor. They provide a way to handle client authentication, manage connection-specific data, and control the connection lifecycle. + +--- +For documentation on connecting to actors from clients, see the [Clients documentation](/docs/clients). For worked presence and chat patterns, see the cookbook: [Live Cursors and Presence](/cookbook/live-cursors/) and [Chat Room](/cookbook/chat-room/). + +## Parameters + +When clients connect to an actor, they can pass connection parameters that are handled during the connection process. Use `params` for static values, or `getParams` when you need fresh connection data each time a connection opens. + +For example: + +```typescript Client +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +interface ConnParams { + authToken: string; +} + +interface ConnState { + userId: string; + role: string; +} + +const gameRoom = actor({ + state: {}, + createConnState: (c, params: ConnParams): ConnState => { + return { userId: "user-123", role: "player" }; + }, + actions: {} +}); + +const registry = setup({ use: { gameRoom } }); +const client = createClient("http://localhost:6420"); + +async function getAuthToken(): Promise { + return "supersekure"; +} + +const gameRoomHandle = client.gameRoom.getOrCreate(["room-123"], { + getParams: async () => ({ + authToken: await getAuthToken(), + }) +}); +``` + +```typescript Actor +import { actor } from "rivetkit"; + +interface ConnParams { + authToken: string; +} + +interface ConnState { + userId: string; + role: string; +} + +// Example validation functions +function validateToken(token: string): boolean { + return token.length > 0; +} + +function getUserIdFromToken(token: string): string { + return "user-" + token.slice(0, 8); +} + +const gameRoom = actor({ + state: {}, + + // Handle connection setup + createConnState: (c, params: ConnParams): ConnState => { + // 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: {} +}); +``` + +## Connection State + +There are two ways to define an actor's connection state: + + +### connState + + Define connection state as a constant value: + + ```typescript + import { actor } from "rivetkit"; + + const chatRoom = actor({ + state: { messages: [] }, + + // Define default connection state as a constant + connState: { + role: "guest", + joinedAt: 0 + }, + + onConnect: (c) => { + // Update join timestamp when a client connects + c.conn.state.joinedAt = Date.now(); + }, + + actions: { + // ... + } + }); + ``` + + This value will be cloned for every new connection using `structuredClone`. + + + +### createConnState + + Create connection state dynamically with a function called for each connection: + + ```typescript + import { actor } from "rivetkit"; + + interface ConnState { + userId: string; + role: string; + joinedAt: number; + } + + interface Message { + username: string; + message: string; + } + + function generateUserId(): string { + return "user-" + Math.random().toString(36).slice(2, 11); + } + + const chatRoom = actor({ + state: { messages: [] as Message[] }, + + // Create connection state dynamically + createConnState: (c): ConnState => { + // Return the connection state + return { + userId: generateUserId(), + role: "guest", + joinedAt: Date.now() + }; + }, + + actions: { + sendMessage: (c, message: string) => { + const username = c.conn.state.userId; + c.state.messages.push({ username, message }); + c.broadcast("newMessage", { username, message }); + } + } + }); + ``` + + +## Connection Lifecycle + +Each client connection goes through a series of lifecycle hooks that allow you to validate, initialize, and clean up connection-specific resources. + +**On Connect** (per client) + +- `onBeforeConnect` +- `createConnState` +- `onConnect` + +Pending connections are not visible in `c.conns` while `onBeforeConnect` or `createConnState` is running. RivetKit adds the connection to `c.conns` after those hooks succeed and before `onConnect` runs. + +**On Disconnect** (per client) + +- `onDisconnect` + +### `createConnState` and `connState` + +[API Reference](/typedoc/interfaces/rivetkit.mod.CreateConnStateContext.html) + +There are two ways to define the initial state for connections: +1. `connState`: Define a constant object that will be used as the initial state for all connections +2. `createConnState`: A function that dynamically creates initial connection state based on connection parameters. Can be async. + +Connections are not visible in `c.conns` until `createConnState` completes successfully. + +### `onBeforeConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html) + +The `onBeforeConnect` hook is called whenever a new client connects to the actor. Can be async. Clients can pass parameters when connecting, accessible via `params`. This hook is used for connection validation and can throw errors to reject connections. + +The `onBeforeConnect` hook does NOT return connection state - it's used solely for validation. + +Connections are not visible in `c.conns` while `onBeforeConnect` is running. + +```typescript +import { actor } from "rivetkit"; + +interface Message { + text: string; + author: string; +} + +interface ConnParams { + authToken?: string; + userId?: string; + role?: string; +} + +interface ConnState { + userId: string; + role: string; + joinTime: number; +} + +function validateToken(token: string): boolean { + return token.length > 0; +} + +const chatRoom = actor({ + state: { messages: [] as Message[] }, + + // Dynamically create connection state + createConnState: (c, params: ConnParams): ConnState => { + return { + userId: params.userId || "anonymous", + role: params.role || "guest", + joinTime: Date.now() + }; + }, + + // Validate connections before accepting them + onBeforeConnect: (c, params: ConnParams) => { + // Validate authentication + const authToken = params.authToken; + if (!authToken || !validateToken(authToken)) { + throw new Error("Invalid authentication"); + } + + // Authentication is valid, connection will proceed + // The actual connection state will come from createConnState + }, + + actions: {} +}); +``` + +Connections cannot interact with the actor until this method completes successfully. Throwing an error will abort the connection. This can be used for authentication, see [Authentication](/docs/actors/authentication) for details. + +### `onConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html) + +Executed after the client has successfully connected. Can be async. Receives the connection object as a second parameter. + +By the time `onConnect` runs, the connection is visible in `c.conns`. + +```typescript +import { actor } from "rivetkit"; + +interface ConnState { + userId: string; +} + +interface UserStatus { + online: boolean; + lastSeen: number; +} + +const chatRoom = actor({ + state: { users: {} as Record, messages: [] as string[] }, + + createConnState: (): ConnState => ({ + userId: "user-" + Math.random().toString(36).slice(2, 11) + }), + + onConnect: (c, conn) => { + // Add user to the room's user list using connection state + const userId = conn.state.userId; + c.state.users[userId] = { + online: true, + lastSeen: Date.now() + }; + + // Broadcast that a user joined + c.broadcast("userJoined", { userId, timestamp: Date.now() }); + + console.log(`User ${userId} connected`); + }, + + actions: {} +}); +``` + +Messages will not be processed for this actor until this hook succeeds. Errors thrown from this hook will cause the client to disconnect. + +### `onDisconnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Called when a client disconnects from the actor. Can be async. Receives the connection object as a second parameter. Use this to clean up any connection-specific resources. + +```typescript +import { actor } from "rivetkit"; + +interface ConnState { + userId: string; +} + +interface UserStatus { + online: boolean; + lastSeen: number; +} + +const chatRoom = actor({ + state: { users: {} as Record, messages: [] as string[] }, + + createConnState: (): ConnState => ({ + userId: "user-" + Math.random().toString(36).slice(2, 11) + }), + + onDisconnect: (c, conn) => { + // Update user status when they disconnect + const userId = conn.state.userId; + if (c.state.users[userId]) { + c.state.users[userId].online = false; + c.state.users[userId].lastSeen = Date.now(); + } + + // Broadcast that a user left + c.broadcast("userLeft", { userId, timestamp: Date.now() }); + + console.log(`User ${userId} disconnected`); + }, + + actions: {} +}); +``` + +## Connection List + +All active connections can be accessed through the context object's `conns` property. This is a `Map` of all current connections, keyed by connection ID. + +This is frequently used with `conn.send(name, event)` to send messages directly to clients. To send an event to all connections at once, use `c.broadcast()` instead. See [Events](/docs/actors/events) for more details on broadcasting. + +For example: + +```typescript +import { actor } from "rivetkit"; + +interface ConnState { + userId: string; +} + +const chatRoom = actor({ + state: { users: {} as Record }, + + createConnState: (): ConnState => ({ + userId: "user-" + Math.random().toString(36).slice(2, 11) + }), + + actions: { + sendDirectMessage: (c, recipientId: string, message: string) => { + // Find the recipient's connection by iterating over the Map + let recipientConn = null; + for (const conn of c.conns.values()) { + if (conn.state.userId === recipientId) { + recipientConn = conn; + break; + } + } + + if (recipientConn) { + // Send a private message to just that client + recipientConn.send("directMessage", { + from: c.conn.state.userId, + message: message + }); + } + } + } +}); +``` + +`conn.send()` has no effect on [low-level WebSocket connections](/docs/actors/websocket-handler). For low-level WebSockets, use the WebSocket API directly (e.g., `websocket.send()`). + +## Disconnecting clients + +Connections can be disconnected from within an action: + +```typescript +import { actor } from "rivetkit"; + +interface ConnState { + userId: string; +} + +const secureRoom = actor({ + state: {}, + + createConnState: (): ConnState => ({ + userId: "user-" + Math.random().toString(36).slice(2, 11) + }), + + actions: { + kickUser: (c, targetUserId: string, reason?: string) => { + // Find the connection to kick by iterating over the Map + for (const conn of c.conns.values()) { + if (conn.state.userId === targetUserId) { + // Disconnect with a reason + conn.disconnect(reason || "Kicked by admin"); + break; + } + } + } + } +}); +``` + +If you need to wait for the disconnection to complete, you can use `await`: + +```typescript +import { actor } from "rivetkit"; + +const myActor = actor({ + state: {}, + actions: { + disconnect: async (c) => { + await c.conn.disconnect("Too many requests"); + } + } +}); +``` + +This ensures the underlying network connections close cleanly before continuing. + +## API Reference + +- [`Conn`](/typedoc/interfaces/rivetkit.mod.Conn.html) - Connection interface +- [`ConnInitContext`](/typedoc/interfaces/rivetkit.mod.ConnInitContext.html) - Connection initialization context +- [`CreateConnStateContext`](/typedoc/interfaces/rivetkit.mod.CreateConnStateContext.html) - Context for creating connection state +- [`OnBeforeConnectContext`](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html) - Pre-connection lifecycle hook context +- [`OnConnectContext`](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html) - Post-connection lifecycle hook context +- [`ActorConn`](/typedoc/types/rivetkit.client_mod.ActorConn.html) - Typed connection from client side + +_Source doc path: /docs/actors/connections_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/debugging.md b/.agents/skills/ai-agent-workspace/reference/actors/debugging.md new file mode 100644 index 0000000..e77debe --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/debugging.md @@ -0,0 +1,644 @@ +# Debugging + +> Source: `src/content/docs/actors/debugging.mdx` +> Canonical URL: https://rivet.dev/docs/actors/debugging +> Description: Inspect and debug running Rivet Actors, runners, and provider configs using management, runner, and actor inspector HTTP APIs. + +--- +## Connecting to Rivet + +All debugging endpoints in this guide are available both locally and in production. In local development, the base URL is `http://localhost:6420` with no authentication. In production (Rivet Cloud or self-hosted), you connect to your Rivet Engine endpoint with a token. + +### Setup + +All examples in this guide use these shell variables. Extract them from your `RIVET_ENDPOINT` (`https://:@`): + +```bash +# From RIVET_ENDPOINT=https://my-namespace:sk_abc123@api.rivet.dev +export RIVET_API="https://api.rivet.dev" +export RIVET_NAMESPACE="my-namespace" +export RIVET_TOKEN="sk_abc123" + +# For local development: +# export RIVET_API="http://localhost:6420" +``` + +Rivet Cloud issues two token types: `sk_` (secret key, server-side only) and `pk_` (public key, client-safe). For debugging, always use `sk_`. See [Endpoints](/docs/general/endpoints) for more details. + +## Management API + +The management API runs on the manager base path (default root path) and is used to list, create, and look up actors. + +### Authentication + +| Environment | Authentication | +|---|---| +| **Local development** | No authentication required. All endpoints are accessible without tokens. | +| **Self-hosted engine** | Set `RIVET_TOKEN` to enable authenticated access to restricted endpoints like KV. | +| **Rivet Cloud** | Authentication is enforced by your deployment entrypoint. For manager KV access, use the bearer token header below when enabled. | + +Restricted endpoints (like KV reads) require the `Authorization: Bearer` header when `RIVET_TOKEN` is configured: + +```bash +curl "$RIVET_API/actors/{actor_id}/kv/keys/{base64_key}" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +### List Actors + +```bash +# List all actors with a given name +curl "$RIVET_API/actors?name=my-actor&namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" + +# Look up one actor by key (name is required when key is provided) +curl "$RIVET_API/actors?name=my-actor&key=%5B%22my-key%22%5D&namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" + +# List actors by IDs (comma-separated) +curl "$RIVET_API/actors?actor_ids=id1,id2&namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Rules: + +- `key` requires `name`. +- `actor_ids` cannot be combined with `name` or `key`. + +Returns: + +```json +{ + "actors": [ + { + "actor_id": "abc123", + "name": "my-actor", + "key": "[\"default\"]", + "namespace_id": "default", + "create_ts": 1706000000000 + } + ] +} +``` + +### Create Actor + +`POST /actors` creates a new actor. + +```bash +curl -X POST "$RIVET_API/actors?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H 'Content-Type: application/json' \ + -d '{ + "name": "my-actor", + "runner_name_selector": "default", + "crash_policy": "restart" + }' +``` + +### Create or Get Actor + +`PUT /actors` creates an actor if it does not exist, otherwise returns the existing one. + +```bash +curl -X PUT "$RIVET_API/actors?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H 'Content-Type: application/json' \ + -d '{ + "name": "my-actor", + "key": "[\"default\"]", + "runner_name_selector": "default", + "crash_policy": "restart" + }' +``` + +Returns the actor object with its `actor_id`. + +### List Actor Names + +```bash +curl "$RIVET_API/actors/names?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns all registered actor names and their metadata. + +### Read Actor KV + +Requires authentication (see above). + +```bash +curl "$RIVET_API/actors/{actor_id}/kv/keys/{base64_key}" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns the value stored at the given key. + +See the [OpenAPI spec](https://github.com/rivet-dev/rivet/tree/main/rivetkit-openapi) for the full schema of all management endpoints. + +## Runner API + +Use the runner endpoints to debug scheduler capacity and provider configuration (for example serverless URL, headers, and limits) through the Rivet API. + +### List Runner Names + +```bash +curl "$RIVET_API/runners/names?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns the runner pools available in the namespace: + +```json +{ + "names": ["default", "gpu-workers"], + "pagination": { "cursor": null } +} +``` + +### List Runners in a Pool + +```bash +curl "$RIVET_API/runners?namespace=$RIVET_NAMESPACE&name=default&include_stopped=true&limit=100" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Useful fields when debugging: + +- `remaining_slots` / `total_slots` for capacity. +- `drain_ts` and `stop_ts` for shutdown behavior. +- `last_ping_ts` and `last_connected_ts` for connectivity. + +### Inspect Provider Config (Runner Config) + +```bash +curl "$RIVET_API/runner-configs?namespace=$RIVET_NAMESPACE&runner_name=default" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns the configured provider settings per datacenter and the latest pool error (if any): + +```json +{ + "runner_configs": { + "default": { + "datacenters": { + "dc-1": { + "serverless": { + "url": "https://your-deployment.example.com/rivet", + "headers": { "Authorization": "Bearer token" }, + "request_lifespan": 55, + "slots_per_runner": 1, + "max_runners": 10 + }, + "runner_pool_error": null + } + } + } + }, + "pagination": { "cursor": null } +} +``` + +`runner_pool_error` mirrors actor scheduling errors such as `serverless_http_error`, `serverless_connection_error`, and `serverless_stream_ended_early`. + +### Check Serverless Provider Health + +Use this to test whether Rivet can reach your serverless provider URL and read runner metadata: + +```bash +curl -X POST "$RIVET_API/runner-configs/serverless-health-check?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "url": "https://your-deployment.example.com/rivet", + "headers": { + "Authorization": "Bearer token" + } + }' +``` + +Possible responses: + +```json +{ "success": { "version": "1.2.3" } } +``` + +```json +{ + "failure": { + "error": { + "message": "non-success status from metadata endpoint", + "details": "received status 503" + } + } +} +``` + +### Refresh Provider Metadata + +If you deploy new actor code or routes and metadata has not updated yet, force a refresh: + +```bash +curl -X POST "$RIVET_API/runner-configs/default/refresh-metadata?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{}' +``` + +## Actor API + +All actor-level endpoints are accessed through the gateway. The gateway routes requests to the correct actor instance using the actor ID in the URL path: + +``` +{RIVET_API}/gateway/{actor_id}/{path} +``` + +The gateway only accepts actor IDs, not names. Use `GET /actors?name=...` from the management API to look up actor IDs first. + +### Authentication + +Standard actor endpoints (health, actions, requests) and inspector endpoints have separate authentication requirements. + +#### Standard Endpoints + +| Environment | Authentication | +|---|---| +| **Local development** | No authentication required. | +| **Self-hosted engine** | The Rivet Engine handles authentication at the gateway level. | +| **Rivet Cloud** | Authentication is handled by the Rivet Cloud platform at the gateway level. | + +#### Inspector Endpoints + +Each actor generates a unique inspector token on first start and persists it in its internal KV store at key `0x03` (base64 `Aw==`). Pass it as a bearer token in the `Authorization` header. + +Inspector endpoints always require the actor's inspector token, including in local development. There is no local-development bypass. + +| Environment | Authentication | +|---|---| +| **Local development** | Bearer the actor's inspector token in the `Authorization` header. Fetch it through the management KV endpoint (see below). | +| **Self-hosted engine** | Bearer the actor's inspector token in the `Authorization` header. The Rivet dashboard fetches it automatically; for direct API access, fetch it through the management KV endpoint (see below). | +| **Rivet Cloud** | Bearer the actor's inspector token in the `Authorization` header. The Rivet dashboard fetches it automatically; for direct API access, fetch it through the management KV endpoint (see below). | + +```bash +curl "$RIVET_API/gateway/{actor_id}/inspector/summary" \ + -H 'Authorization: Bearer YOUR_INSPECTOR_TOKEN' +``` + +#### Retrieving the Inspector Token + +Each actor generates a unique inspector token on first start and persists it in its internal KV store. The Rivet dashboard retrieves this token automatically, but if you need it for direct API access, fetch it from the management KV endpoint. This applies in every environment, including local development. + +The inspector token is stored at internal KV key `0x03` (base64: `Aw==`). The response value is also base64-encoded. + +```bash +# Fetch the inspector token for a specific actor +ACTOR_ID="your-actor-id" + +RESPONSE=$(curl -s "$RIVET_API/actors/$ACTOR_ID/kv/keys/Aw==" \ + -H "Authorization: Bearer $RIVET_TOKEN") + +# Extract and decode the base64 value +INSPECTOR_TOKEN=$(echo "$RESPONSE" | jq -r '.value' | base64 -d) + +# Use it to call inspector endpoints +curl "$RIVET_API/gateway/$ACTOR_ID/inspector/summary" \ + -H "Authorization: Bearer $INSPECTOR_TOKEN" +``` + +### Standard Actor Endpoints + +These are the built-in actor endpoints available through the gateway: + +```bash +# Health check +curl $RIVET_API/gateway/{actor_id}/health + +# Metadata +curl $RIVET_API/gateway/{actor_id}/metadata + +# Call an action +curl -X POST $RIVET_API/gateway/{actor_id}/action/myAction \ + -H 'Content-Type: application/json' \ + -d '{"args": [1, 2, 3]}' + +# Send queue message (queue name in path) +curl -X POST $RIVET_API/gateway/{actor_id}/queue/jobs \ + -H 'Content-Type: application/json' \ + -d '{"body":{"id":"job-1"}}' + +# Send queue message and wait for completion (optional timeout in ms) +curl -X POST $RIVET_API/gateway/{actor_id}/queue/jobs \ + -H 'Content-Type: application/json' \ + -d '{"body":{"id":"job-1"},"wait":true,"timeout":5000}' + +# Forward an HTTP request to the actor's onRequest handler +curl $RIVET_API/gateway/{actor_id}/request/my/custom/path +``` + +Queue send responses always include a `status` field: + +```json +{ "status": "completed" } +``` + +The `response` field is only present when the queue handler returns a value: + +```json +{ "status": "completed", "response": { "result": "ok" } } +``` + +If `wait: true` and the timeout is reached, `status` is `"timedOut"`. + +### Inspector Endpoints + +The inspector HTTP API exposes JSON endpoints for querying and modifying actor internals at runtime. These are designed for agent-based debugging and tooling. + +Every inspector endpoint requires the actor's inspector token as a bearer token, including in local development. The examples below omit the `Authorization` header for brevity, but you must add `-H "Authorization: Bearer $INSPECTOR_TOKEN"` to each request. See [Retrieving the Inspector Token](#retrieving-the-inspector-token) above. + +#### Get State + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/state +``` + +Returns the actor's current persisted state: + +```json +{ + "state": { "count": 42, "users": [] }, + "isStateEnabled": true +} +``` + +#### Set State + +```bash +curl -X PATCH $RIVET_API/gateway/{actor_id}/inspector/state \ + -H 'Content-Type: application/json' \ + -d '{"state": {"count": 0, "users": []}}' +``` + +Returns: + +```json +{ "ok": true } +``` + +#### Get Connections + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/connections +``` + +Returns all active connections with their params, state, and metadata: + +```json +{ + "connections": [ + { + "type": "websocket", + "id": "conn-id", + "details": { + "type": "websocket", + "params": {}, + "stateEnabled": true, + "state": {}, + "subscriptions": 2, + "isHibernatable": true + } + } + ] +} +``` + +#### Get RPCs + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/rpcs +``` + +Returns a list of available actions: + +```json +{ "rpcs": ["increment", "getCount"] } +``` + +#### Execute Action + +```bash +curl -X POST $RIVET_API/gateway/{actor_id}/inspector/action/increment \ + -H 'Content-Type: application/json' \ + -d '{"args": [5]}' +``` + +Returns: + +```json +{ "output": 47 } +``` + +#### Get Queue Status + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/queue?limit=10 +``` + +Returns queue status with messages: + +```json +{ + "size": 3, + "maxSize": 1000, + "truncated": false, + "messages": [ + { "id": 1, "name": "process", "createdAtMs": 1706000000000 } + ] +} +``` + +#### Get Workflow History + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/workflow-history +``` + +Returns: + +```json +{ + "history": null, + "isWorkflowEnabled": false +} +``` + +#### Get Database Schema + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/database/schema +``` + +Returns discovered SQLite tables and views when the actor has `c.db` enabled: + +```json +{ + "schema": { + "tables": [ + { + "table": { "schema": "main", "name": "test_data", "type": "table" }, + "columns": [ + { "cid": 0, "name": "id", "type": "", "notnull": 0, "dflt_value": null, "pk": 0 } + ], + "foreignKeys": [], + "records": 2 + } + ] + } +} +``` + +#### Get Database Rows + +```bash +curl "$RIVET_API/gateway/{actor_id}/inspector/database/rows?table=test_data&limit=100&offset=0" +``` + +Returns paged rows for a specific SQLite table or view: + +```json +{ + "rows": [ + { + "id": 1, + "value": "Alice", + "payload": "", + "created_at": 1706000000000 + } + ] +} +``` + +#### Execute SQLite + +Run manual SQL against an actor's SQLite database. This supports both read-only queries and mutations. + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/database/execute \ + -H 'Content-Type: application/json' \ + -d '{ + "sql": "SELECT id, value FROM test_data WHERE value = ? ORDER BY id DESC", + "args": ["alpha"] + }' +``` + +Returns: + +```json +{ + "rows": [ + { "id": 2, "value": "alpha" } + ] +} +``` + +You can also use named SQLite bindings through a `properties` object: + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/database/execute \ + -H 'Content-Type: application/json' \ + -d '{ + "sql": "SELECT id, value FROM test_data WHERE value = :value ORDER BY id DESC", + "properties": { + "value": "alpha" + } + }' +``` + +For mutations, use `RETURNING` if you want rows back. Otherwise the statement still runs and `rows` is empty: + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/database/execute \ + -H 'Content-Type: application/json' \ + -d '{ + "sql": "INSERT INTO test_data (value, created_at) VALUES (?, ?) RETURNING id, value", + "args": ["beta", 1706000000000] + }' +``` + +For workflow-enabled actors, `history` is a JSON object with `nameRegistry`, `entries`, and `entryMetadata`. Step outputs, loop state, and message payloads are decoded from CBOR into normal JSON values. + +#### Replay Workflow From Step + +Reset a workflow to a specific step and restart execution immediately. Omitting `entryId` replays the workflow from the beginning. + +If the workflow is still running when you call replay, the endpoint rejects the request with `409 Conflict` and an `actor/workflow_in_flight` error instead of cancelling the live run for you. + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/workflow/replay \ + -H 'Content-Type: application/json' \ + -d '{"entryId":"workflow-step-id"}' +``` + +Returns the same JSON shape as `/inspector/workflow-history`: + +```json +{ + "history": { + "nameRegistry": ["step-one", "step-two"], + "entries": [], + "entryMetadata": {} + }, + "isWorkflowEnabled": true +} +``` + +While a workflow is in flight, the response shape is: + +```json +{ + "group": "actor", + "code": "workflow_in_flight", + "message": "Workflow replay is unavailable while the workflow is currently in flight.", + "metadata": null +} +``` + +#### Summary + +Get a full snapshot of the actor in a single request: + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/summary +``` + +Returns: + +```json +{ + "state": { "count": 42 }, + "connections": [], + "rpcs": ["increment", "getCount"], + "queueSize": 0, + "isStateEnabled": true, + "isDatabaseEnabled": false, + "isWorkflowEnabled": false, + "workflowHistory": null +} +``` + +When workflow history is present in `/inspector/summary`, `workflowHistory` is returned as the same decoded JSON shape as `/inspector/workflow-history`. + +### Polling + +Inspector endpoints are safe to poll. For live monitoring, poll at 1-5 second intervals. The `/inspector/summary` endpoint is useful for periodic snapshots since it returns all data in a single request. + +## OpenAPI Spec + +An OpenAPI specification covering many of the management and actor endpoints is available: + +- In the repository at [`rivetkit-openapi/openapi.json`](https://github.com/rivet-dev/rivet/tree/main/rivetkit-openapi) +- Served at `/doc` on the manager when running locally + +The checked-in spec does not yet list every endpoint documented on this page (for example the actor metadata and queue routes and the inspector database routes), so treat this page as the authoritative reference where they differ. + +_Source doc path: /docs/actors/debugging_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/design-patterns.md b/.agents/skills/ai-agent-workspace/reference/actors/design-patterns.md new file mode 100644 index 0000000..ba75783 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/design-patterns.md @@ -0,0 +1,616 @@ +# Design Patterns + +> Source: `src/content/docs/actors/design-patterns.mdx` +> Canonical URL: https://rivet.dev/docs/actors/design-patterns +> Description: Common patterns and anti-patterns for building scalable actor systems. + +--- +## How Actors Scale + +Actors are inherently scalable because of how they're designed: + +- **Isolated state:** Each actor manages its own private data. No shared state means no conflicts and no locks, so actors run concurrently without coordination. +- **Actor-to-actor communication:** Actors interact through [actions](/docs/actors/actions) and [events](/docs/actors/events), so they don't need to coordinate access to shared data. This makes it easy to distribute them across machines. +- **Small, focused units:** Each actor handles a limited scope (a single user, document, or chat room), so load naturally spreads across many actors rather than concentrating in one place. +- **Horizontal scaling:** Adding more machines automatically distributes actors across them. + +These properties form the foundation for the patterns described below. + +## Actor Per Entity + +The core pattern is creating one actor per entity in your system. Each actor represents a single user, document, chat room, or other distinct object. This keeps actors small, independent, and easy to scale. + +**Good examples** + +- `User`: Manages user profile, preferences, and authentication +- `Document`: Handles document content, metadata, and versioning +- `ChatRoom`: Manages participants and message history + +**Bad examples** + +- `Application`: Too broad, handles everything +- `DocumentWordCount`: Too granular, should be part of Document actor + +## Coordinator & Data Actors + +Actors scale by splitting state into isolated entities. However, it's common to need to track and coordinate actors in a central place. This is where coordinator actors come in. + +**Data actors** handle the main logic in your application. Examples: chat rooms, user sessions, game lobbies. + +**Coordinator actors** track other actors. Think of them as an index of data actors. Examples: a list of chat rooms, a list of active users, a list of game lobbies. + +**Example: Chat Room Coordinator** + +### Actor + +```ts +import { actor, setup } from "rivetkit"; + +// Data actor: handles messages and connections +const chatRoom = actor({ + state: { messages: [] as { sender: string; text: string }[] }, + actions: { + sendMessage: (c, sender: string, text: string) => { + const message = { sender, text }; + c.state.messages.push(message); + c.broadcast("newMessage", message); + return message; + }, + getHistory: (c) => c.state.messages, + }, +}); + +// Coordinator: indexes chat rooms +const chatRoomList = actor({ + state: { chatRoomIds: [] as string[] }, + actions: { + createChatRoom: async (c, name: string) => { + const client = c.client(); + // Create the chat room actor and get its ID + const handle = await client.chatRoom.create([name]); + const actorId = await handle.resolve(); + // Track it in the list + c.state.chatRoomIds.push(actorId); + return actorId; + }, + listChatRooms: (c) => c.state.chatRoomIds, + }, +}); + +const registry = setup({ + use: { chatRoom, chatRoomList }, +}); +``` + +### Client + +```ts +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +const chatRoom = actor({ + state: { messages: [] as { sender: string; text: string }[] }, + actions: { + sendMessage: (c, sender: string, text: string) => { + const message = { sender, text }; + c.state.messages.push(message); + return message; + }, + getHistory: (c) => c.state.messages, + }, +}); + +const chatRoomList = actor({ + state: { chatRoomIds: [] as string[] }, + actions: { + createChatRoom: async (c, name: string) => "room-id", + listChatRooms: (c) => c.state.chatRoomIds, + }, +}); + +const registry = setup({ use: { chatRoom, chatRoomList } }); +const client = createClient("http://localhost:6420"); + +// Create a new chat room via coordinator +const coordinator = client.chatRoomList.getOrCreate(["main"]); +const actorId = await coordinator.createChatRoom("general"); + +// Get list of all chat rooms +const chatRoomIds = await coordinator.listChatRooms(); + +// Connect to a chat room using its ID +const chatRoomHandle = client.chatRoom.getForId(actorId); +await chatRoomHandle.sendMessage("alice", "Hello!"); +const history = await chatRoomHandle.getHistory(); +``` + +## Sharding + +Sharding splits a single actor's workload across multiple actors based on a key. Use this when one actor can't handle all the load or data for an entity. + +**How it works:** +- Partition data using a shard key (user ID, region, time bucket, or random) +- Requests are routed to shards based on the key +- Shards operate independently without coordination + +**Example: Sharding by Time** + +### Actor + +```ts +import { actor, setup } from "rivetkit"; + +interface Event { + type: string; + url: string; +} + +const hourlyAnalytics = actor({ + state: { events: [] as Event[] }, + actions: { + trackEvent: (c, event: Event) => { + c.state.events.push(event); + }, + getEvents: (c) => c.state.events, + }, +}); + +export const registry = setup({ + use: { hourlyAnalytics }, +}); +``` + +### Client + +```ts +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +interface Event { + type: string; + url: string; +} + +const hourlyAnalytics = actor({ + state: { events: [] as Event[] }, + actions: { + trackEvent: (c, event: Event) => { + c.state.events.push(event); + }, + }, +}); + +const registry = setup({ use: { hourlyAnalytics } }); +const client = createClient("http://localhost:6420"); + +// Shard by hour: hourlyAnalytics:2024-01-15T00, hourlyAnalytics:2024-01-15T01 +const shardKey = new Date().toISOString().slice(0, 13); // "2024-01-15T00" +const analytics = client.hourlyAnalytics.getOrCreate([shardKey]); +await analytics.trackEvent({ type: "page_view", url: "/home" }); +``` + +**Example: Random Sharding** + +### Actor + +```ts +import { actor, setup } from "rivetkit"; + +const rateLimiter = actor({ + state: { requests: {} as Record }, + actions: { + checkLimit: (c, userId: string, limit: number) => { + const count = c.state.requests[userId] ?? 0; + if (count >= limit) return false; + c.state.requests[userId] = count + 1; + return true; + }, + }, +}); + +export const registry = setup({ + use: { rateLimiter }, +}); +``` + +### Client + +```ts +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +const rateLimiter = actor({ + state: { requests: {} as Record }, + actions: { + checkLimit: (c, userId: string, limit: number) => { + const count = c.state.requests[userId] ?? 0; + if (count >= limit) return false; + c.state.requests[userId] = count + 1; + return true; + }, + }, +}); + +const registry = setup({ use: { rateLimiter } }); +const client = createClient("http://localhost:6420"); + +// Shard randomly: rateLimiter:shard-0, rateLimiter:shard-1, rateLimiter:shard-2 +const shardKey = `shard-${Math.floor(Math.random() * 3)}`; +const limiter = client.rateLimiter.getOrCreate([shardKey]); +const allowed = await limiter.checkLimit("user-123", 100); +``` + +Choose shard keys that distribute load evenly. Note that cross-shard queries require coordination. + +## Fan-In & Fan-Out + +Fan-in and fan-out are patterns for distributing work and aggregating results. + +**Fan-Out**: One actor spawns work across multiple actors. Use for parallel processing or broadcasting updates. + +**Fan-In**: Multiple actors send results to one aggregator. Use for collecting results or reducing data. + +**Example: Map-Reduce** + +### Actor + +```ts +import { actor, setup } from "rivetkit"; + +interface Task { + id: string; + data: string; +} + +interface Result { + taskId: string; + output: string; +} + +// Coordinator fans out tasks, then fans in results +const coordinator = actor({ + state: { results: [] as Result[] }, + actions: { + // Fan-out: distribute work in parallel + startJob: async (c, tasks: Task[]) => { + const client = c.client(); + await Promise.all( + tasks.map(task => client.worker.getOrCreate(task.id).process(task)) + ); + }, + // Fan-in: collect results + reportResult: (c, result: Result) => { + c.state.results.push(result); + }, + getResults: (c) => c.state.results, + }, +}); + +const worker = actor({ + state: {}, + actions: { + process: async (c, task: Task) => { + const result = { taskId: task.id, output: `Processed ${task.data}` }; + const client = c.client(); + await client.coordinator.getOrCreate("main").reportResult(result); + }, + }, +}); + +export const registry = setup({ + use: { coordinator, worker }, +}); +``` + +### Client + +```ts +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +interface Task { + id: string; + data: string; +} + +interface Result { + taskId: string; + output: string; +} + +const coordinator = actor({ + state: { results: [] as Result[] }, + actions: { + startJob: async (c, tasks: Task[]) => {}, + reportResult: (c, result: Result) => { c.state.results.push(result); }, + getResults: (c) => c.state.results, + }, +}); + +const worker = actor({ + state: {}, + actions: { + process: async (c, task: Task) => {}, + }, +}); + +const registry = setup({ use: { coordinator, worker } }); +const client = createClient("http://localhost:6420"); + +const coordinatorHandle = client.coordinator.getOrCreate(["main"]); + +// Start a job with multiple tasks +await coordinatorHandle.startJob([ + { id: "task-1", data: "..." }, + { id: "task-2", data: "..." }, + { id: "task-3", data: "..." }, +]); + +// Results are collected as workers report back +const results = await coordinatorHandle.getResults(); +``` + +## Integrating With External Databases & APIs + +Actors can integrate with external resources like databases or external APIs. + +### Loading State + +Load external data during actor initialization using `createVars`. This keeps your actor's persisted state clean while caching expensive lookups. + +Use this when: + +- Fetching user profiles, configs, or permissions from a database +- Loading data that changes externally and shouldn't be persisted +- Caching expensive API calls or computations + +**Example: Loading User Profile** + +### Actor + +```ts +import { actor, setup } from "rivetkit"; + +interface User { + id: string; + email: string; + name: string; +} + +// Mock database interface for demonstration +const db = { + users: { + findById: async (id: string): Promise => ({ id, email: "user@example.com", name: "User" }), + update: async (id: string, data: Partial) => {}, + }, +}; + +const userSession = actor({ + state: { requestCount: 0 }, + + // createVars runs on every wake (after restarts, crashes, or sleep), so + // external data stays fresh. + createVars: async (c): Promise<{ user: User }> => { + // Load from database on every wake + const user = await db.users.findById(c.key.join("-")); + return { user }; + }, + + actions: { + getProfile: (c) => { + c.state.requestCount++; + return c.vars.user; + }, + updateEmail: async (c, email: string) => { + c.state.requestCount++; + await db.users.update(c.key.join("-"), { email }); + // Refresh cached data + c.vars.user = await db.users.findById(c.key.join("-")); + }, + }, +}); + +const registry = setup({ + use: { userSession }, +}); +``` + +### Client + +```ts +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +interface User { + id: string; + email: string; + name: string; +} + +const userSession = actor({ + state: { requestCount: 0 }, + createVars: () => ({ user: null as User | null }), + actions: { + getProfile: (c) => c.vars.user, + updateEmail: async (c, email: string) => {}, + }, +}); + +const registry = setup({ use: { userSession } }); +const client = createClient("http://localhost:6420"); + +const session = client.userSession.getOrCreate(["user-123"]); + +// Get profile (loaded from database on actor wake) +const profile = await session.getProfile(); + +// Update email (writes to database and refreshes cache) +await session.updateEmail("alice@example.com"); +``` + +### Syncing State Changes + +Use `onStateChange` to automatically sync actor state changes to external resources. This hook runs after state changes are flushed, which is coalesced to once per event loop tick rather than once per individual field mutation. + +Use this when: + +- You need to mirror actor state in an external database +- Triggering external side effects when state changes +- Keeping external systems in sync with actor state + +**Example: Syncing to Database** + +### Actor + +```ts +import { actor, setup } from "rivetkit"; + +// Mock database interface for demonstration +const db = { + users: { + insert: async (data: { id: string; email: string; createdAt: number }) => {}, + update: async (id: string, data: { email: string; lastActive: number }) => {}, + }, +}; + +const userActor = actor({ + state: { + email: "", + lastActive: 0, + }, + + onCreate: async (c, input: { email: string }) => { + // Insert into database on actor creation + await db.users.insert({ + id: c.key.join("-"), + email: input.email, + createdAt: Date.now(), + }); + }, + + onStateChange: async (c, newState) => { + // Sync any state changes to database + await db.users.update(c.key.join("-"), { + email: newState.email, + lastActive: newState.lastActive, + }); + }, + + actions: { + updateEmail: (c, email: string) => { + c.state.email = email; + c.state.lastActive = Date.now(); + }, + getUser: (c) => ({ + email: c.state.email, + lastActive: c.state.lastActive, + }), + }, +}); + +const registry = setup({ + use: { userActor }, +}); +``` + +### Client + +```ts +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +const userActor = actor({ + state: { email: "", lastActive: 0 }, + actions: { + updateEmail: (c, email: string) => { + c.state.email = email; + c.state.lastActive = Date.now(); + }, + getUser: (c) => ({ + email: c.state.email, + lastActive: c.state.lastActive, + }), + }, +}); + +const registry = setup({ use: { userActor } }); +const client = createClient("http://localhost:6420"); + +const user = await client.userActor.create(["user-123"], { + input: { email: "alice@example.com" }, +}); + +// Updates state and triggers onStateChange +await user.updateEmail("alice2@example.com"); + +const userData = await user.getUser(); +``` + +`onStateChange` is called once per flush with the final coalesced state, ensuring external resources stay in sync. In the `updateEmail` example above, the two synchronous assignments produce a single `onStateChange` call. + +Do not mutate `c.state` inside `onStateChange`; re-entrant state mutation is rejected. + +## Anti-Patterns + +### "God" Actor + +Avoid creating a single actor that handles everything. This defeats the purpose of the actor model and creates a bottleneck. + +**Problem:** +```ts +import { actor } from "rivetkit"; + +// Bad: one actor doing everything +const app = actor({ + state: { users: {}, orders: {}, inventory: {}, analytics: {} }, + actions: { + createUser: (c, user) => { /* ... */ }, + processOrder: (c, order) => { /* ... */ }, + updateInventory: (c, item) => { /* ... */ }, + trackEvent: (c, event) => { /* ... */ }, + }, +}); +``` + +**Solution:** Split into focused actors per entity (User, Order, Inventory, Analytics). + +### Actor-Per-Request + +Actors are designed to maintain state across multiple requests. Creating a new actor for each request wastes resources and loses the benefits of persistent state. + +**Problem:** +```ts +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; +import { Hono } from "hono"; + +const processor = actor({ + state: {}, + actions: { + process: (c, body: unknown) => ({ processed: true }), + destroySelf: (c) => c.destroy(), + }, +}); + +const registry = setup({ use: { processor } }); +const client = createClient("http://localhost:6420"); +const app = new Hono(); + +// Bad: creating an actor for each API request +app.post("/process", async (c) => { + const actorHandle = client.processor.getOrCreate([crypto.randomUUID()]); + const result = await actorHandle.process(await c.req.json()); + await actorHandle.destroySelf(); + return c.json(result); +}); +``` + +**Solution:** Use actors for entities that persist (users, sessions, documents), not for one-off operations. For stateless request handling, use regular functions. + +## API Reference + +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for pattern examples +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - Context usage patterns +- [`ActionContext`](/typedoc/interfaces/rivetkit.mod.ActionContext.html) - Action patterns + +_Source doc path: /docs/actors/design-patterns_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/destroy.md b/.agents/skills/ai-agent-workspace/reference/actors/destroy.md new file mode 100644 index 0000000..951f865 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/destroy.md @@ -0,0 +1,123 @@ +# Destroying Actors + +> Source: `src/content/docs/actors/destroy.mdx` +> Canonical URL: https://rivet.dev/docs/actors/destroy +> Description: Actors can be permanently destroyed. Common use cases include: + +--- +- User account deletion +- Ending a user session +- Closing a room or game +- Cleaning up temporary resources +- GDPR/compliance data removal + +Actors sleep when idle, so destruction is only needed to permanently remove data — not to save compute. + +## Destroying An Actor + +### Destroy via Action + +To destroy an actor, use `c.destroy()` like this: + +```typescript +import { actor } from "rivetkit"; + +interface UserInput { + email: string; + name: string; +} + +const userActor = actor({ + createState: (c, input: UserInput) => ({ + email: input.email, + name: input.name, + }), + actions: { + deleteAccount: (c) => { + c.destroy(); + }, + }, +}); +``` + +### Destroy via HTTP + +Send a DELETE request to destroy an actor. This requires a token for authentication: + +- **Rivet Cloud**: Use the service key (`sk_*`) from your `RIVET_ENDPOINT` URL. Find this in the dashboard under **Settings > Advanced > Backend Configuration** (e.g. the `sk_...` portion of `https://default:sk_abc123@api.rivet.dev`). +- **Self-hosted**: Use an admin token. + +```typescript +const actorId = "your-actor-id"; +const namespace = "default"; +const token = "your-token"; + +await fetch(`https://api.rivet.dev/actors/${actorId}?namespace=${namespace}`, { + method: "DELETE", + headers: { + Authorization: `Bearer ${token}`, + }, +}); +``` + +```bash +curl -X DELETE "https://api.rivet.dev/actors/{actorId}?namespace={namespace}" \ + -H "Authorization: Bearer {token}" +``` + +To find the actor ID, you can list actors first: + +```bash +curl "https://api.rivet.dev/actors?namespace={namespace}" \ + -H "Authorization: Bearer {token}" +``` + +### Destroy via Dashboard + +To destroy an actor via the dashboard, navigate to the actor and press the red "X" in the top right. + +## Lifecycle Hook + +Once destroyed, the `onDestroy` hook will be called. This can be used to clean up resources related to the actor. For example: + +```typescript +import { actor } from "rivetkit"; + +interface UserState { + email: string; + name: string; +} + +// Example email service interface +const emailService = { + send: async (options: { from: string; to: string; subject: string; text: string }) => {}, +}; + +const userActor = actor({ + state: { email: "", name: "" } as UserState, + onDestroy: async (c) => { + await emailService.send({ + from: "noreply@example.com", + to: c.state.email, + subject: "Account Deleted", + text: `Goodbye ${c.state.name}, your account has been deleted.`, + }); + }, + actions: { + deleteAccount: (c) => { + c.destroy(); + }, + }, +}); +``` + +## Accessing Actor After Destroy + +Once an actor is destroyed, any subsequent requests to it will fail with an `actor.not_found` error (`{ group: "actor", code: "not_found" }`). The actor's state is permanently deleted. + +## API Reference + +- [`ActorHandle`](/typedoc/types/rivetkit.client_mod.ActorHandle.html) - Has destroy methods +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - Context during destruction + +_Source doc path: /docs/actors/destroy_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/errors.md b/.agents/skills/ai-agent-workspace/reference/actors/errors.md new file mode 100644 index 0000000..05d89c8 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/errors.md @@ -0,0 +1,434 @@ +# Errors + +> Source: `src/content/docs/actors/errors.mdx` +> Canonical URL: https://rivet.dev/docs/actors/errors +> Description: Rivet provides robust error handling with security built in by default. Errors are handled differently based on whether they should be exposed to clients or kept private. + +--- +There are two types of errors: + +- **UserError**: Thrown from actors and safely returned to clients with full details +- **Internal errors**: All other errors that are converted to a generic error message for security + +## Throwing and Catching Errors + +`UserError` lets you throw custom errors that will be safely returned to the client. + +Throw a `UserError` with just a message: + +### Actor + +```typescript +import { actor, UserError } from "rivetkit"; + +const user = actor({ + state: { username: "" }, + actions: { + updateUsername: (c, username: string) => { + // Validate username + if (username.length > 32) { + throw new UserError("Username is too long"); + } + + // Update username + c.state.username = username; + } + } +}); +``` + +### Client (Connection) + +```typescript +import { actor, setup } from "rivetkit"; +import { createClient, ActorError } from "rivetkit/client"; + +const user = actor({ + state: { username: "" }, + actions: { + updateUsername: (c, username: string) => { + if (username.length > 32) throw new Error("Username is too long"); + c.state.username = username; + } + } +}); + +const registry = setup({ use: { user } }); +const client = createClient("http://localhost:6420"); +const conn = client.user.getOrCreate([]).connect(); + +try { + await conn.updateUsername("extremely_long_username_that_exceeds_the_limit"); +} catch (error) { + if (error instanceof ActorError) { + console.log(error.message); // "Username is too long" + } +} +``` + +### Client (Stateless) + +```typescript +import { actor, setup } from "rivetkit"; +import { createClient, ActorError } from "rivetkit/client"; + +const user = actor({ + state: { username: "" }, + actions: { + updateUsername: (c, username: string) => { + if (username.length > 32) throw new Error("Username is too long"); + c.state.username = username; + } + } +}); + +const registry = setup({ use: { user } }); +const client = createClient("http://localhost:6420"); +const userActor = client.user.getOrCreate([]); + +try { + await userActor.updateUsername("extremely_long_username_that_exceeds_the_limit"); +} catch (error) { + if (error instanceof ActorError) { + console.log(error.message); // "Username is too long" + } +} +``` + +## Error Codes + +Use error codes for explicit error matching in try-catch blocks: + +### Actor + +```typescript +import { actor, UserError } from "rivetkit"; + +const user = actor({ + state: { username: "" }, + actions: { + updateUsername: (c, username: string) => { + if (username.length < 3) { + throw new UserError("Username is too short", { + code: "username_too_short" + }); + } + + if (username.length > 32) { + throw new UserError("Username is too long", { + code: "username_too_long" + }); + } + + // Update username + c.state.username = username; + } + } +}); +``` + +### Client (Connection) + +```typescript +import { actor, setup } from "rivetkit"; +import { createClient, ActorError } from "rivetkit/client"; + +const user = actor({ + state: { username: "" }, + actions: { + updateUsername: (c, username: string) => { c.state.username = username; } + } +}); + +const registry = setup({ use: { user } }); +const client = createClient("http://localhost:6420"); +const conn = client.user.getOrCreate([]).connect(); + +try { + await conn.updateUsername("ab"); +} catch (error) { + if (error instanceof ActorError) { + if (error.code === "username_too_short") { + console.log("Please choose a longer username"); + } else if (error.code === "username_too_long") { + console.log("Please choose a shorter username"); + } + } +} +``` + +### Client (Stateless) + +```typescript +import { actor, setup } from "rivetkit"; +import { createClient, ActorError } from "rivetkit/client"; + +const user = actor({ + state: { username: "" }, + actions: { + updateUsername: (c, username: string) => { c.state.username = username; } + } +}); + +const registry = setup({ use: { user } }); +const client = createClient("http://localhost:6420"); +const userActor = client.user.getOrCreate([]); + +try { + await userActor.updateUsername("ab"); +} catch (error) { + if (error instanceof ActorError) { + if (error.code === "username_too_short") { + console.log("Please choose a longer username"); + } else if (error.code === "username_too_long") { + console.log("Please choose a shorter username"); + } + } +} +``` + +## Errors With Metadata + +Include metadata to provide additional context for rich error handling: + +### Actor + +```typescript +import { actor, UserError } from "rivetkit"; + +const api = actor({ + state: { requestCount: 0, lastReset: Date.now() }, + actions: { + makeRequest: (c) => { + c.state.requestCount++; + + const limit = 100; + if (c.state.requestCount > limit) { + const resetAt = c.state.lastReset + 60_000; // Reset after 1 minute + + throw new UserError("Rate limit exceeded", { + code: "rate_limited", + metadata: { + limit: limit, + resetAt: resetAt, + retryAfter: Math.ceil((resetAt - Date.now()) / 1000) + } + }); + } + + // Rest of request logic... + } + } +}); +``` + +### Client (Connection) + +```typescript +import { actor, setup } from "rivetkit"; +import { createClient, ActorError } from "rivetkit/client"; + +const api = actor({ + state: { requestCount: 0 }, + actions: { makeRequest: (c) => {} } +}); + +const registry = setup({ use: { api } }); +const client = createClient("http://localhost:6420"); +const conn = client.api.getOrCreate([]).connect(); + +try { + await conn.makeRequest(); +} catch (error) { + if (error instanceof ActorError) { + console.log(error.message); // "Rate limit exceeded" + console.log(error.code); // "rate_limited" + console.log(error.metadata); // { limit: 100, resetAt: 1234567890, retryAfter: 45 } + + if (error.code === "rate_limited") { + const metadata = error.metadata as { retryAfter: number }; + console.log(`Rate limit hit. Try again in ${metadata.retryAfter} seconds`); + } + } +} +``` + +### Client (Stateless) + +```typescript +import { actor, setup } from "rivetkit"; +import { createClient, ActorError } from "rivetkit/client"; + +const api = actor({ + state: { requestCount: 0 }, + actions: { makeRequest: (c) => {} } +}); + +const registry = setup({ use: { api } }); +const client = createClient("http://localhost:6420"); +const apiActor = client.api.getOrCreate([]); + +try { + await apiActor.makeRequest(); +} catch (error) { + if (error instanceof ActorError) { + console.log(error.message); // "Rate limit exceeded" + console.log(error.code); // "rate_limited" + console.log(error.metadata); // { limit: 100, resetAt: 1234567890, retryAfter: 45 } + + if (error.code === "rate_limited") { + const metadata = error.metadata as { retryAfter: number }; + console.log(`Rate limit hit. Try again in ${metadata.retryAfter} seconds`); + } + } +} +``` + +## Internal Errors + +All errors that are not UserError instances are automatically converted to a generic "internal error" response. This prevents accidentally leaking sensitive information like stack traces, database details, or internal system information. + +### Actor + +```typescript +import { actor } from "rivetkit"; + +const payment = actor({ + state: { transactions: [] }, + actions: { + processPayment: async (c, amount: number) => { + // This will throw a regular Error (not UserError) + const result = await fetch("https://payment-api.example.com/charge", { + method: "POST", + body: JSON.stringify({ amount }) + }); + + if (!result.ok) { + // This internal error will be hidden from the client + throw new Error(`Payment API returned ${result.status}: ${await result.text()}`); + } + + // Rest of payment logic... + } + } +}); +``` + +### Client (Connection) + +```typescript +import { actor, setup } from "rivetkit"; +import { createClient, ActorError } from "rivetkit/client"; + +interface Transaction { + amount: number; + status: string; +} + +const payment = actor({ + state: { transactions: [] as Transaction[] }, + actions: { processPayment: async (c, amount: number) => {} } +}); + +const registry = setup({ use: { payment } }); +const client = createClient("http://localhost:6420"); +const conn = client.payment.getOrCreate([]).connect(); + +try { + await conn.processPayment(100); +} catch (error) { + if (error instanceof ActorError) { + console.log(error.code); // "internal_error" + console.log(error.message); // "An internal error occurred" + + // Original error details are NOT exposed to the client + // Check your server logs to see the actual error message + } +} +``` + +### Client (Stateless) + +```typescript +import { actor, setup } from "rivetkit"; +import { createClient, ActorError } from "rivetkit/client"; + +interface Transaction { + amount: number; + status: string; +} + +const payment = actor({ + state: { transactions: [] as Transaction[] }, + actions: { processPayment: async (c, amount: number) => {} } +}); + +const registry = setup({ use: { payment } }); +const client = createClient("http://localhost:6420"); +const paymentActor = client.payment.getOrCreate([]); + +try { + await paymentActor.processPayment(100); +} catch (error) { + if (error instanceof ActorError) { + console.log(error.code); // "internal_error" + console.log(error.message); // "An internal error occurred" + + // Original error details are NOT exposed to the client + // Check your server logs to see the actual error message + } +} +``` + +### Server-Side Logging + +**All internal errors are logged server-side with full details.** When an internal error occurs, the complete error message, stack trace, and context are written to your server logs. This is where you should look first when debugging internal errors in production. + +The client receives only a generic "Internal error" message for security, but you can find the full error details in your server logs including: + +- Complete error message +- Stack trace +- Request context (actor ID, action name, connection ID, etc.) +- Timestamp + +**Always check your server logs to see the actual error details when debugging internal errors.** + +### Exposing Errors to Clients (Development Only) + +**Warning:** Only enable error exposure in development environments. In production, this will leak sensitive internal details to clients. + +For faster debugging during development, you can expose internal error details to clients by setting `RIVET_EXPOSE_ERRORS=1`. + +With error exposure enabled, clients will see the full error message instead of the generic "Internal error" response: + +```typescript +import { actor, setup } from "rivetkit"; +import { createClient, ActorError } from "rivetkit/client"; + +const payment = actor({ + state: {}, + actions: { processPayment: async (c, amount: number) => {} } +}); + +const registry = setup({ use: { payment } }); +const client = createClient("http://localhost:6420"); +const paymentActor = client.payment.getOrCreate([]); + +// With RIVET_EXPOSE_ERRORS=1 +try { + await paymentActor.processPayment(100); +} catch (error) { + if (error instanceof ActorError) { + console.log(error.message); + // "Payment API returned 402: Insufficient funds" + // Instead of: "An internal error occurred" + } +} +``` + +## API Reference + +- [`UserError`](/typedoc/classes/rivetkit.actor_errors.UserError.html) - User-facing error class +- [`ActorError`](/typedoc/classes/rivetkit.client_mod.ActorError.html) - Errors received by the client + +_Source doc path: /docs/actors/errors_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/events.md b/.agents/skills/ai-agent-workspace/reference/actors/events.md new file mode 100644 index 0000000..367d702 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/events.md @@ -0,0 +1,390 @@ +# Realtime + +> Source: `src/content/docs/actors/events.mdx` +> Canonical URL: https://rivet.dev/docs/actors/events +> Description: Events enable realtime communication from actors to clients. While clients use actions to send data to actors, events allow actors to push updates to connected clients instantly. + +--- +Events can be sent to clients connected using `.connect()`. They have no effect on [low-level WebSocket connections](/docs/actors/websocket-handler). + +For worked realtime patterns, see the cookbook: [Live Cursors and Presence](/cookbook/live-cursors/) and [Chat Room](/cookbook/chat-room/). + +## Publishing Events from Actors + +### Broadcasting to All Clients + +Define event names and payload types with `events` and `event()`, then use `c.broadcast(eventName, ...args)` to send events to all connected clients: + +```typescript +import { actor, event } from "rivetkit"; + +type Message = { + id: string; + userId: string; + text: string; + timestamp: number; +}; + +const chatRoom = actor({ + state: { + messages: [] as Message[] + }, + + events: { + messageReceived: event() + }, + + actions: { + sendMessage: (c, userId: string, text: string) => { + const message = { + id: crypto.randomUUID(), + userId, + text, + timestamp: Date.now() + }; + + c.state.messages.push(message); + + // Broadcast to all connected clients + c.broadcast('messageReceived', message); + + return message; + }, + } +}); +``` + +### Sending to Specific Connections + +Send events to individual connections using `conn.send(eventName, ...args)`: + +```typescript +import { actor, event } from "rivetkit"; + +interface ConnState { + playerId: string; + role: string; +} + +const gameRoom = actor({ + state: { + players: {} as Record + }, + + events: { + privateMessage: event<{ + from?: string; + message: string; + timestamp: number; + }>() + }, + + createConnState: (c, params: { playerId: string, role?: string }): ConnState => ({ + playerId: params.playerId, + role: params.role || "player" + }), + + actions: { + sendPrivateMessage: (c, targetPlayerId: string, message: string) => { + // Find the target player's connection + let targetConn = null; + for (const conn of c.conns.values()) { + if (conn.state.playerId === targetPlayerId) { + targetConn = conn; + break; + } + } + + if (targetConn) { + targetConn.send('privateMessage', { + from: c.conn?.state.playerId, + message, + timestamp: Date.now() + }); + } else { + throw new Error("Player not found or not connected"); + } + } + } +}); +``` + +Send events to all connections except the sender: + +```typescript +import { actor, event } from "rivetkit"; + +interface ConnState { + playerId: string; + role: string; +} + +const gameRoom = actor({ + state: { + players: {} as Record + }, + + events: { + playerMoved: event<{ + playerId: string; + position: { x: number; y: number }; + }>() + }, + + createConnState: (c, params: { playerId: string, role?: string }): ConnState => ({ + playerId: params.playerId, + role: params.role || "player" + }), + + actions: { + updatePlayerPosition: (c, position: {x: number, y: number}) => { + const playerId = c.conn?.state.playerId; + if (!playerId) return; + + if (c.state.players[playerId]) { + c.state.players[playerId].position = position; + + // Send position update to all OTHER players + for (const conn of c.conns.values()) { + if (conn.state.playerId !== playerId) { + conn.send('playerMoved', { playerId, position }); + } + } + } + } + } +}); +``` + +## Subscribing to Events from Clients + +Clients must establish a connection to receive events from actors. Use `.connect()` to create a persistent connection, then listen for events. + +### Basic Event Subscription + +Use `connection.on(eventName, callback)` to listen for events: + +```typescript TypeScript +import { actor, event, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +type Message = { id: string; userId: string; text: string }; + +// Define the actor +const chatRoom = actor({ + state: { messages: [] as Message[] }, + events: { + messageReceived: event() + }, + actions: { + sendMessage: (c, userId: string, text: string) => { + const message = { id: crypto.randomUUID(), userId, text }; + c.state.messages.push(message); + c.broadcast('messageReceived', message); + return message; + } + } +}); + +const registry = setup({ use: { chatRoom } }); +const client = createClient("http://localhost:6420"); + +// Helper function for demonstration +function displayMessage(message: Message) { + console.log("Display:", message); +} + +// Get actor handle and establish connection +const chatRoomHandle = client.chatRoom.getOrCreate(["general"]); +const connection = chatRoomHandle.connect(); + +// Listen for events +connection.on('messageReceived', (message: Message) => { + console.log(`${message.userId}: ${message.text}`); + displayMessage(message); +}); + +// Call actions through the connection +await connection.sendMessage("user-123", "Hello everyone!"); +``` + +```tsx React @nocheck +import { useState } from "react"; +import { useActor } from "./rivetkit"; + +function ChatRoom() { + const [messages, setMessages] = useState>([]); + + const chatRoom = useActor({ + name: "chatRoom", + key: ["general"] + }); + + // Listen for events + chatRoom.useEvent("messageReceived", (message) => { + setMessages(prev => [...prev, message]); + }); + + // ...rest of component... +} +``` + +### One-time Event Listeners + +Use `connection.once(eventName, callback)` for events that should only trigger once: + +```typescript TypeScript +import { actor, event, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +const gameRoom = actor({ + state: { started: false }, + events: { + gameStarted: event<[]>() + }, + actions: { + startGame: (c) => { + c.state.started = true; + c.broadcast('gameStarted'); + } + } +}); + +const registry = setup({ use: { gameRoom } }); +const client = createClient("http://localhost:6420"); + +function showGameInterface() { + console.log("Showing game interface"); +} + +const gameRoomHandle = client.gameRoom.getOrCreate(["room-456"]); +const connection = gameRoomHandle.connect(); + +// Listen for game start (only once) +connection.once('gameStarted', () => { + console.log('Game has started!'); + showGameInterface(); +}); +``` + +```tsx React @nocheck +import { useState, useEffect } from "react"; +import { useActor } from "./rivetkit"; + +function GameLobby() { + const [gameStarted, setGameStarted] = useState(false); + + const gameRoom = useActor({ + name: "gameRoom", + key: ["room-456"], + params: { + playerId: "player-789", + role: "player" + } + }); + + // Listen for game start (only once) + useEffect(() => { + if (!gameRoom.connection) return; + + const handleGameStart = () => { + console.log('Game has started!'); + setGameStarted(true); + }; + + gameRoom.connection.once('gameStarted', handleGameStart); + }, [gameRoom.connection]); + + // ...rest of component... +} +``` + +### Removing Event Listeners + +Use the callback returned from `.on()` to remove event listeners: + +```typescript TypeScript +import { actor, event, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +type Message = { text: string }; + +const chatRoom = actor({ + state: { messages: [] as string[] }, + events: { + messageReceived: event() + }, + actions: { + sendMessage: (c, text: string) => { + c.state.messages.push(text); + c.broadcast('messageReceived', { text }); + } + } +}); + +const registry = setup({ use: { chatRoom } }); +const client = createClient("http://localhost:6420"); +const connection = client.chatRoom.getOrCreate(["general"]).connect(); + +// Add listener +const unsubscribe = connection.on('messageReceived', (message) => { + console.log("Received:", message); +}); + +// Remove listener +unsubscribe(); +``` + +```tsx React @nocheck +import { useState, useEffect } from "react"; +import { useActor } from "./rivetkit"; + +function ConditionalListener() { + const [isListening, setIsListening] = useState(false); + const [messages, setMessages] = useState([]); + + const chatRoom = useActor({ + name: "chatRoom", + key: ["general"] + }); + + useEffect(() => { + if (!chatRoom.connection || !isListening) return; + + // Add listener + const unsubscribe = chatRoom.connection.on('messageReceived', (message) => { + setMessages(prev => [...prev, message.text]); + }); + + // Cleanup - remove listener when component unmounts or listening stops + return () => { + unsubscribe(); + }; + }, [chatRoom.connection, isListening]); + + // ...rest of component... +} +``` + +## Debugging + +- `GET /inspector/connections` shows active connections and connection metadata. +- Use this to confirm clients are connected before expecting broadcasts. +- `GET /inspector/summary` provides connections, RPCs, and queue size in one response. +- In non-dev mode, inspector endpoints require authorization. + +## More About Connections + +For more details on actor connections, including connection lifecycle, authentication, and advanced connection patterns, see the [Connections documentation](/docs/actors/connections). + +## API Reference + +- [`RivetEvent`](/typedoc/interfaces/rivetkit.mod.RivetEvent.html) - Base event interface +- [`RivetMessageEvent`](/typedoc/interfaces/rivetkit.mod.RivetMessageEvent.html) - Message event type +- [`RivetCloseEvent`](/typedoc/interfaces/rivetkit.mod.RivetCloseEvent.html) - Close event type +- [`UniversalEvent`](/typedoc/interfaces/rivetkit.mod.UniversalEvent.html) - Universal event type +- [`UniversalMessageEvent`](/typedoc/interfaces/rivetkit.mod.UniversalMessageEvent.html) - Universal message event +- [`UniversalErrorEvent`](/typedoc/interfaces/rivetkit.mod.UniversalErrorEvent.html) - Universal error event +- [`EventUnsubscribe`](/typedoc/types/rivetkit.client_mod.EventUnsubscribe.html) - Unsubscribe function type + +_Source doc path: /docs/actors/events_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/fetch-and-websocket-handler.md b/.agents/skills/ai-agent-workspace/reference/actors/fetch-and-websocket-handler.md new file mode 100644 index 0000000..b8b0509 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/fetch-and-websocket-handler.md @@ -0,0 +1,10 @@ +# Fetch and WebSocket Handler + +> Source: `src/content/docs/actors/fetch-and-websocket-handler.mdx` +> Canonical URL: https://rivet.dev/docs/actors/fetch-and-websocket-handler +> Description: These docs have moved to [Low-Level WebSocket Handler](/docs/actors/websocket-handler) and [Low-Level Request Handler](/docs/actors/request-handler). + +--- + + +_Source doc path: /docs/actors/fetch-and-websocket-handler_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/helper-types.md b/.agents/skills/ai-agent-workspace/reference/actors/helper-types.md new file mode 100644 index 0000000..55555c7 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/helper-types.md @@ -0,0 +1,10 @@ +# Helper Types + +> Source: `src/content/docs/actors/helper-types.mdx` +> Canonical URL: https://rivet.dev/docs/actors/helper-types +> Description: This page has moved to [Types](/docs/actors/types). + +--- + + +_Source doc path: /docs/actors/helper-types_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/http-api.md b/.agents/skills/ai-agent-workspace/reference/actors/http-api.md new file mode 100644 index 0000000..1d8d5be --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/http-api.md @@ -0,0 +1,10 @@ +# Vanilla HTTP API + +> Source: `src/content/docs/actors/http-api.mdx` +> Canonical URL: https://rivet.dev/docs/actors/http-api +> Description: Use the low-level HTTP handler to send and receive requests from actors. + +--- +TODO + +_Source doc path: /docs/actors/http-api_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/input.md b/.agents/skills/ai-agent-workspace/reference/actors/input.md new file mode 100644 index 0000000..ecc62dd --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/input.md @@ -0,0 +1,287 @@ +# Input Parameters + +> Source: `src/content/docs/actors/input.mdx` +> Canonical URL: https://rivet.dev/docs/actors/input +> Description: Pass initialization data to actors when creating instances + +--- +Actors can receive input parameters when created, allowing for flexible initialization and configuration. Input is passed during actor creation and is available in lifecycle hooks. + +## Passing Input to Actors + +Input is provided when creating actor instances using the `input` property: + +```typescript +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +interface GameInput { + gameMode: string; + maxPlayers: number; + difficulty?: string; +} + +const game = actor({ + createState: (c, input: GameInput) => ({ + gameMode: input.gameMode, + maxPlayers: input.maxPlayers, + difficulty: input.difficulty ?? "medium", + }), + actions: {} +}); + +const registry = setup({ use: { game } }); +const client = createClient("http://localhost:6420"); + +// Client side - create with input +const gameHandle = await client.game.create(["game-123"], { + input: { + gameMode: "tournament", + maxPlayers: 8, + difficulty: "hard", + } +}); + +// getOrCreate can also accept input (used only if creating) +const gameHandle2 = client.game.getOrCreate(["game-456"], { + createWithInput: { + gameMode: "casual", + maxPlayers: 4, + } +}); +``` + +## Accessing Input in Lifecycle Hooks + +Input is available as the second argument to the `createState` and `onCreate` lifecycle hooks: + +```typescript +import { actor } from "rivetkit"; + +interface ChatRoomInput { + roomName: string; + isPrivate: boolean; + maxUsers?: number; +} + +interface ChatRoomState { + name: string; + isPrivate: boolean; + maxUsers: number; + users: Record; + messages: string[]; +} + +// Mock function for demonstration +function setupPrivateRoomLogging(roomName: string) { + console.log(`Setting up logging for private room: ${roomName}`); +} + +const chatRoom = actor({ + createState: (c, input: ChatRoomInput): ChatRoomState => ({ + name: input?.roomName ?? "Unnamed Room", + isPrivate: input?.isPrivate ?? false, + maxUsers: input?.maxUsers ?? 50, + users: {}, + messages: [], + }), + + onCreate: (c, input: ChatRoomInput) => { + console.log(`Creating room: ${input.roomName}`); + + // Setup external services based on input + if (input.isPrivate) { + setupPrivateRoomLogging(input.roomName); + } + }, + + actions: { + // Input remains accessible in actions via initial state + getRoomInfo: (c) => ({ + name: c.state.name, + isPrivate: c.state.isPrivate, + maxUsers: c.state.maxUsers, + currentUsers: Object.keys(c.state.users).length, + }), + }, +}); +``` + +## Input Validation + +You can validate input parameters in the `createState` or `onCreate` hooks: + +```typescript +import { actor } from "rivetkit"; +import { z } from "zod"; + +const GameInputSchema = z.object({ + gameMode: z.enum(["casual", "tournament", "ranked"]), + maxPlayers: z.number().min(2).max(16), + difficulty: z.enum(["easy", "medium", "hard"]).optional(), +}); + +type GameInput = z.infer; + +interface GameState { + gameMode: string; + maxPlayers: number; + difficulty: string; + players: Record; + gameState: string; +} + +const game = actor({ + createState: (c, inputRaw: GameInput): GameState => { + // Validate input + const input = GameInputSchema.parse(inputRaw); + + return { + gameMode: input.gameMode, + maxPlayers: input.maxPlayers, + difficulty: input.difficulty ?? "medium", + players: {}, + gameState: "waiting", + }; + }, + + actions: { + // Actions can access the validated input via state + getGameInfo: (c) => ({ + gameMode: c.state.gameMode, + maxPlayers: c.state.maxPlayers, + difficulty: c.state.difficulty, + currentPlayers: Object.keys(c.state.players).length, + }), + }, +}); +``` + +## Input vs Connection Parameters + +Input parameters are different from connection parameters: + +- **Input**: + - Passed when creating the actor instance + - Use for actor-wide configuration + - Available in lifecycle hooks +- **Connection parameters**: + - Passed when connecting to an existing actor + - Used for connection-specific configuration + - Available in connection hooks + +```typescript +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +interface RoomInput { roomName: string; isPrivate: boolean; } + +const chatRoom = actor({ + createState: (c, input: RoomInput) => ({ name: input.roomName, isPrivate: input.isPrivate }), + createConnState: (c, params: { userId: string; displayName: string }) => ({ + userId: params.userId, + displayName: params.displayName, + }), + actions: {} +}); + +const registry = setup({ use: { chatRoom } }); +const client = createClient("http://localhost:6420"); + +// Actor creation with input +const room = await client.chatRoom.create(["room-123"], { + input: { + roomName: "General Discussion", + isPrivate: false, + }, +}); +``` + +## Input Best Practices + +### Use Type Safety + +Define input types to ensure type safety: + +```typescript +import { actor } from "rivetkit"; + +interface GameInput { + gameMode: "casual" | "tournament" | "ranked"; + maxPlayers: number; + difficulty?: "easy" | "medium" | "hard"; +} + +interface GameState { + gameMode: string; + maxPlayers: number; + difficulty: string; +} + +const game = actor({ + createState: (c, input: GameInput): GameState => ({ + gameMode: input.gameMode, + maxPlayers: input.maxPlayers, + difficulty: input.difficulty ?? "medium", + }), + + actions: { + // Actions are now type-safe + }, +}); +``` + +### Store Input in State + +Input is only available in `createState` and `onCreate` lifecycle hooks. If you need to access input data later (in actions, timers, or other hooks), store it in the actor's state during creation. This is the recommended pattern because input shapes can evolve over time, and persisting input in state ensures you always have access to the values the actor was created with: + +```typescript +import { actor } from "rivetkit"; + +interface GameInput { + gameMode: string; + maxPlayers: number; + difficulty?: string; +} + +interface GameConfig { + gameMode: string; + maxPlayers: number; + difficulty: string; +} + +interface GameState { + config: GameConfig; + players: Record; + gameState: string; +} + +const game = actor({ + createState: (c, input: GameInput): GameState => ({ + // Store input configuration in state + config: { + gameMode: input.gameMode, + maxPlayers: input.maxPlayers, + difficulty: input?.difficulty ?? "medium", + }, + // Runtime state + players: {}, + gameState: "waiting", + }), + + actions: { + getConfig: (c) => c.state.config, + updateDifficulty: (c, difficulty: string) => { + c.state.config.difficulty = difficulty; + }, + }, +}); +``` + +## API Reference + +- [`CreateOptions`](/typedoc/interfaces/rivetkit.client_mod.CreateOptions.html) - Options for creating actors +- [`CreateRequest`](/typedoc/types/rivetkit.client_mod.CreateRequest.html) - Request type for creation +- [`ActorDefinition`](/typedoc/classes/rivetkit.mod.ActorDefinition.html) - Actor definition returned by `actor()` + +_Source doc path: /docs/actors/input_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/inspector-tabs.md b/.agents/skills/ai-agent-workspace/reference/actors/inspector-tabs.md new file mode 100644 index 0000000..4fea60a --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/inspector-tabs.md @@ -0,0 +1,290 @@ +# Custom Inspector Tabs + +> Source: `src/content/docs/actors/inspector-tabs.mdx` +> Canonical URL: https://rivet.dev/docs/actors/inspector-tabs +> Description: Ship your own UI tabs alongside a Rivet Actor — embedded directly in the dashboard inspector. + +--- +Custom inspector tabs let you embed your own UI directly in the Rivet +dashboard, next to the built-in tabs. Declare a tab on your actor, point +it at a folder of static files, and the dashboard picks it up +automatically. + +Common uses: + +- Domain-specific debugging panels (queue depth, connection maps, log + filters). +- Operational tools (admin buttons, drain controls, snapshot uploaders). +- Any author-defined view that ships with your actor. + +A runnable example lives at +[`examples/inspector-tabs`](https://github.com/rivet-dev/rivet/tree/main/examples/inspector-tabs). + +## Quickstart + +Declare a tab on your actor: + +```ts +import { actor, setup } from "rivetkit"; + +export const counter = actor({ + state: { value: 0 }, + actions: { + increment: (c, amount: number) => { + c.state.value += amount; + return c.state.value; + }, + }, + inspector: { + tabs: [ + { + id: "counter", + label: "Counter", + icon: "tag", + source: "./inspector-tabs/counter", + }, + { id: "queue", hidden: true }, + ], + }, +}); + +export const registry = setup({ use: { counter } }); +registry.start(); +``` + +Drop an `index.html` in the `source` directory: + +```html + + + + + + + +

Counter: …

+ + + +``` + +Open the dashboard and the "Counter" tab appears alongside the built-ins. + +## Configuration + +Each entry in `inspector.tabs[]` is either a **custom tab** or a +**hide modifier** for a built-in. + +### Custom tab + +```ts @nocheck +{ + id: string, // URL-safe id: /^[A-Za-z0-9_-]+$/ + label: string, // Shown in the tab strip + source: string, // Directory of static assets + icon?: string, // Optional icon id +} +``` + +- **`id`** — used as the URL segment and tab-strip key. Cannot collide + with a built-in id (`workflow`, `database`, `state`, `queue`, + `connections`, `console`). +- **`source`** — directory of static files. The bytes you put there are + the bytes the browser sees. Point it at a Vite/webpack `dist/` and + any framework works (React, Vue, Svelte, vanilla — all fine). +- **`icon`** — one of `workflow`, `database`, `state`, `queue`, `plug`, + `terminal`, `tag`, `logs`. Anything else falls back to a neutral icon. + +### Hide a built-in tab + +```ts @nocheck +{ + id: "workflow" | "database" | "state" | "queue" | "connections" | "console", + hidden: true, +} +``` + +Use this to clean up the strip when the actor doesn't use a given +subsystem — e.g. a counter actor with no queues: + +```ts +inspector: { tabs: [{ id: "queue", hidden: true }] } +``` + +Misconfigurations (missing directory, duplicate id, invalid characters, +empty label) throw at registry construction, so problems show up +immediately. + +## Talking to the dashboard + +The tab loads in an iframe and communicates with the dashboard via +`postMessage`. The contract is small. + +### From the dashboard + +The dashboard sends an `init` message on load and again whenever the +inspector token rotates. Always overwrite the cached token when it +arrives. + +```ts @nocheck +{ + type: "init", + v: 1, + actorId: string, + authToken: string, // Per-actor inspector bearer token + theme?: "light" | "dark", + activeTab?: string, // For multi-view tabs +} +``` + +Multi-view tabs can read the optional `activeTab` field on `init` to +seed their initial sub-view. The dashboard does not send a separate +message when the user switches custom tabs — it navigates the iframe +`src` instead, so the tab reloads and receives a fresh `init`. + +### From the tab + +Send `ready` once your message listener is registered: + +```ts @nocheck +{ type: "ready", v: 1 } +``` + +If a fetch returns 401, the token has rotated. Ask the dashboard for a +fresh one and wait for the next `init` — don't retry with the stale +token: + +```ts @nocheck +{ type: "token-refresh-needed", v: 1 } +``` + +### Security check + +Always reject messages whose `event.origin` doesn't match the +`?shellOrigin=` URL parameter. Without this check, any page that frames +your tab could forge an `init` and feed you a fake token. + +### TypeScript types + +If you build the tab with TypeScript, the message and response types +are exported as types-only: + +```ts +import type { + V1Init, + ShellToTabMessage, + TabToShellMessage, + InspectorStateResponse, + InspectorActionResponse, + InspectorRpcsResponse, +} from "rivetkit/inspector-tab"; +``` + +## Reading state and calling actions + +The tab can hit any inspector endpoint with the supplied bearer token. +Use relative paths so the tab doesn't need to know the engine origin or +actor id: + +```js +fetch("../../state", { headers: { Authorization: `Bearer ${token}` } }); +fetch("../../action/increment", { method: "POST", headers: { ... }, body: ... }); +fetch("../../rpcs", { headers: { Authorization: `Bearer ${token}` } }); +fetch("../../connections", { headers: { Authorization: `Bearer ${token}` } }); +fetch("../../queue", { headers: { Authorization: `Bearer ${token}` } }); +``` + +The action body shape is `{ args: [...] }` — the array is passed as +positional arguments to the action. + +Full endpoint reference: +[Debugging → Inspector Endpoints](/docs/actors/debugging#inspector-endpoints). + +For high-frequency UIs, prefer the inspector WebSocket +(`/inspector/connect`) over polling. + +## Styling + +A shared stylesheet matching the dashboard's design tokens is served at +`../../tab.css`: + +```html + +``` + +It defines `--rivet-*` tokens for colors, spacing, radius, and +typography, plus sensible defaults so a bare tab looks at home without +custom CSS: + +```css +.my-card { + background: var(--rivet-card); + color: var(--rivet-foreground); + border: 1px solid var(--rivet-border); + border-radius: var(--rivet-radius-md); + padding: var(--rivet-space-4); +} +``` + +Toggle dark mode by adding the `dark` class to `` — the dashboard +sends the active theme in the `init` message. + +Color tokens come in both pre-wrapped (`--rivet-card`) and raw HSL +(`--rivet-card-raw`) forms, so you can compose with alpha: + +```css +.overlay { background: hsl(var(--rivet-background-raw) / 0.6); } +``` + +You're free to skip the stylesheet entirely and bring your own. + +## Security + +The tab runs in an iframe at the engine origin and can call any +inspector endpoint with the supplied token. Treat the bundle like any +author code that ships with your actor: + +- **Don't inline secrets.** The bundle is fetchable by anyone who can + reach the actor. +- **Always validate `event.origin`.** Reject inbound messages from + anywhere other than the dashboard origin. +- **Never retry silently on 401.** Post `token-refresh-needed` and wait + for a fresh `init`. + +## See also + +- [Debugging](/docs/actors/debugging) — full inspector HTTP API +- [Actions](/docs/actors/actions) — actions your tab can invoke +- [State](/docs/actors/state) — state your tab can read +- [`examples/inspector-tabs`](https://github.com/rivet-dev/rivet/tree/main/examples/inspector-tabs) — runnable example + +_Source doc path: /docs/actors/inspector-tabs_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/keys.md b/.agents/skills/ai-agent-workspace/reference/actors/keys.md new file mode 100644 index 0000000..f4c5018 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/keys.md @@ -0,0 +1,261 @@ +# Actor Keys + +> Source: `src/content/docs/actors/keys.mdx` +> Canonical URL: https://rivet.dev/docs/actors/keys +> Description: Actor keys uniquely identify actor instances within each actor type. Keys are used for addressing which specific actor to communicate with. + +--- +## Key Format + +Actor keys can be either a string or an array of strings: + +```typescript +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +const counter = actor({ + state: { count: 0 }, + actions: { increment: (c) => c.state.count++ } +}); + +const chatRoom = actor({ + state: { messages: [] as string[] }, + actions: {} +}); + +const registry = setup({ use: { counter, chatRoom } }); +const client = createClient("http://localhost:6420"); + +// String key +const counterHandle = client.counter.getOrCreate(["my-counter"]); + +// Array key (compound key) +const chatRoomHandle = client.chatRoom.getOrCreate(["room", "general"]); +``` + +### Compound Keys & User Data + +Array keys are useful when you need compound keys with user-provided data. Using arrays makes adding user data safe by preventing key injection attacks: + +```typescript +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +const chatRoom = actor({ state: { messages: [] as string[] }, actions: {} }); +const gameRoom = actor({ state: { players: [] as string[] }, actions: {} }); +const workspace = actor({ state: { data: {} }, actions: {} }); + +const registry = setup({ use: { chatRoom, gameRoom, workspace } }); +const client = createClient("http://localhost:6420"); + +// Example user data +const userId = "user-123"; +const gameId = "game-456"; +const tenantId = "tenant-789"; +const workspaceId = "workspace-abc"; + +// User-specific chat rooms +const userRoomHandle = client.chatRoom.getOrCreate(["user", userId, "private"]); + +// Game rooms by region and difficulty +const gameRoomHandle = client.gameRoom.getOrCreate(["us-west", "hard", gameId]); + +// Multi-tenant resources +const workspaceHandle = client.workspace.getOrCreate(["tenant", tenantId, workspaceId]); +``` + +This allows you to create hierarchical addressing schemes and organize actors by multiple dimensions. + +Don't build keys using string interpolation like `"foo:${userId}:bar"` when `userId` contains user data. If a user provides a value containing the delimiter (`:` in this example), it can break your key structure and cause key injection attacks. + +### Omitting Keys + +You can create actors without specifying a key in situations where there is a singleton actor (i.e. only one actor of a given type). For example: + +```typescript +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +const globalActor = actor({ + state: { config: {} }, + actions: {} +}); + +const registry = setup({ use: { globalActor } }); +const client = createClient("http://localhost:6420"); + +// Get the singleton session +const globalActorHandle = client.globalActor.getOrCreate(); +``` + +This pattern should be avoided, since a singleton actor usually means you have a single actor serving all traffic & your application will not scale. See [scaling documentation](/docs/actors/scaling) for more information. + +### Key Uniqueness + +Keys are unique within each actor name. Different actor types can use the same key: + +```typescript +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +const chatRoom = actor({ state: { messages: [] as string[] }, actions: {} }); +const userProfile = actor({ state: { name: "" }, actions: {} }); + +const registry = setup({ use: { chatRoom, userProfile } }); +const client = createClient("http://localhost:6420"); + +// These are different actors, same key is fine +const userChat = client.chatRoom.getOrCreate(["user-123"]); +const userProfileHandle = client.userProfile.getOrCreate(["user-123"]); +``` + +## Accessing Keys in Metadata + +Access the actor's key within the actor using the [metadata](/docs/actors/metadata) API: + +```typescript index.ts +import { actor, setup } from "rivetkit"; + +const chatRoom = actor({ + state: { messages: [] as string[] }, + actions: { + getRoomName: (c) => { + // Access the key from metadata + const key = c.key; + return key[1]; // Get "general" from ["room", "general"] + } + } +}); + +export const registry = setup({ + use: { chatRoom } +}); +``` + +```typescript client.ts +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +const chatRoom = actor({ + state: { messages: [] as string[] }, + actions: { getRoomName: (c) => c.key[1] } +}); + +const registry = setup({ use: { chatRoom } }); +const client = createClient("http://localhost:6420"); + +async function connectToRoom(roomName: string) { + // Connect to a chat room + const chatRoomHandle = client.chatRoom.getOrCreate(["room", roomName]); + + // Get the room name from the key + const retrievedRoomName = await chatRoomHandle.getRoomName(); + console.log("Room name:", retrievedRoomName); // e.g., "general" + + return chatRoomHandle; +} + +// Usage example +const generalRoom = await connectToRoom("general"); +``` + +## Configuration Examples + +### Simple Configuration with Keys + +Use keys to provide basic actor configuration: + +```typescript index.ts +import { actor, setup } from "rivetkit"; + +interface UserSessionState { + userId: string; + loginTime: number; + preferences: Record; +} + +const userSession = actor({ + createState: (c): UserSessionState => ({ + userId: c.key[0], // Extract user ID from key + loginTime: Date.now(), + preferences: {} + }), + + actions: { + getUserId: (c) => c.state.userId + } +}); + +export const registry = setup({ + use: { userSession } +}); +``` + +```typescript client.ts +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +const userSession = actor({ + state: { userId: "", loginTime: 0, preferences: {} }, + actions: { getUserId: (c) => c.state.userId } +}); + +const registry = setup({ use: { userSession } }); +const client = createClient("http://localhost:6420"); + +// Pass user ID in the key for user-specific actors +const userId = "user-123"; +const userSessionHandle = client.userSession.getOrCreate([userId]); +``` + +### Complex Configuration with Input + +For more complex configuration, use [input parameters](/docs/actors/input): + +```typescript client.ts +import { actor, setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +interface ChatRoomInput { + maxUsers: number; + isPrivate: boolean; + moderators: string[]; + settings: { allowImages: boolean; slowMode: boolean }; +} + +const chatRoom = actor({ + createState: (c, input: ChatRoomInput) => ({ + maxUsers: input.maxUsers, + isPrivate: input.isPrivate, + moderators: input.moderators, + settings: input.settings, + }), + actions: {} +}); + +const registry = setup({ use: { chatRoom } }); +const client = createClient("http://localhost:6420"); +const roomName = "general"; + +// Create with both key and input +const chatRoomHandle = await client.chatRoom.create(["room", roomName], { + input: { + maxUsers: 100, + isPrivate: false, + moderators: ["admin1", "admin2"], + settings: { + allowImages: true, + slowMode: false + } + } +}); +``` + +## API Reference + +- [`ActorKey`](/typedoc/types/rivetkit.mod.ActorKey.html) - Key type for actors +- [`ActorQuery`](/typedoc/types/rivetkit.mod.ActorQuery.html) - Query type using keys +- [`GetOptions`](/typedoc/interfaces/rivetkit.client_mod.GetOptions.html) - Options for getting by key +- [`QueryOptions`](/typedoc/interfaces/rivetkit.client_mod.QueryOptions.html) - Options for querying + +_Source doc path: /docs/actors/keys_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/kv.md b/.agents/skills/ai-agent-workspace/reference/actors/kv.md new file mode 100644 index 0000000..09ac165 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/kv.md @@ -0,0 +1,162 @@ +# Low-Level KV Storage + +> Source: `src/content/docs/actors/kv.mdx` +> Canonical URL: https://rivet.dev/docs/actors/kv +> Description: Use the built-in key-value store on ActorContext for durable string and binary data alongside actor state. + +--- +KV is deprecated. It is a low-level escape hatch kept for backward compatibility. For new actors, prefer [in-memory state](/docs/actors/state) for small serializable values or [SQLite](/docs/actors/sqlite) for larger or queryable data. + +Every Rivet Actor includes a lightweight key-value store on `c.kv`. It is useful for dynamic keys, blobs, or data that does not fit well in structured state. + +If your data has a known schema, prefer [state](/docs/actors/state). KV is best for flexible or user-defined keys. + +## Basic Usage + +Keys and values default to `text`, so you can use strings without extra options. + +```typescript +import { actor } from "rivetkit"; + +const greetings = actor({ + state: {}, + actions: { + setGreeting: async (c, userId: string, message: string) => { + await c.kv.put(`greeting:${userId}`, message); + }, + getGreeting: async (c, userId: string) => { + return await c.kv.get(`greeting:${userId}`); + }, + }, +}); +``` + +## Value Types + +You can store binary values by passing `Uint8Array` or `ArrayBuffer`. Use `type` on both reads and writes to get the right value type: `binary` for `Uint8Array` and `arrayBuffer` for `ArrayBuffer`. + +```typescript +import { actor } from "rivetkit"; + +const assets = actor({ + state: {}, + actions: { + putAvatar: async (c, bytes: Uint8Array) => { + await c.kv.put("avatar", bytes); + }, + getAvatar: async (c) => { + return await c.kv.get("avatar", { type: "binary" }); + }, + putSnapshot: async (c, data: ArrayBuffer) => { + await c.kv.put("snapshot", data, { type: "arrayBuffer" }); + }, + getSnapshot: async (c) => { + return await c.kv.get("snapshot", { type: "arrayBuffer" }); + }, + }, +}); +``` + +TypeScript returns a concrete type based on the option you pass in: + +```typescript +import { actor } from "rivetkit"; + +const example = actor({ + state: {}, + actions: { + demo: async (c) => { + const textValue = await c.kv.get("greeting"); + // ^? string | null + + const bytes = await c.kv.get("avatar", { type: "binary" }); + // ^? Uint8Array | null + }, + }, +}); +``` + +## Key Types + +Keys accept either `string` or `Uint8Array`. String keys are encoded as UTF-8 by default. + +When listing by prefix, you can control how keys are decoded with `keyType`. Returned keys have the prefix removed. + +```typescript +import { actor } from "rivetkit"; + +const example = actor({ + state: {}, + actions: { + listGreetings: async (c) => { + const results = await c.kv.list("greeting:", { keyType: "text" }); + + for (const [key, value] of results) { + console.log(key, value); + } + }, + }, +}); +``` + +If you use binary keys, set `keyType: "binary"` so the returned keys stay as `Uint8Array`. + +## Range Operations + +Use `listRange(start, end)` to read an arbitrary half-open range `[start, end)`. Use `deleteRange(start, end)` to clear that same range efficiently. + +```typescript +import { actor } from "rivetkit"; + +const example = actor({ + state: {}, + actions: { + pruneAndScan: async (c) => { + const active = await c.kv.listRange("job:", "joc:", { + keyType: "text", + }); + + const encoder = new TextEncoder(); + await c.kv.deleteRange( + encoder.encode("job:old:"), + encoder.encode("job:old;"), + ); + + return active.map(([key, value]) => ({ key, value })); + }, + }, +}); +``` + +## Batch Operations + +KV supports batch operations for efficiency. `batchPut` and `batchGet` work on raw `Uint8Array` keys and values, so encode strings before passing them in. + +```typescript +import { actor } from "rivetkit"; + +const example = actor({ + state: {}, + actions: { + batchOps: async (c) => { + const encoder = new TextEncoder(); + + await c.kv.batchPut([ + [encoder.encode("alpha"), encoder.encode("1")], + [encoder.encode("beta"), encoder.encode("2")], + ]); + + const values = await c.kv.batchGet([ + encoder.encode("alpha"), + encoder.encode("beta"), + ]); + }, + }, +}); +``` + +## API Reference + +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - `c.kv` is available on the context + +_Source doc path: /docs/actors/kv_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/lifecycle.md b/.agents/skills/ai-agent-workspace/reference/actors/lifecycle.md new file mode 100644 index 0000000..d5b9cb4 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/lifecycle.md @@ -0,0 +1,1145 @@ +# Lifecycle + +> Source: `src/content/docs/actors/lifecycle.mdx` +> Canonical URL: https://rivet.dev/docs/actors/lifecycle +> Description: Learn about actor lifecycle hooks for initialization, state management, and cleanup. + +--- +# Lifecycle + +Actors follow a well-defined lifecycle with hooks at each stage. Understanding these hooks is essential for proper initialization, state management, and cleanup. + +## Lifecycle + +Actors transition through several states during their lifetime. Each transition triggers specific hooks that let you initialize resources, manage connections, and clean up state. + +``` +Loading ──Start──▶ Ready ──spawn driver──▶ Started + │ + ┌────────────────────────────────────────┤ + │ │ + │ idle timer + can_sleep │ Destroy command + ▼ ▼ + SleepGrace ─── grace window closes ──▶ Destroying + │ │ + ▼ │ + SleepFinalize ──── stop sequence ───────────┤ + ▼ + Terminated +``` + +**On Create** (runs once per actor) + +1. `onMigrate` +2. `createState` +3. `onCreate` +4. `createVars` +5. `onWake` +6. `run` (background, does not block) + +**On Destroy** + +1. `onDestroy` + +**On Wake** (after sleep, restart, or crash) + +1. `onMigrate` +2. `createVars` +3. `onWake` +4. `run` (background, does not block) + +**On Sleep** (after idle period) + +1. Wait for `run` to complete (with timeout) +2. `onSleep` + +**On Connect** (per client) + +1. `onBeforeConnect` +2. `createConnState` +3. `onConnect` + +**On Disconnect** (per client) + +1. `onDisconnect` + +**On Inbound Action Invoke** (per action call) + +1. Action handler executes + +**On Inbound Queue Publish** (per `handle.send(...)`) + +1. `queues..canPublish` (if defined) +2. Queue message is enqueued + +**On Event Subscription Request** (per subscribe request) + +1. `events..canSubscribe` (if defined) +2. Subscription is applied + +## Lifecycle Hooks + +Actor lifecycle hooks are defined as functions in the actor configuration. + +### `state` + +The `state` constant defines the initial state of the actor. See [state documentation](/docs/actors/state) for more information. + +```typescript +import { actor } from "rivetkit"; + +const counter = actor({ + state: { count: 0 }, + actions: { /* ... */ } +}); +``` + +### `onMigrate` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onMigrate` hook runs on every actor start, before `createState`, `onCreate`, `createVars`, and `onWake`. Can be async. It runs early so that database migrations are applied before any other lifecycle hook accesses the database. The second parameter is `true` when the actor is being created for the first time. + +```typescript +import { actor } from "rivetkit"; + +const counter = actor({ + state: { count: 0 }, + + onMigrate: (c, isNew) => { + // Run database migrations before any other lifecycle hook + }, + + actions: { /* ... */ } +}); +``` + +### `createState` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `createState` function dynamically initializes state based on input. Called only once when the actor is first created. Can be async. See [state documentation](/docs/actors/state) for more information. + +```typescript +import { actor } from "rivetkit"; + +const counter = actor({ + createState: (c, input: { initialCount: number }) => ({ + count: input.initialCount + }), + actions: { /* ... */ } +}); +``` + +### `vars` + +The `vars` constant defines ephemeral variables for the actor. These variables are not persisted and are useful for storing runtime-only data. The value for `vars` must be clonable via `structuredClone`. See [ephemeral variables documentation](/docs/actors/state#ephemeral-variables) for more information. + +```typescript +import { actor } from "rivetkit"; + +const counter = actor({ + state: { count: 0 }, + vars: { lastAccessTime: 0 }, + actions: { /* ... */ } +}); +``` + +### `createVars` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `createVars` function dynamically initializes ephemeral variables. Can be async. Use this when you need to initialize values at runtime. See [ephemeral variables documentation](/docs/actors/state#ephemeral-variables) for more information. + +```typescript +import { actor } from "rivetkit"; + +interface CounterVars { + lastAccessTime: number; + emitter: EventTarget; +} + +const counter = actor({ + state: { count: 0 }, + createVars: (c): CounterVars => ({ + lastAccessTime: Date.now(), + emitter: new EventTarget() + }), + actions: { /* ... */ } +}); +``` + +### `onCreate` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onCreate` hook is called when the actor is first created. Can be async. Use this hook for initialization logic that doesn't affect the initial state. + +```typescript +import { actor } from "rivetkit"; + +const counter = actor({ + state: { count: 0 }, + + onCreate: (c, input: { initialCount: number }) => { + console.log("Actor created with initial count:", input.initialCount); + }, + + actions: { /* ... */ } +}); +``` + +### `onDestroy` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onDestroy` hook is called when the actor is being permanently destroyed. Can be async. Use this for final cleanup operations like closing external connections, releasing resources, or performing any last-minute state persistence. + +The actor is still fully functional when `onDestroy` runs. You can access the database, broadcast events, call `waitUntil`, send queue messages, and use `schedule.after`. State mutations made during `onDestroy` are persisted before the actor is torn down. + +```typescript +import { actor } from "rivetkit"; + +const gameSession = actor({ + onDestroy: (c) => { + // Clean up any external resources + }, + actions: { /* ... */ } +}); +``` + +### `onWake` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +This hook is called any time the actor is started (e.g. after restarting, upgrading code, or crashing). Can be async. + +This is called after the actor has been initialized but before any connections are accepted. + +Use this hook to set up any resources or start any background tasks, such as `setInterval`. + +```typescript +import { actor } from "rivetkit"; + +const counter = actor({ + state: { count: 0 }, + vars: { intervalId: null as NodeJS.Timeout | null }, + + onWake: (c) => { + console.log('Actor started with count:', c.state.count); + + // Set up interval for automatic counting + const intervalId = setInterval(() => { + c.state.count++; + c.broadcast("countChanged", c.state.count); + console.log('Auto-increment:', c.state.count); + }, 10000); + + // Store interval ID in vars to clean up later if needed + c.vars.intervalId = intervalId; + }, + + actions: { + stop: (c) => { + if (c.vars.intervalId) { + clearInterval(c.vars.intervalId); + c.vars.intervalId = null; + } + } + } +}); +``` + +### `onSleep` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +This hook is called when the actor is going to sleep. Can be async. Use this to clean up resources, close connections, or perform any shutdown operations. + +The actor is still fully functional when `onSleep` runs. You can access the database, broadcast events, call `waitUntil`, send queue messages, and use `schedule.after`. State mutations made during `onSleep` are persisted before the actor finishes sleeping. + +This hook may not always be called in situations like crashes or forced terminations. Don't rely on it for critical cleanup operations. + +Not supported on Cloudflare Workers. + +```typescript +import { actor } from "rivetkit"; + +const counter = actor({ + state: { count: 0 }, + vars: { intervalId: null as NodeJS.Timeout | null }, + + onWake: (c) => { + // Set up interval when actor wakes + c.vars.intervalId = setInterval(() => { + c.state.count++; + console.log('Auto-increment:', c.state.count); + }, 10000); + }, + + onSleep: (c) => { + console.log('Actor going to sleep, cleaning up...'); + + // Clean up interval before sleeping + if (c.vars.intervalId) { + clearInterval(c.vars.intervalId); + c.vars.intervalId = null; + } + + // Perform any other cleanup + console.log('Final count:', c.state.count); + }, + + actions: { /* ... */ } +}); +``` + +### `run` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `run` hook is called after the actor starts and runs in the background without blocking actor startup. This is ideal for long-running background tasks like: + +- Reading from message queues in a loop +- Tick loops for periodic work +- Custom workflow logic +- Background processing + +The handler exposes `c.aborted` for loop checks and `c.abortSignal` for canceling operations when the actor is stopping. You should always check or listen for shutdown to exit gracefully. + +**Important behavior:** +- The actor may go to sleep at any time during the `run` handler. Wrap work that must keep the actor awake with `c.keepAwake(promise)` to block idle sleep until the promise settles. +- If the `run` handler exits (returns), the actor follows its normal idle sleep timeout once it becomes idle +- If the `run` handler throws an error, the actor logs the error and then follows its normal idle sleep timeout once it becomes idle +- On shutdown, `c.abortSignal` fires so the `run` handler can exit within the graceful shutdown window. + +```typescript +import { actor } from "rivetkit"; + +// Example: Tick loop +const tickActor = actor({ + state: { tickCount: 0 }, + + run: async (c) => { + c.log.info("Background loop started"); + + while (!c.aborted) { + c.state.tickCount++; + c.log.info({ msg: "tick", count: c.state.tickCount }); + + // Wait 1 second. Final shutdown also resolves this wait. + await new Promise((resolve) => { + const timeout = setTimeout(resolve, 1000); + c.abortSignal.addEventListener("abort", () => { + clearTimeout(timeout); + resolve(); + }, { once: true }); + }); + } + + c.log.info("Background loop exiting gracefully"); + }, + + actions: { + getTickCount: (c) => c.state.tickCount + } +}); +``` + +```typescript +import { actor } from "rivetkit"; + +// Example: Queue consumer +const queueConsumer = actor({ + state: { processedCount: 0 }, + + run: async (c) => { + c.log.info("Queue consumer started"); + + while (!c.aborted) { + // Wait for next message with timeout. + const message = await c.queue.next({ names: ["tasks"], timeout: 1000 }); + + if (message) { + c.log.info({ msg: "processing message", body: message.body }); + // Process the message... + c.state.processedCount++; + } + } + + c.log.info("Queue consumer exiting gracefully"); + }, + + actions: { + getProcessedCount: (c) => c.state.processedCount + } +}); +``` + +Finite `run` handlers leave the actor alive after they finish. If you want a one shot task to clean itself up when it is done, call `c.destroy()` before returning. + +```typescript +import { actor } from "rivetkit"; + +// Example: Finite task that destroys the actor when done +const oneShotJob = actor({ + run: async (c) => { + await processJob(); + c.destroy(); + }, +}); + +async function processJob(): Promise {} +``` + +### `onStateChange` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Called whenever the actor's state changes. Cannot be async. This is often used to broadcast state updates. + +Do not mutate `c.state` inside `onStateChange`; re-entrant state mutation is rejected. + +```typescript +import { actor } from "rivetkit"; + +const counter = actor({ + state: { count: 0 }, + + onStateChange: (c, newState) => { + // Broadcast the new count to all connected clients + c.broadcast('countUpdated', { + count: newState.count + }); + }, + + actions: { + increment: (c) => { + c.state.count++; + return c.state.count; + } + } +}); +``` + +### `createConnState` and `connState` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +There are two ways to define the initial state for connections: +1. `connState`: Define a constant object that will be used as the initial state for all connections +2. `createConnState`: A function that dynamically creates initial connection state based on connection parameters. Can be async. + +### `onBeforeConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.BeforeConnectContext.html) + +The `onBeforeConnect` hook is called whenever a new client connects to the actor. Can be async. Clients can pass parameters when connecting, accessible via `params`. This hook is used for connection validation and can throw errors to reject connections. + +The `onBeforeConnect` hook does NOT return connection state - it's used solely for validation. + +```typescript +import { actor } from "rivetkit"; + +function validateToken(token: string): boolean { + return token.length > 0; +} + +type ConnParams = { + userId?: string; + role?: string; + authToken?: string; +}; + +const chatRoom = actor({ + state: { messages: [] }, + + // Method 2: Dynamically create connection state + createConnState: (_c, params: ConnParams) => { + return { + userId: params.userId || "anonymous", + role: params.role || "guest", + joinTime: Date.now() + }; + }, + + // Validate connections before accepting them + onBeforeConnect: (_c, params: ConnParams) => { + // Validate authentication + const authToken = params.authToken; + if (!authToken || !validateToken(authToken)) { + throw new Error("Invalid authentication"); + } + + // Authentication is valid, connection will proceed + // The actual connection state will come from connState or createConnState + }, + + actions: { /* ... */ } +}); +``` + +Connections cannot interact with the actor until this method completes successfully. Throwing an error will abort the connection. This can be used for authentication - see [Authentication](/docs/actors/authentication) for details. + +### `onConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ConnectContext.html) + +Executed after the client has successfully connected. Can be async. Receives the connection object as a second parameter. + +```typescript +import { actor } from "rivetkit"; + +const chatRoom = actor({ + state: { + users: {} as Record, + messages: [] as string[], + }, + + createConnState: (_c, params: { userId?: string }) => ({ + userId: params.userId ?? "anonymous", + }), + + onConnect: (c, conn) => { + // Add user to the room's user list using connection state + const userId = conn.state.userId; + c.state.users[userId] = { + online: true, + lastSeen: Date.now() + }; + + // Broadcast that a user joined + c.broadcast("userJoined", { userId, timestamp: Date.now() }); + + console.log(`User ${userId} connected`); + }, + + actions: { /* ... */ } +}); +``` + +Messages will not be processed for this actor until this hook succeeds. Errors thrown from this hook will cause the client to disconnect. + +### `canPublish` and `canSubscribe` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Use schema-level hooks to authorize queue publishes and event subscriptions. Both hooks can be async and must return booleans: + +- `queues..canPublish` runs before inbound queue publishes. +- `events..canSubscribe` runs before inbound event subscription requests. + +For actions, enforce authorization directly inside each action handler. + +```typescript +import { actor, event, queue, UserError } from "rivetkit"; + +type ConnState = { role: "member" | "admin" }; + +const securedActor = actor({ + state: {}, + createConnState: (_c, params: { role?: ConnState["role"] }): ConnState => ({ + role: params.role ?? "member", + }), + + events: { + publicFeed: event<{ text: string }>(), + adminFeed: event<{ text: string }>({ + canSubscribe: (c) => c.conn?.state.role === "admin", + }), + }, + + queues: { + jobs: queue<{ task: string }>({ + canPublish: (c) => c.conn?.state.role === "admin", + }), + }, + + actions: { + publicAction: () => "ok", + privateAction: (c) => { + if (c.conn?.state.role !== "admin") { + throw new UserError("Forbidden", { code: "forbidden" }); + } + return "secret"; + }, + }, +}); +``` + +Use deny-by-default rules for each hook and return `false` unless explicitly allowed. See [Access Control](/docs/actors/access-control) for full guidance. + +### `onDisconnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Called when a client disconnects from the actor. Can be async. Receives the connection object as a second parameter. Use this to clean up any connection-specific resources. + +```typescript +import { actor } from "rivetkit"; + +const chatRoom = actor({ + state: { + users: {} as Record, + messages: [] as string[], + }, + + createConnState: (_c, params: { userId?: string }) => ({ + userId: params.userId ?? "anonymous", + }), + + onDisconnect: (c, conn) => { + // Update user status when they disconnect + const userId = conn.state.userId; + if (c.state.users[userId]) { + c.state.users[userId].online = false; + c.state.users[userId].lastSeen = Date.now(); + } + + // Broadcast that a user left + c.broadcast("userLeft", { userId, timestamp: Date.now() }); + + console.log(`User ${userId} disconnected`); + }, + + actions: { /* ... */ } +}); +``` + +### `onRequest` + +[API Reference](/typedoc/interfaces/rivetkit.mod.RequestContext.html) + +The `onRequest` hook handles HTTP requests sent to your actor at `/actors/{actorName}/http/*` endpoints. Can be async. It receives the request context and a standard `Request` object, and should return a `Response` object. + +See [Request Handler](/docs/actors/request-handler) for more details. + +```typescript +import { actor } from "rivetkit"; + +const apiActor = actor({ + state: { requestCount: 0 }, + + onRequest: (c, request) => { + const url = new URL(request.url); + c.state.requestCount++; + + if (url.pathname === "/api/status") { + return new Response(JSON.stringify({ + status: "ok", + requestCount: c.state.requestCount + }), { + headers: { "Content-Type": "application/json" } + }); + } + + return new Response("Not found", { status: 404 }); + }, + + actions: { /* ... */ } +}); +``` + +### `onWebSocket` + +[API Reference](/typedoc/interfaces/rivetkit.mod.WebSocketContext.html) + +The `onWebSocket` hook handles WebSocket connections to your actor. Can be async. It receives the actor context and a `WebSocket` object. Use this to set up WebSocket event listeners and handle real-time communication. + +See [WebSocket Handler](/docs/actors/websocket-handler) for more details. + +```typescript +import { actor } from "rivetkit"; + +const realtimeActor = actor({ + state: { connectionCount: 0 }, + + onWebSocket: (c, websocket) => { + c.state.connectionCount++; + + // Send welcome message + websocket.send(JSON.stringify({ + type: "welcome", + connectionCount: c.state.connectionCount + })); + + // Handle incoming messages + websocket.addEventListener("message", (event) => { + const data = JSON.parse(event.data); + + if (data.type === "ping") { + websocket.send(JSON.stringify({ + type: "pong", + timestamp: Date.now() + })); + } + }); + + // Handle connection close + websocket.addEventListener("close", () => { + c.state.connectionCount--; + }); + }, + + actions: { /* ... */ } +}); +``` + +### `onBeforeActionResponse` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onBeforeActionResponse` hook is called before sending an action response to the client. Can be async. Use this hook to modify or transform the output of an action before it's sent to the client. This is useful for formatting responses, adding metadata, or applying transformations to the output. + +```typescript +import { actor } from "rivetkit"; + +const loggingActor = actor({ + state: { requestCount: 0 }, + + onBeforeActionResponse: (c, actionName, args, output) => { + // Log action calls + console.log(`Action ${actionName} called with args:`, args); + console.log(`Action ${actionName} returned:`, output); + + c.state.requestCount++; + c.broadcast("actionResponseLogged", { + actionName, + timestamp: Date.now(), + requestCount: c.state.requestCount, + }); + + return output; + }, + + actions: { + getUserData: (c, userId: string) => { + c.state.requestCount++; + + // This response is returned after onBeforeActionResponse runs + return { + userId, + profile: { name: "John Doe", email: "john@example.com" }, + lastActive: Date.now() + }; + }, + + getStats: (c) => { + // This also passes through onBeforeActionResponse + return { + requestCount: c.state.requestCount, + uptime: process.uptime() + }; + } + } +}); +``` + +## Sleeping + +Actors automatically sleep after a period of inactivity to free up resources. When a request arrives for a sleeping actor, it wakes up, restores its state, and handles the request. + +### When Actors Sleep + +#### Idle Timeout + +An actor is considered idle and eligible to sleep when **all** of the following are true: + +- No active HTTP requests +- No active connections (unless they are hibernatable WebSockets) +- No active `run` handler (unless it is waiting on a queue) +- No outstanding `c.keepAwake(promise)` promises +- No pending disconnect callbacks +- No async `onWebSocket` event handlers (eg `open`, `message`, `close`) still running + +Once the actor becomes idle, the sleep timer starts. After `sleepTimeout` (default 30 seconds) of continuous inactivity, the actor begins the sleep process. Any activity resets the timer. + +Outbound requests (e.g. `fetch` calls) do not count as activity and will not keep the actor awake. Wrap them with `c.waitUntil()` if they must complete before the actor sleeps. + +#### Upgrades & Eviction + +The platform may force an actor to migrate to a new machine during version upgrades or when a serverless request is about to timeout. The same [shutdown sequence](#shutdown-sequence) runs, then the actor is rescheduled on a new machine and wakes up with its persisted state. + +Use `onSleep`, `waitUntil`, or `keepAwake` to control the length of the grace period before the actor moves to another machine. + +### Manual Lifecycle Controls + +You can also trigger lifecycle transitions from the Rivet Cloud API. These endpoints are useful for operational workflows, debugging, and forcing an actor to move through the same sleep or reschedule path that the platform would normally trigger. + +```bash +curl -X POST \ + "https://cloud-api.rivet.dev/actors/$ACTOR_ID/sleep?namespace=$NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{}' +``` + +```bash +curl -X POST \ + "https://cloud-api.rivet.dev/actors/$ACTOR_ID/reschedule?namespace=$NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{}' +``` + +`/sleep` asks the actor to enter the normal sleep shutdown sequence. `/reschedule` asks the platform to allocate the actor again, which is useful after crashes or when you need to force a fresh placement. Both endpoints require the actor ID and namespace. + +### Skip Ready Wait + +The gateway normally holds requests until the actor is ready. The actor is not ready during startup (before `onWake` finishes) or during the sleep grace period (while `onSleep` and `waitUntil` are running). Probes and readiness checks can opt out with `skipReadyWait` to reach the actor's `onRequest` or `onWebSocket` handler in either window. + +See [Skip Ready Wait](/docs/clients/javascript#skip-ready-wait) on the JavaScript client page for usage. + +### Keeping the Actor Awake + +RivetKit gives you two primitives for holding the actor awake across background work. Both take a `Promise` and differ in how they interact with idle sleep and the grace period. + +| Method | Accepts | Blocks idle sleep | Blocks grace finalize | Use case | +| --- | --- | --- | --- | --- | +| `c.keepAwake(promise)` | `Promise` (returns same promise) | Yes | Yes | Critical work that must keep the actor running end to end (for example a turn in a game, an ongoing tool call). | +| `c.waitUntil(promise)` | `Promise` (returns void) | No | Yes | Best-effort finalization work that may complete during the grace window (for example analytics flushes, cleanup writes). | + +`c.keepAwake(promise)` is the preferred primitive for long-running work the actor should not sleep through. It holds a keep-awake counter until the promise settles, which blocks both idle sleep and the grace finalize step. The promise is returned unchanged, so you can `await` it if you need the value. + +```typescript +import { actor } from "rivetkit"; + +const sessionActor = actor({ + state: { + activeTurns: 0, + }, + + actions: { + runTurn: async (c, input: string) => { + c.state.activeTurns += 1; + try { + const result = await c.keepAwake(processTurn(input)); + return result; + } finally { + c.state.activeTurns -= 1; + } + }, + } +}); + +declare function processTurn(input: string): Promise; +``` + +`setPreventSleep(enabled)` is deprecated and now a no-op. Wrap the work you want to keep alive with `c.keepAwake(promise)` instead. + +### On Sleep Hook + +The [`onSleep`](#onsleep) hook runs during shutdown for cleanup like clearing intervals or closing connections. It is best-effort and will not run if the actor crashes. + +```typescript +import { actor } from "rivetkit"; + +const myActor = actor({ + state: { count: 0 }, + vars: { intervalId: null as ReturnType | null }, + + onWake: (c) => { + c.vars.intervalId = setInterval(() => { c.state.count++; }, 10_000); + }, + + onSleep: (c) => { + if (c.vars.intervalId) clearInterval(c.vars.intervalId); + }, + + actions: { /* ... */ } +}); +``` + +### Wait Before Sleep + +`c.waitUntil(promise)` registers a background promise that must resolve before the actor finishes sleeping. Use this to flush data or finish in-flight work during shutdown without blocking the main execution flow. + +```typescript +import { actor } from "rivetkit"; + +const analyticsActor = actor({ + state: { events: [] as string[] }, + + actions: { + track: (c, event: string) => { + c.state.events.push(event); + + // The actor will wait for this to complete before sleeping. + c.waitUntil( + fetch("https://analytics.example.com/ingest", { + method: "POST", + body: JSON.stringify({ event }), + }).then(() => {}) + ); + }, + }, +}); +``` + +The actor waits up to `sleepGracePeriod` for graceful sleep work during the [shutdown sequence](#shutdown-sequence). That single budget covers `onSleep`, `waitUntil`, `keepAwake`, async raw WebSocket handlers such as `message` and `close`. By default, this graceful sleep window is 15 seconds total. If the timeout is exceeded, the actor proceeds with sleep anyway. + +### Sleep Timeouts + +| Option | Default | Description | +|--------|---------|-------------| +| `sleepTimeout` | 30 seconds | Time of inactivity before the actor begins sleeping. | +| `sleepGracePeriod` | 15 seconds | Total graceful shutdown window for hooks, `waitUntil`, `keepAwake`, async raw WebSocket handlers, and disconnects. | + +Rivet enforces a hard limit of **30 minutes** for the entire stop process. These can be configured in the [options](#options). + +### WebSocket Hibernation + +WebSocket connections are preserved across sleep cycles by default and transparently migrated to the new actor instance. Client stays connected and sees no interruption. Actor migration is very fast, realtime workloads are not interrupted. + +### Shutdown Sequence + +When an actor sleeps or is destroyed, it enters the graceful shutdown window: + +1. `c.abortSignal` fires and `c.aborted` becomes `true`. New connections and dispatch are rejected. Alarm timeouts are cancelled. On sleep, scheduled events are persisted and will be re-armed when the actor wakes. +2. `onSleep` or `onDestroy` and `onDisconnect` for each closing connection run during the same window. User `waitUntil` promises and async raw WebSocket handlers are drained. Hibernatable WebSocket connections are preserved on sleep and closed on destroy. +3. Once graceful work has completed, state is saved and final cleanup runs. + +The entire window is bounded by `sleepGracePeriod` on both sleep and destroy. Defaults to 15 seconds. If the window is exceeded, the actor proceeds to state save anyway. + +#### Graceful shutdown window + +During steps 1 through 6, the actor is still fully functional. Database access, `broadcast`, `waitUntil`, `queue.send`, and `schedule.after` all work. State mutations are persisted at step 7. Actions invoked by pre-existing connections or lifecycle hooks continue to execute normally. + +New connections and raw WebSocket upgrades are rejected as soon as the shutdown sequence begins. New requests that arrive during shutdown are held until the actor wakes up again. The caller does not need to retry. + +If `schedule.after` is called during shutdown, the event is persisted so it survives the sleep/wake cycle, but no local timeout is scheduled. The event will fire after the actor wakes. + +In-flight actions are **not** waited on during shutdown. If an action must complete before the actor stops, wrap the critical work with `c.waitUntil()`. + +## Options + +The `options` object allows you to configure various timeouts and behaviors for your actor. + +```typescript +import { actor } from "rivetkit"; + +const myActor = actor({ + state: { count: 0 }, + + options: { + // Timeout for createVars function (default: 5000ms) + createVarsTimeout: 5000, + + // Timeout for createConnState function (default: 5000ms) + createConnStateTimeout: 5000, + + // Timeout for onConnect hook (default: 5000ms) + onConnectTimeout: 5000, + + // Total graceful shutdown budget for both sleep and destroy. Default: 15000ms. + sleepGracePeriod: 15_000, + + // Interval for saving state (default: 1000ms) + stateSaveInterval: 1_000, + + // Timeout for action execution (default: 60000ms) + actionTimeout: 60_000, + + // Timeout for connection liveness check (default: 2500ms) + connectionLivenessTimeout: 2500, + + // Interval for connection liveness check (default: 5000ms) + connectionLivenessInterval: 5000, + + // Time before actor sleeps due to inactivity (default: 30000ms) + sleepTimeout: 30_000, + + // Whether WebSockets can hibernate for onWebSocket (default: false) + // Can be a boolean or a function that takes a Request and returns a boolean + canHibernateWebSocket: false, + }, + + actions: { /* ... */ } +}); +``` + +| Option | Default | Description | +|--------|---------|-------------| +| `createVarsTimeout` | 5000ms | Timeout for `createVars` function | +| `createConnStateTimeout` | 5000ms | Timeout for `createConnState` function | +| `onConnectTimeout` | 5000ms | Timeout for `onConnect` hook | +| `sleepGracePeriod` | 15000ms | Total graceful shutdown window for both sleep and destroy | +| `stateSaveInterval` | 1000ms | Interval for persisting state | +| `actionTimeout` | 60000ms | Timeout for action execution | +| `connectionLivenessTimeout` | 2500ms | Timeout for connection liveness check | +| `connectionLivenessInterval` | 5000ms | Interval for connection liveness check | +| `sleepTimeout` | 30000ms | Time before actor sleeps due to inactivity | +| `canHibernateWebSocket` | false | Whether WebSockets can hibernate (experimental) | + +## Advanced + +### Actor Shutdown Abort Signal + +The `c.abortSignal` provides an `AbortSignal` that fires when the actor is stopping, and `c.aborted` is the shorthand boolean for loop checks. Use these to cancel ongoing operations when the actor sleeps or is destroyed. + +The abort signal fires at the very start of the [shutdown sequence](#shutdown-sequence), before `onSleep` or `onDestroy` runs. This means `c.aborted` is already `true` inside those lifecycle hooks. The signal fires early so that the `run` handler can exit promptly, but the actor remains fully functional throughout the graceful shutdown window. + +```typescript +import { actor } from "rivetkit"; + +const chatActor = actor({ + actions: { + generate: async (c, prompt: string) => { + const response = await fetch("https://api.example.com/generate", { + method: "POST", + body: JSON.stringify({ prompt }), + signal: c.abortSignal + }); + + return await response.json(); + } + } +}); +``` + +See [Canceling Long-Running Actions](/docs/actors/actions#canceling-long-running-actions) for manually canceling operations on-demand. + +### Using `ActorContext` Type Externally + +When extracting logic from lifecycle hooks or actions into external functions, you'll often need to define the type of the context parameter. Rivet provides helper types that make it easy to extract and pass these context types to external functions. + +```typescript +import { actor, ActorContextOf } from "rivetkit"; + +const myActor = actor({ + state: { count: 0 }, + actions: {}, +}); + +// Simple external function with typed context +function logActorStarted(c: ActorContextOf) { + console.log(`Actor started with count: ${c.state.count}`); +} +``` + +See [Types](/docs/actors/types) for more details on using `ActorContextOf`. + +## Full Example + +```typescript +import { actor } from "rivetkit"; + +interface CounterInput { + initialCount?: number; + stepSize?: number; + name?: string; +} + +interface CounterState { + count: number; + stepSize: number; + name: string; + requestCount: number; +} + +interface ConnParams { + userId: string; + role: string; +} + +interface ConnState { + userId: string; + role: string; + connectedAt: number; +} + +const counter = actor({ + // Initialize state with input + createState: (_c, input: CounterInput): CounterState => ({ + count: input.initialCount ?? 0, + stepSize: input.stepSize ?? 1, + name: input.name ?? "Unnamed Counter", + requestCount: 0, + }), + + // Initialize actor (run setup that doesn't affect initial state) + onCreate: (c, input: CounterInput) => { + console.log(`Counter "${input.name}" initialized`); + // Set up external resources, logging, etc. + }, + + // Dynamically create connection state from params + createConnState: (c, params: ConnParams): ConnState => { + return { + userId: params.userId, + role: params.role, + connectedAt: Date.now() + }; + }, + + // Lifecycle hooks + onWake: (c) => { + console.log(`Counter "${c.state.name}" started with count:`, c.state.count); + }, + + // Background task (does not block startup) + run: async (c) => { + while (!c.aborted) { + // Example: periodic logging + console.log(`Counter "${c.state.name}" is at ${c.state.count}`); + await new Promise((resolve) => { + const timeout = setTimeout(resolve, 60000); + c.abortSignal.addEventListener("abort", () => { + clearTimeout(timeout); + resolve(); + }, { once: true }); + }); + } + }, + + onStateChange: (c, newState) => { + c.broadcast('countUpdated', { + count: newState.count, + name: newState.name + }); + }, + + onBeforeConnect: (c, params: ConnParams) => { + // Validate connection params + if (!params.userId) { + throw new Error("userId is required"); + } + console.log(`User ${params.userId} attempting to connect`); + }, + + onConnect: (c, conn) => { + console.log(`User ${conn.state.userId} connected to "${c.state.name}"`); + }, + + onDisconnect: (c, conn) => { + console.log(`User ${conn.state.userId} disconnected from "${c.state.name}"`); + }, + + // Observe action responses before they are sent + onBeforeActionResponse: (c, actionName, args, output) => { + c.state.requestCount++; + console.log(`Action ${actionName} called`, args); + return output; + }, + + // Define actions + actions: { + increment: (c, amount?: number) => { + const step = amount ?? c.state.stepSize; + c.state.count += step; + return c.state.count; + }, + + getInfo: (c) => ({ + name: c.state.name, + count: c.state.count, + stepSize: c.state.stepSize, + totalRequests: c.state.requestCount, + }), + } +}); + +export default counter; +``` + +_Source doc path: /docs/actors/lifecycle_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/limits.md b/.agents/skills/ai-agent-workspace/reference/actors/limits.md new file mode 100644 index 0000000..a7135be --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/limits.md @@ -0,0 +1,174 @@ +# Limits + +> Source: `src/content/docs/actors/limits.mdx` +> Canonical URL: https://rivet.dev/docs/actors/limits +> Description: Limits and constraints for Rivet Actors. + +--- +This page documents the limits for Rivet Actors. + +There are two types of limits: + +- **Soft Limit**: Application-level limit, configurable in RivetKit. These cannot exceed the hard limit. +- **Hard Limit**: Infrastructure-level limit that cannot be configured. + +Soft limits are configured in two places. Registry-level WebSocket message-size limits are passed to `setup`: + +```typescript +import { setup } from "rivetkit"; + +const rivet = setup({ + use: { /* ... */ }, + maxIncomingMessageSize: 1_048_576, + maxOutgoingMessageSize: 10_485_760, +}); +``` + +Per-actor limits such as queue sizes and lifecycle timeouts are passed to `actor(...)` via `options`: + +```typescript +import { actor } from "rivetkit"; + +const myActor = actor({ + options: { + maxQueueSize: 1000, + actionTimeout: 60_000, + stateSaveInterval: 1_000, + }, + // ... +}); +``` + +## Limits + +### WebSocket + +These limits affect actions that use `.connect()` and [low-level WebSockets](/docs/actors/websocket-handler). + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max incoming message size | 64 KiB | 32 MiB | Maximum size of incoming WebSocket messages. Soft limit configurable via `maxIncomingMessageSize`. | +| Max outgoing message size | 1 MiB | 32 MiB | Maximum size of outgoing WebSocket messages. Soft limit configurable via `maxOutgoingMessageSize`. | +| WebSocket open timeout | — | 15 seconds | Time allowed for WebSocket connection to be established, including `onBeforeConnect` and `createConnState` hooks. Connection is closed if exceeded. | +| Message ack timeout | — | 30 seconds | Time allowed for message acknowledgment before connection is closed. Only relevant in the case of a network issue and does not affect your application. | + +### Hibernating WebSocket + +Hibernating WebSockets allow actors to sleep while keeping client connections alive. All WebSocket limits above also apply to hibernating WebSockets. See [WebSocket Hibernation](/docs/actors/websocket-handler#web-socket-hibernation) for details. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max pending buffer size | — | 128 MiB | Total size of all buffered messages per connection while actor is sleeping. | +| Max pending message count | — | 65,535 | Maximum number of buffered messages per connection while actor is sleeping. | +| Hibernation timeout | — | 90 seconds | Maximum time an actor has to wake up before the client is disconnected. Only relevant if something is wrong with starting actors. | + +### HTTP + +These limits affect actions that do not use `.connect()` and [low-level HTTP requests](/docs/actors/request-handler). + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max request body size | — | 20 MiB | Maximum size of HTTP request bodies. | +| Max response body size | — | 20 MiB | Maximum size of HTTP response bodies. | +| Request timeout | — | 5 minutes | Maximum time for a request to complete. | + +### Networking + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Connection ping timeout | — | 30 seconds | Connection is closed if a ping is not acknowledged within this time. Applies to both HTTP and WebSocket. Only relevant in the case of a network issue and does not affect your application. | + +### Queue + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max queue size | 1,000 messages | — | Maximum number of messages in the queue before new messages are rejected. Configurable via `maxQueueSize`. | +| Max queue message size | 64 KiB | 128 KiB (effective) | Maximum size of each individual queue message. Configurable via `maxQueueMessageSize`. Actual payload is slightly lower after queue serialization overhead. | + +### Actor KV Storage + +These limits apply to the low-level KV storage interface powering Rivet Actors. They likely do not affect your application, but are documented for completeness. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max key size | — | 2 KiB | Maximum size of a single key. | +| Max value size | — | 128 KiB | Maximum size of a single value. | +| Max keys per operation | — | 128 | Maximum number of keys in a single batch get/put/delete operation. Does not apply to range operations (`listRange`, `deleteRange`). | +| Max batch put payload size | — | 976 KiB | Maximum total size of all key-value pairs in a single batch put operation. | +| Max storage size per actor | — | 10 GiB | Maximum total KV storage size for a single actor. | +| List default limit | — | 16,384 | Default maximum number of keys returned by a list operation. | + +### Actor SQLite Storage + +These limits apply to the [SQLite database](/docs/actors/state#sqlite-database) available via `this.sql`. SQLite data is stored through the KV layer, so the storage limit is shared with KV storage. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max storage size per actor | — | 10 GiB | Maximum total storage size for a single actor. This limit is shared with KV storage. | +| Max dirty data per commit | — | 1,310,720 bytes | Maximum raw SQLite page data that can be written in a single commit. This is 320 dirty pages at 4 KiB per page. | + +SQLite commit deltas are compressed and split into internal chunks before storage, but all chunks for one commit are published atomically. The commit limit is therefore based on raw dirty page bytes before compression, not the compressed delta size. + +### KV Preloading + +When an actor starts, the engine can pre-fetch KV data declared in the actor name metadata and deliver it alongside the start command. This removes round-trips to storage during actor startup. RivetKit emits the preload manifest from its own key layout and exposes per-actor overrides via `options`. Operators can still enforce a global cap in the [engine config](/docs/self-hosting/configuration) with `pegboard.preload_max_total_bytes`. In serverless mode, this data is serialized into the `/api/rivet/start` request body along with actor config and protocol metadata, so the accepted body size must be larger than the preload budget. RivetKit defaults `serverless.maxStartPayloadBytes` to 16 MiB to leave margin for the default 1 MiB preload budget and larger SQLite startup page preloads. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max total preload size | 1 MiB | — | Maximum total size of all preloaded KV data sent with the start command. Configurable via `pegboard.preload_max_total_bytes`. Setting to 0 disables all preloading. | +| Max workflow preload size | 128 KiB | — | Default maximum size of preloaded workflow data for RivetKit actors. Configurable per actor via `options.preloadMaxWorkflowBytes`. Setting to 0 disables workflow preloading for that actor. | +| Max connections preload size | 64 KiB | — | Default maximum size of preloaded connection data for RivetKit actors. Configurable per actor via `options.preloadMaxConnectionsBytes`. Setting to 0 disables connections preloading for that actor. | + +### Actor Input + +See [Actor Input](/docs/actors/input) for details. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max actor input size | — | 4 MiB | Maximum size of the input passed when creating an actor. | +| Max connection params size | — | 4 KiB | Maximum size of connection parameters passed when connecting to an actor. | +| Max actor key component size | — | 128 bytes | Maximum size of each component in an actor key array. | +| Max actor key total size | — | 1,024 bytes | Maximum total size of the serialized actor key string. | +| Max actor name length | — | 64 characters | Maximum length for actor and project identifiers. | + +### Rate Limiting + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Rate limit | — | 1200 requests/minute | Default rate limit per actor per IP address with a 1 minute time bucket. | +| Max in-flight requests | — | 32 | Default maximum concurrent requests to an actor per IP address. | + +### Timeouts + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Action timeout | 60 seconds | — | Timeout for RPC actions. Configurable via `actionTimeout`. | +| Create vars timeout | 5 seconds | — | Timeout for `createVars` hook. Configurable via `createVarsTimeout`. | +| Create conn state timeout | 5 seconds | — | Timeout for `createConnState` hook. Configurable via `createConnStateTimeout`. | +| On connect timeout | 5 seconds | — | Timeout for `onConnect` hook. Configurable via `onConnectTimeout`. | +| Sleep grace period | 15 seconds | — | Total graceful shutdown budget for both sleep and destroy. Covers `onSleep`/`onDestroy`, run handler shutdown, `waitUntil`, `keepAwake`, async raw WebSocket handlers, and connection cleanup. Configurable via `sleepGracePeriod`. | +| Sleep timeout | 30 seconds | — | Time of inactivity before actor hibernates. Configurable via `sleepTimeout`. | +| State save interval | 1 second | — | Interval between automatic state saves. Configurable via `stateSaveInterval`. | + +### Serverless Shutdown + +These timeouts control how actors are shut down when a serverless request reaches its lifespan limit. See [Shutdown Sequence](/docs/general/runtime-modes#shutdown-sequence) for details. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Request lifespan | 3600 seconds (60 min) | — | Total lifespan of a serverless request before drain begins. Configurable via `requestLifespan` in [`configurePool`](/docs/general/registry-configuration). | +| Runner config drain grace period | — | 30 minutes | Time a serverless runner reserves for actors to stop gracefully. Configurable via `drainGracePeriod` in [`configurePool`](/docs/general/registry-configuration). | +| Engine serverless drain fallback | — | 10 seconds | Engine-level fallback used when no per-runner config applies. Configurable via [engine config](/docs/self-hosting/configuration) (`pegboard.serverless_drain_grace_period`). | + +### Actor Lifecycle + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Actor start threshold | — | 30 seconds | Maximum time for an actor to start before it is considered lost and rescheduled. | +| Actor stop threshold | — | 30 minutes | Maximum time for an actor to stop before it is considered lost. | + +## Increasing Limits + +These limits are sane defaults designed to protect your application from exploits and accidental runaway bugs. If you have a use case that requires different limits, [contact us](https://rivet.dev/contact) to discuss your requirements. + +_Source doc path: /docs/actors/limits_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/metadata.md b/.agents/skills/ai-agent-workspace/reference/actors/metadata.md new file mode 100644 index 0000000..7a6012b --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/metadata.md @@ -0,0 +1,137 @@ +# Metadata + +> Source: `src/content/docs/actors/metadata.mdx` +> Canonical URL: https://rivet.dev/docs/actors/metadata +> Description: Metadata provides information about the currently running actor. + +--- +## Actor ID + +Get the unique instance ID of the actor: + +```typescript +import { actor } from "rivetkit"; + +const example = actor({ + state: {}, + actions: { + getId: (c) => { + const actorId = c.actorId; + return actorId; + }, + }, +}); +``` + +## Actor Name + +Get the actor type name: + +```typescript +import { actor } from "rivetkit"; + +const example = actor({ + state: {}, + actions: { + getName: (c) => { + const actorName = c.name; + return actorName; + }, + }, +}); +``` + +This is useful when you need to know which actor type is running, especially if you have generic utility functions that are shared between different actor implementations. + +## Actor Key + +Get the actor key used to identify this actor instance: + +```typescript +import { actor } from "rivetkit"; + +const example = actor({ + state: {}, + actions: { + getKey: (c) => { + const actorKey = c.key; + return actorKey; + }, + }, +}); +``` + +The key is used to route requests to the correct actor instance and can include parameters passed when creating the actor. + +Learn more about using keys for actor addressing and configuration in the [keys documentation](/docs/actors/keys). + +## Region + +Region can be accessed from the context object via `c.region`. + +```typescript +import { actor } from "rivetkit"; + +const example = actor({ + state: {}, + actions: { + getRegion: (c) => { + const region = c.region; + return region; + }, + }, +}); +``` + +`c.region` is only supported on Rivet at the moment. + +## Example Usage + +```typescript index.ts +import { actor, setup } from "rivetkit"; + +const chatRoom = actor({ + state: { + messages: [], + }, + + actions: { + // Get actor metadata + getMetadata: (c) => { + return { + actorId: c.actorId, + name: c.name, + key: c.key, + region: c.region, + }; + }, + }, +}); + +export const registry = setup({ + use: { chatRoom }, +}); + +registry.start(); +``` + +```typescript client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +// Connect to a chat room +const chatRoomHandle = client.chatRoom.get(["general"]); + +// Get actor metadata +const metadata = await chatRoomHandle.getMetadata(); +console.log("Actor metadata:", metadata); +``` + +## API Reference + +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining metadata +- [`CreateOptions`](/typedoc/interfaces/rivetkit.client_mod.CreateOptions.html) - Options for creating an actor, including `region` and `input` + +_Source doc path: /docs/actors/metadata_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/queues.md b/.agents/skills/ai-agent-workspace/reference/actors/queues.md new file mode 100644 index 0000000..7b4a252 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/queues.md @@ -0,0 +1,496 @@ +# Queues & Run Loops + +> Source: `src/content/docs/actors/queues.mdx` +> Canonical URL: https://rivet.dev/docs/actors/queues +> Description: Use actor-local durable queues for serial run loops and request/response workflows. + +--- +## What are queues? + +- **Realtime**: messages are delivered to a live actor as soon as possible. +- **Durable**: messages are persisted and survive actor sleep/restart. +- **Request/response**: clients can wait for a queue completion response. +- **Scalable**: queues absorb large bursts and handle heavy backpressure safely. +- **Local per actor**: each actor instance has its own queue storage (scoped by actor key/id). + +Queues are commonly referred to as "mailboxes" in other actor frameworks. + +For a worked queue-driven pattern, see the cookbook: [AI Agent](/cookbook/ai-agent/). + +## What are queues good for? + +- Great for any task that changes actor state. +- Helps avoid race conditions by handling work in order. +- Makes complex behavior easier to organize. + +## Basic queue + +This is the default pattern. Define queue names in `queues`, process them in `run`, and publish from the client with `handle.send(...)`. + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; + +export const counter = actor({ + state: { value: 0 }, + queues: { + increment: queue<{ amount: number }>(), + }, + run: async (c) => { + for await (const message of c.queue.iter()) { + c.state.value += message.body.amount; + } + }, +}); + +export const registry = setup({ use: { counter } }); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.counter.getOrCreate(["main"]); + +await handle.send("increment", { amount: 1 }); +await handle.send("increment", { amount: 5 }); +``` + +## Completable messages + +Use this when you want explicit completion/ack semantics but do not need to return data. + +- `message.complete()` resolves a sender waiting on `wait: true` (or `enqueueAndWait`). It does not change durability: messages are removed from queue storage when they are received, not when they are completed. +- If processing fails before `message.complete()`, the message is not redelivered, and any waiting sender times out instead of receiving a completion. +- `status: "timedOut"` means sender timeout elapsed before `message.complete(...)`. + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; + +export const counter = actor({ + state: { value: 0 }, + queues: { + increment: queue<{ amount: number }, undefined>(), + }, + run: async (c) => { + for await (const message of c.queue.iter({ completable: true })) { + c.state.value += message.body.amount; + await message.complete(); + } + }, +}); + +export const registry = setup({ use: { counter } }); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.counter.getOrCreate(["main"]); + +const result = await handle.send( + "increment", + { amount: 5 }, + { wait: true, timeout: 5_000 }, +); + +if (result.status === "completed") { + console.log("applied"); +} else if (result.status === "timedOut") { + console.log("timed out"); +} +``` + +## Request/reply pattern + +Use this when the sender needs data back from queued work. + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; + +export const counter = actor({ + state: { value: 0 }, + queues: { + increment: queue<{ amount: number }, { value: number }>(), + }, + run: async (c) => { + for await (const message of c.queue.iter({ completable: true })) { + c.state.value += message.body.amount; + await message.complete({ value: c.state.value }); + } + }, +}); + +export const registry = setup({ use: { counter } }); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.counter.getOrCreate(["main"]); + +const result = await handle.send( + "increment", + { amount: 5 }, + { wait: true, timeout: 5_000 }, +); + +if (result.status === "completed") { + console.log(result.response); // { value: 5 } +} else if (result.status === "timedOut") { + console.log("timed out"); +} +``` + +## Queue messages from within an actor + +Queueing is useful from inside actor logic too, not just from clients. + +- Use actions as entrypoints, then enqueue into the run loop to keep mutations serialized. +- You can also call `c.queue.send(...)` from other parts of `run` when needed. +- `c.queue.send(...)` confirms durable enqueue. It does not wait for processing to finish. + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; + +export const counter = actor({ + state: { value: 0 }, + queues: { + mutate: queue<{ delta: number }>(), + }, + run: async (c) => { + for await (const message of c.queue.iter()) { + c.state.value += message.body.delta; + } + }, + actions: { + increment: async (c, delta: number) => { + await c.queue.send("mutate", { delta }); + }, + }, +}); + +export const registry = setup({ use: { counter } }); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.counter.getOrCreate(["main"]); + +await handle.increment(5); +await handle.increment(2); +``` + +## Defining queue schemas + +You can define queue types with `queue()` or with schema objects. Schema objects support [Standard Schema](https://standardschema.dev/) validators, including [Zod](https://zod.dev/). + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; +import { z } from "zod"; + +export const worker = actor({ + state: {}, + queues: { + // Use generic queue typing when you want compile-time typing only. + foo: queue<{ id: string }, { ok: true }>(), + // Use schema objects when you want runtime validation for message and completion payloads. + bar: { + message: z.object({ id: z.string() }), + complete: z.object({ ok: z.boolean() }), + }, + }, +}); + +export const registry = setup({ use: { worker } }); +``` + +## Pull messages with `next` and `nextBatch` + +Use `next` when you want to wait for one queue message. +Use `nextBatch` when you want to wait for multiple queue messages. + +- Waits until messages are available unless timeout is hit. +- Omit `timeout` to wait indefinitely. + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; + +export const queueWorker = actor({ + state: {}, + queues: { + jobs: queue<{ id: string }>(), + }, + actions: { + pull: async (c) => { + const batch = await c.queue.nextBatch({ + count: 10, + timeout: 1_000, + }); + + const oneWithoutTimeout = await c.queue.next(); + + return { + batchCount: batch.length, + receivedOneWithoutTimeout: oneWithoutTimeout !== undefined, + }; + }, + }, +}); + +export const registry = setup({ use: { queueWorker } }); +``` + +## Poll messages + +Use `tryNext` when you need one non-blocking read. +Use `tryNextBatch` for non-blocking batch reads. + +- Returns immediately and never waits. + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; + +export const queueWorker = actor({ + state: {}, + queues: { + jobs: queue<{ id: string }>(), + }, + actions: { + poll: async (c) => { + const immediate = await c.queue.tryNext(); + + const immediateBatch = await c.queue.tryNextBatch({ + count: 10, + }); + + return { + hasImmediate: immediate !== undefined, + immediateBatchCount: immediateBatch.length, + }; + }, + }, +}); + +export const registry = setup({ use: { queueWorker } }); +``` + +## Abort signals + +Use `signal` when your receive loop needs external cancellation semantics in addition to actor shutdown behavior. + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; +import { joinSignals } from "rivetkit/utils"; + +export const signalWorker = actor({ + state: {}, + createVars: () => ({ + cancelController: new AbortController(), + }), + queues: { + jobs: queue<{ id: string }>(), + }, + actions: { + cancelProcessing: async (c) => { + c.vars.cancelController.abort(); + }, + }, + run: async (c) => { + while (!c.aborted) { + const signal = joinSignals(c.abortSignal, c.vars.cancelController.signal); + + try { + const message = await c.queue.next({ signal }); + if (!message) continue; + console.log("Processing job", message.body.id); + } catch (error) { + if (c.vars.cancelController.signal.aborted && !c.aborted) { + c.vars.cancelController = new AbortController(); + continue; + } + throw error; + } + } + }, +}); + +export const registry = setup({ use: { signalWorker } }); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.signalWorker.getOrCreate(["main"]); + +await handle.send("jobs", { id: "job-1" }); +await handle.cancelProcessing(); +``` + +## Multiple queues + +Multiple queues let you separate message flows by purpose. By default, receive calls race across all queues when `names` is not specified. In this pattern, prompt messages run through a streaming loop while stop messages act as control signals on a separate receive path. + +Use `iter({ names: ["prompt"] })` as the main stream and `next({ names: ["stop"] })` as a stop signal. + +```ts index.ts +import { openai } from "@ai-sdk/openai"; +import { generateText } from "ai"; +import { actor, queue, setup } from "rivetkit"; +import { joinSignals } from "rivetkit/utils"; + +export const agent = actor({ + state: { running: false, messages: [] as string[] }, + queues: { + prompt: queue<{ prompt: string }, undefined>(), + stop: queue<{ reason?: string }>(), + }, + run: async (c) => { + for await (const promptMessage of c.queue.iter({ names: ["prompt"], completable: true })) { + // Create a stop controller for this prompt run. + const stopController = new AbortController(); + const runSignal = joinSignals(c.abortSignal, stopController.signal); + + // Watch for stop messages while generation is running. + const stopWatcher = c.queue + .next({ names: ["stop"], signal: runSignal }) + .then((stopMessage) => { + if (stopMessage) stopController.abort(); + }) + .catch(() => {}); + + // Generate a response for the prompt. + c.state.running = true; + const { text } = await generateText({ + model: openai("gpt-5"), + prompt: promptMessage.body.prompt, + abortSignal: runSignal, + }).finally(async () => { + stopController.abort(); + c.state.running = false; + }); + + // Append each model response to actor state and acknowledge the prompt. + c.state.messages.push(text); + await promptMessage.complete(); + } + }, +}); + +export const registry = setup({ use: { agent } }); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.agent.getOrCreate(["main"]); + +await handle.send("prompt", { prompt: "summarize latest logs" }); +await handle.send("stop", { reason: "user canceled" }); +``` + +## Sleeping behavior + +If an actor has a `run` handler, it does not sleep while that handler is actively doing work. It only can sleep when the run loop is blocked waiting for queue entries (for example inside `iter(...)` or `next(...)`). + +This means you can run normal code in `run` without worrying about sleep interrupting it mid-call. + +## Debugging + +- `GET /inspector/queue?limit=50` returns queue size and pending message metadata. +- `GET /inspector/summary` includes `queueSize` for quick queue health checks. +- `POST /queue/:name` with `wait: true` is useful to verify completable/request-response behavior. +- In non-dev mode, inspector endpoints require authorization. + +## Recommendations + +- Actions are for getting data, queue entries are for mutating data. +- Implement connection auth in `onBeforeConnect`. See [Authentication](/docs/actors/authentication). +- Route most state changes through one queue loop so ordering stays predictable. +- If you need more complex multi-step run loops, consider using workflows. +- Use `c.aborted` and `c.abortSignal` for actor shutdown. Use your own `AbortController` for earlier loop cancellation. +- Add `timeout` when callers need bounded wait behavior. +- Use `wait: true` only when the caller actually needs a response. + +## Pitfalls + +### Avoid `wait: true` between actors + +`wait: true` blocks the sender's run loop until the receiver finishes. Between actors, this adds unnecessary overhead and risks deadlocks, especially if the target actor needs to communicate back. If an actor sends a `wait: true` message to *itself*, it is a guaranteed deadlock because the run loop is already busy processing the current message. + +Reserve `wait: true` for external callers (HTTP handlers, CLI tools, client apps). For actor-to-actor communication, send a queue message to the other actor without `wait: true`, then have that actor send a queue message back when the work is done. + +## Tips + +### Message TTL + +Every queue message includes a `createdAt` timestamp. Use this to skip or discard stale messages in your run loop: + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; + +export const worker = actor({ + state: {}, + queues: { + jobs: queue<{ task: string }>(), + }, + run: async (c) => { + for await (const message of c.queue.iter()) { + const ageMs = Date.now() - message.createdAt; + if (ageMs > 60_000) { + // Message is older than 60 seconds, skip it. + continue; + } + console.log("Processing", message.body.task); + } + }, +}); + +export const registry = setup({ use: { worker } }); +``` + +### Delayed delivery + +Use [`c.schedule`](/docs/actors/schedule) to enqueue messages at a future time instead of processing them immediately: + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; + +export const reminder = actor({ + state: {}, + queues: { + notify: queue<{ userId: string }>(), + }, + actions: { + scheduleReminder: async (c, userId: string) => { + // Enqueue a message in 30 seconds. + c.schedule.after(30_000, "enqueueReminder", userId); + }, + enqueueReminder: async (c, userId: string) => { + await c.queue.send("notify", { userId }); + }, + }, + run: async (c) => { + for await (const message of c.queue.iter()) { + console.log("Sending reminder to", message.body.userId); + } + }, +}); + +export const registry = setup({ use: { reminder } }); +``` + +See [Schedule](/docs/actors/schedule) for the full scheduling API. + +_Source doc path: /docs/actors/queues_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/quickstart/backend.md b/.agents/skills/ai-agent-workspace/reference/actors/quickstart/backend.md new file mode 100644 index 0000000..e5917ef --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/quickstart/backend.md @@ -0,0 +1,183 @@ +# Node.js & Bun Quickstart + +> Source: `src/content/docs/actors/quickstart/backend.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/backend +> Description: Get started with Rivet Actors in Node.js and Bun + +--- +Prefer to start from a complete project? See the runnable [`hello-world`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world) example. + +## Steps + +### Add Rivet Skill to Coding Agent (Optional) + +If you're using an AI coding assistant (like Claude Code, Cursor, Windsurf, etc.), add Rivet skills for enhanced development assistance: + +```sh +npx skills add rivet-dev/skills +``` + +### Install Rivet + +```sh +npm install rivetkit +``` + +### Create Actors and Start Server + +Create a file with your actors, set up the registry, and start the server: + +```ts index.ts +import { actor, setup } from "rivetkit"; + +export 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; + }, + }, +}); + +export const registry = setup({ + use: { counter }, +}); + +registry.start(); +``` + +### Run Server + +```sh Node.js +npx tsx --watch index.ts +``` + +```sh Bun +bun --watch index.ts +``` + +```sh Deno +deno run --allow-net --allow-read --allow-env --watch index.ts +``` + +Your server is now running on `http://localhost:6420`. Clients connect directly to the Rivet Engine on this port. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend: + +### TypeScript + +```ts index.ts @hide +import { actor, setup } from "rivetkit"; + +export 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; + }, + }, +}); + +export const registry = setup({ + use: { counter }, +}); + +registry.start(); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +// Get or create a counter actor for the key "my-counter" +const counter = client.counter.getOrCreate(["my-counter"]); + +// Call actions +const count = await counter.increment(3); +console.log("New count:", count); + +// Listen to realtime events +const connection = counter.connect(); +connection.on("newCount", (newCount: number) => { + console.log("Count changed:", newCount); +}); + +// Increment through connection +await connection.increment(1); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### React + +```ts index.ts @hide +import { actor, setup } from "rivetkit"; + +export 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; + }, + }, +}); + +export const registry = setup({ + use: { counter }, +}); + +registry.start(); +``` + +```tsx Counter.tsx +import { createRivetKit } from "@rivetkit/react"; +import { useState } from "react"; +import type { registry } from "./index"; + +const { useActor } = createRivetKit("http://localhost:6420"); + +function Counter() { + const [count, setCount] = useState(0); + + // Get or create a counter actor for the key "my-counter" + const counter = useActor({ + name: "counter", + key: ["my-counter"] + }); + + // Listen to realtime events + counter.useEvent("newCount", (x: number) => setCount(x)); + + const increment = async () => { + // Call actions + await counter.connection?.increment(1); + }; + + return ( +
+

Count: {count}

+ +
+ ); +} +``` + +See the [React documentation](/docs/clients/react) for more information. + +### Deploy + +## Configuration Options + +_Source doc path: /docs/actors/quickstart/backend_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/quickstart/cloudflare.md b/.agents/skills/ai-agent-workspace/reference/actors/quickstart/cloudflare.md new file mode 100644 index 0000000..bf43bd5 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/quickstart/cloudflare.md @@ -0,0 +1,263 @@ +# Cloudflare Workers Quickstart + +> Source: `src/content/docs/actors/quickstart/cloudflare.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/cloudflare +> Description: Set up a Rivet project locally targeting Cloudflare Workers. + +--- +Set up a Rivet project locally that runs on Cloudflare Workers. The `@rivetkit/cloudflare-workers` package wires the WebAssembly runtime for you. + +Prefer to start from a complete project? See the runnable [`hello-world-cloudflare-workers`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-cloudflare-workers) example (with [Hono](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-cloudflare-workers-hono) and [raw router](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-cloudflare-workers-raw) variants). + +## Steps + +### Install Packages + +```sh +npm install rivetkit @rivetkit/cloudflare-workers +npm install --save-dev wrangler +``` + +### Configure Wrangler + +```toml wrangler.toml +name = "rivetkit-cloudflare" +main = "src/index.ts" +compatibility_date = "2025-04-01" +compatibility_flags = ["nodejs_compat"] +``` + +The `nodejs_compat` flag is required so the runtime can read its connection config from `process.env`. + +### Create the Worker + +`createHandler` serves the Rivet manager API on `/api/rivet`. Pick how you want to handle your own routes: + +- **Default**: Rivet handles everything. +- **Hono**: Mount a [Hono](https://hono.dev) app for your routes (`npm install hono`). +- **Raw**: Provide a `fetch` and route requests yourself. + +```ts Default @nocheck +import { actor } from "rivetkit"; +import { createHandler } from "@rivetkit/cloudflare-workers"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +export default createHandler({ use: { counter } }); +``` + +```ts Hono @nocheck +import { actor } from "rivetkit"; +import { createClient } from "rivetkit/client"; +import { createHandler, setup } from "@rivetkit/cloudflare-workers"; +import { Hono } from "hono"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +// `setup` returns a typed registry, so the client below is fully typed. +const registry = setup({ use: { counter } }); + +const app = new Hono(); + +app.get("/", (c) => c.text("Hello from Hono + Rivet Actors!")); + +app.post("/increment/:name", async (c) => { + // `createClient` reads RIVET_ENDPOINT from the environment (passed by `rivet + // dev`, or set as a Worker secret in production). + const client = createClient(); + const count = await client.counter.getOrCreate(c.req.param("name")).increment(1); + return c.json({ count }); +}); + +// Rivet keeps `/api/rivet`; Hono handles everything else. +export default createHandler(registry, { fetch: app.fetch }); +``` + +```ts Raw @nocheck +import { actor } from "rivetkit"; +import { createClient } from "rivetkit/client"; +import { createHandler, setup } from "@rivetkit/cloudflare-workers"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +// `setup` returns a typed registry, so the client below is fully typed. +const registry = setup({ use: { counter } }); + +// Rivet keeps `/api/rivet`; your `fetch` handles everything else. +export default createHandler(registry, { + fetch: async (request: Request) => { + const url = new URL(request.url); + + if (url.pathname === "/") { + return new Response("Hello from a raw Rivet Worker router!"); + } + + const increment = url.pathname.match(/^\/increment\/(.+)$/); + if (request.method === "POST" && increment) { + // `createClient` reads RIVET_ENDPOINT from the environment (passed by + // `rivet dev`, or set as a Worker secret in production). + const client = createClient(); + const count = await client.counter.getOrCreate(increment[1]).increment(1); + return Response.json({ count }); + } + + return new Response("Not found", { status: 404 }); + }, +}); +``` + +### Run Locally + +Start Rivet. The CLI runs the local engine and spawns `wrangler dev` for you: + +```sh +npx @rivetkit/cli dev --provider cloudflare +``` + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend. It connects directly to the local engine on `http://localhost:6420`: + +### TypeScript + +```ts index.ts @hide +import { actor, setup } from "rivetkit"; + +export 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; + }, + }, +}); + +export const registry = setup({ + use: { counter }, +}); + +registry.start(); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +// Get or create a counter actor for the key "my-counter" +const counter = client.counter.getOrCreate(["my-counter"]); + +// Call actions +const count = await counter.increment(3); +console.log("New count:", count); + +// Listen to realtime events +const connection = counter.connect(); +connection.on("newCount", (newCount: number) => { + console.log("Count changed:", newCount); +}); + +// Increment through connection +await connection.increment(1); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### React + +```ts index.ts @hide +import { actor, setup } from "rivetkit"; + +export 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; + }, + }, +}); + +export const registry = setup({ + use: { counter }, +}); + +registry.start(); +``` + +```tsx Counter.tsx +import { createRivetKit } from "@rivetkit/react"; +import { useState } from "react"; +import type { registry } from "./index"; + +const { useActor } = createRivetKit("http://localhost:6420"); + +function Counter() { + const [count, setCount] = useState(0); + + // Get or create a counter actor for the key "my-counter" + const counter = useActor({ + name: "counter", + key: ["my-counter"] + }); + + // Listen to realtime events + counter.useEvent("newCount", (x: number) => setCount(x)); + + const increment = async () => { + // Call actions + await counter.connection?.increment(1); + }; + + return ( +
+

Count: {count}

+ +
+ ); +} +``` + +See the [React documentation](/docs/clients/react) for more information. + +### Deploy + +Ready to ship? See [Deploying to Cloudflare Workers](/docs/deploy/cloudflare). + +## Related + +- [Quickstart](/docs/actors/quickstart) +- [Deploying to Cloudflare Workers](/docs/deploy/cloudflare) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/actors/quickstart/cloudflare_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/quickstart/effect.md b/.agents/skills/ai-agent-workspace/reference/actors/quickstart/effect.md new file mode 100644 index 0000000..11c558d --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/quickstart/effect.md @@ -0,0 +1,239 @@ +# Effect.ts Quickstart (Beta) + +> Source: `src/content/docs/actors/quickstart/effect.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/effect +> Description: Build a Rivet Actor with the Effect SDK + +--- +Effect support is in beta. The `@rivetkit/effect` API may change between releases. See the [`hello-world-effect`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-effect) and [`chat-room-effect`](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room-effect) examples for complete runnable projects. + +## Steps + +### Install Rivet + +Add `rivetkit`, the Effect SDK, and its Effect peers: + +```sh +npm install rivetkit @rivetkit/effect effect @effect/platform-node +``` + +### Define Your Actor + +Split each actor into a public contract and a server-only implementation so the contract can be imported from client code without leaking server details. + +The contract declares the actor and its actions. Actions are standalone values with explicit [`effect/Schema`](https://effect.website/docs/schema/introduction/) payloads and successes, validated end to end: + +```ts src/actors/counter/api.ts @nocheck +import { Action, Actor } from "@rivetkit/effect"; +import { Schema } from "effect"; + +export const Increment = Action.make("Increment", { + payload: { amount: Schema.Number }, + success: Schema.Number, +}); + +export const GetCount = Action.make("GetCount", { + success: Schema.Number, +}); + +export const Counter = Actor.make("Counter", { + actions: [Increment, GetCount], +}); +``` + +The implementation registers the actor with `.toLayer`. The wake function runs once when the actor awakes and returns the action handlers. Persisted state is accessed through a `SubscriptionRef`-like `State` API: + +```ts src/actors/counter/live.ts @nocheck +import { Actor, State } from "@rivetkit/effect"; +import { Effect, Schema } from "effect"; +import { Counter } from "./api.ts"; + +export const CounterLive = Counter.toLayer( + Effect.fnUntraced(function* ({ rawRivetkitContext, state }) { + return Counter.of({ + Increment: Effect.fnUntraced(function* ({ payload }) { + const next = yield* State.updateAndGet(state, (current) => ({ + count: current.count + payload.amount, + })).pipe(Effect.orDie); + + // Broadcast the new value to every connected client. + rawRivetkitContext.broadcast("newCount", next.count); + + return next.count; + }), + GetCount: () => + State.get(state).pipe( + Effect.map((current) => current.count), + Effect.orDie, + ), + }); + }), + { + state: { + schema: Schema.Struct({ count: Schema.Number }), + initialValue: () => ({ count: 0 }), + }, + name: "Counter", + icon: "calculator", + }, +); +``` + +### Serve The Registry + +Compose the actor layers and serve them with `Registry.serve`. `Registry.layer()` reads engine config from the environment, and the actor layer is provided a `Client` so actors can call other actors: + +```ts src/main.ts @nocheck +import { NodeRuntime } from "@effect/platform-node"; +import { Client, Registry } from "@rivetkit/effect"; +import { Layer } from "effect"; +import { CounterLive } from "./actors/counter/live.ts"; + +const endpoint = process.env.RIVET_ENDPOINT ?? "http://127.0.0.1:6420"; + +const ActorsLayer = CounterLive.pipe(Layer.provide(Client.layer({ endpoint }))); + +const MainLayer = Registry.serve(ActorsLayer).pipe(Layer.provide(Registry.layer())); + +// Keeps the layer alive. Tears down on SIGINT/SIGTERM. +Layer.launch(MainLayer).pipe(NodeRuntime.runMain); +``` + +### Run The Server + +Set `RIVET_RUN_ENGINE=1` to spawn a local Rivet Engine alongside the server. The engine binary is downloaded and cached the first time you run, so there is nothing else to install: + +```sh +RIVET_RUN_ENGINE=1 npx tsx --watch src/main.ts +``` + +Your server now connects to the Rivet Engine on `http://localhost:6420`. Clients connect directly to the engine on this port. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +To point at a remote engine instead, set `RIVET_ENDPOINT=https://...` and omit `RIVET_RUN_ENGINE`. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend: + +### Effect + +The Effect client imports the same actor contract from your registry. `Counter.client` yields a typed accessor backed by the client layer: + +```ts src/client.ts @nocheck +import { NodeRuntime } from "@effect/platform-node"; +import { Client } from "@rivetkit/effect"; +import { Effect } from "effect"; +import { Counter } from "./actors/counter/api.ts"; + +const program = Effect.gen(function* () { + const counter = (yield* Counter.client).getOrCreate("my-counter"); + + const count = yield* counter.Increment({ amount: 3 }); + yield* Effect.log(`New count: ${count}`); + + const total = yield* counter.GetCount(); + yield* Effect.log(`Total: ${total}`); +}); + +const ClientLayer = Client.layer({ endpoint: "http://localhost:6420" }); + +program.pipe(Effect.provide(ClientLayer), NodeRuntime.runMain); +``` + +With the server still running, start the client in another terminal: + +```sh +npx tsx src/client.ts +``` + +See the [`chat-room-effect`](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room-effect) example for a larger project with typed errors and actor-to-actor calls. + +### TypeScript + +A plain RivetKit client can call your Effect actor by name through the same engine. Actor and action names are resolved at runtime, so the client is untyped here: + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient("http://localhost:6420"); + +const counter = client.Counter.getOrCreate(["my-counter"]); + +const count = await counter.Increment({ amount: 3 }); +console.log("New count:", count); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### Deploy + +## Feature Support + +The Effect SDK wraps the most common actor features with typed, schema-validated APIs. Everything else is still fully usable through the raw RivetKit context (see [Raw Escape Hatch](#raw-escape-hatch) below), so no feature is off limits, it just isn't typed yet. + +| Feature | Effect-native API | Access | +| --- | --- | --- | +| Actor contract & actions | `Actor.make`, `Action.make` | Typed | +| Persisted state | `State.get` / `set` / `update` / `updateAndGet` / `changes` | Typed | +| Typed client | `Actor.client`, `Client.layer` | Typed | +| Typed errors | `RivetError` | Typed | +| Logging | `Logger` | Typed | +| Sleep request | `Actor.Sleep` | Typed | +| Actor address (`actorId` / `name` / `key`) | `Actor.CurrentAddress` | Typed | +| Registry serve / test / web handler | `Registry` | Typed | +| [Events & broadcast](/docs/actors/events) | Not yet wrapped | `rawRivetkitContext.broadcast(...)` | +| [Schedule](/docs/actors/schedule) | Not yet wrapped | `rawRivetkitContext.schedule.*` | +| [Embedded SQLite](/docs/actors/sqlite) | Not yet wrapped | `rawRivetkitContext.db.execute(...)` | +| [Destroy](/docs/actors/lifecycle) | Not yet wrapped | `rawRivetkitContext.destroy()` | +| Queues, connections, vars, alarms | Not yet wrapped | `rawRivetkitContext.*` | +| Lifecycle hooks (`onSleep` / `onDestroy`) | Not yet wrapped | `rawRivetkitContext.*` | +| Raw HTTP / WebSocket handlers | Not yet wrapped | `rawRivetkitContext.*` | + +### Raw Escape Hatch + +Every wake function receives `rawRivetkitContext`, the underlying RivetKit [actor context](/docs/actors). Reach for it to use any feature that does not have a typed wrapper yet. The typed `state` argument and the raw context point at the same actor, so you can mix both: + +```ts src/actors/counter/live.ts @nocheck +export const CounterLive = Counter.toLayer( + Effect.fnUntraced(function* ({ rawRivetkitContext, state }) { + return Counter.of({ + Increment: Effect.fnUntraced(function* ({ payload }) { + // Typed state wrapper + const next = yield* State.updateAndGet(state, (current) => ({ + count: current.count + payload.amount, + })).pipe(Effect.orDie); + + // Untyped features run through the raw context + rawRivetkitContext.broadcast("newCount", next.count); + rawRivetkitContext.schedule.after(1_000, "tick", {}); + + return next.count; + }), + }); + }), + { + state: { + schema: Schema.Struct({ count: Schema.Number }), + initialValue: () => ({ count: 0 }), + }, + name: "Counter", + }, +); +``` + +Calls through `rawRivetkitContext` are not validated by `effect/Schema` and their payloads are typed as they are in the base RivetKit API. + +## Next Steps + + +- [Actions](/docs/actors/actions) — Define the RPC surface clients call on your actor. + + +- [State](/docs/actors/state) — Persist and load actor state across sleeps and restarts. + + +- [Events](/docs/actors/events) — Broadcast realtime updates to connected clients. + +_Source doc path: /docs/actors/quickstart/effect_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/quickstart/next-js.md b/.agents/skills/ai-agent-workspace/reference/actors/quickstart/next-js.md new file mode 100644 index 0000000..2c8c421 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/quickstart/next-js.md @@ -0,0 +1,136 @@ +# Next.js Quickstart + +> Source: `src/content/docs/actors/quickstart/next-js.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/next-js +> Description: Get started with Rivet Actors in Next.js + +--- +### Add Rivet Skill to Coding Agent (Optional) + +If you're using an AI coding assistant (like Claude Code, Cursor, Windsurf, etc.), add Rivet skills for enhanced development assistance: + +```sh +npx skills add rivet-dev/skills +``` + +### Create a Next.js App + +```sh +npx create-next-app@latest my-app +cd my-app +``` + +### Install RivetKit + +### Create an Actor + +Create a file at `src/rivet/registry.ts` with a simple counter actor: + +```ts src/rivet/registry.ts +import { actor, setup } from "rivetkit"; + +export 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; + }, + }, +}); + +export const registry = setup({ + use: { counter }, +}); +``` + +### Setup Rivet API route + +Create a file at `src/app/api/rivet/[...all]/route.ts` to setup the API routes: + +```ts src/app/api/rivet/[...all]/route.ts @nocheck +import { toNextHandler } from "@rivetkit/next-js"; +import { registry } from "@/rivet/registry"; + +export const maxDuration = 300; + +export const { GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS } = toNextHandler(registry); +``` + +### Use the Actor in a component + +Create a Counter component and add it to your page: + +```tsx src/components/Counter.tsx @nocheck +"use client"; + +import { createRivetKit } from "@rivetkit/next-js/client"; +import type { registry } from "@/rivet/registry"; +import { useState } from "react"; + +export const { useActor } = createRivetKit({ + endpoint: + process.env.NEXT_PUBLIC_RIVET_ENDPOINT ?? "http://localhost:3000/api/rivet", + namespace: process.env.NEXT_PUBLIC_RIVET_NAMESPACE, + token: process.env.NEXT_PUBLIC_RIVET_TOKEN, +}); + +export function Counter() { + const [count, setCount] = useState(0); + + // Get or create a counter actor for the key "my-counter" + const counter = useActor({ + name: "counter", + key: ["my-counter"] + }); + + // Listen to realtime events + counter.useEvent("newCount", (x: number) => setCount(x)); + + const increment = async () => { + // Call actions + await counter.connection?.increment(1); + }; + + return ( +
+

Count: {count}

+ +
+ ); +} +``` + +```tsx src/app/page.tsx @nocheck +import { Counter } from "@/components/Counter"; + +export default function Home() { + return ( +
+

My App

+ +
+ ); +} +``` + +For information about the Next.js client API, see the [React Client API Reference](/docs/clients/react). + +### Run Locally + +Start the Next.js dev server. Rivet auto-starts a local engine alongside it: + +```sh +npm run dev +``` + +Open `http://localhost:3000` in your browser to use the app. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Deploy to Vercel + +See the [Vercel deployment guide](/docs/deploy/vercel) for detailed instructions on deploying your Rivet app to Vercel. + +_Source doc path: /docs/actors/quickstart/next-js_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/quickstart/react.md b/.agents/skills/ai-agent-workspace/reference/actors/quickstart/react.md new file mode 100644 index 0000000..8c412dc --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/quickstart/react.md @@ -0,0 +1,157 @@ +# React Quickstart + +> Source: `src/content/docs/actors/quickstart/react.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/react +> Description: Build realtime React applications with Rivet Actors + +--- +## Steps + +### Add Rivet Skill to Coding Agent (Optional) + +If you're using an AI coding assistant (like Claude Code, Cursor, Windsurf, etc.), add Rivet skills for enhanced development assistance: + +```sh +npx skills add rivet-dev/skills +``` + +### Install Dependencies + +```sh +npm install rivetkit @rivetkit/react +``` + +### Create Backend Actor and Start Server + +Create your actor registry on the backend and start the server: + +```ts backend/index.ts +import { actor, setup } from "rivetkit"; + +export 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; + }, + }, +}); + +export const registry = setup({ + use: { counter }, +}); + +registry.start(); +``` + +### Create React Frontend + +Set up your React application: + +```tsx Counter.tsx +import { createRivetKit } from "@rivetkit/react"; +import { useState } from "react"; +import type { registry } from "./index"; + +const { useActor } = createRivetKit("http://localhost:6420"); + +function Counter() { + const [count, setCount] = useState(0); + + // Get or create a counter actor for the key "my-counter" + const counter = useActor({ + name: "counter", + key: ["my-counter"] + }); + + // Listen to realtime events + counter.useEvent("newCount", (x: number) => setCount(x)); + + const increment = async () => { + // Call actions + await counter.connection?.increment(1); + }; + + return ( +
+

Count: {count}

+ +
+ ); +} +``` + +```ts index.ts @hide +import { actor, setup } from "rivetkit"; + +export 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; + }, + }, +}); + +export const registry = setup({ + use: { counter }, +}); + +registry.start(); +``` + +For detailed information about the React client API, see the [React Client API Reference](/docs/clients/react). + +### Setup Vite Configuration + +Configure Vite for development: + +```ts vite.config.ts @nocheck +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [react()], + server: { + port: 5173, + }, +}) +``` + +### Run Your Application + +Start both the backend and frontend: + +**Terminal 1**: Start the backend + +```sh Node.js +npx tsx --watch backend/index.ts +``` + +```sh Bun +bun --watch backend/index.ts +``` + +```sh Deno +deno run --allow-net --allow-read --allow-env --watch backend/index.ts +``` + +**Terminal 2**: Start the frontend + +```sh Frontend +npx vite +``` + +Open `http://localhost:5173` in your browser. Try opening multiple tabs to see realtime sync in action. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Deploy + +## Configuration Options + +_Source doc path: /docs/actors/quickstart/react_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/quickstart/rust.md b/.agents/skills/ai-agent-workspace/reference/actors/quickstart/rust.md new file mode 100644 index 0000000..1e55471 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/quickstart/rust.md @@ -0,0 +1,249 @@ +# Rust Quickstart (Beta) + +> Source: `src/content/docs/actors/quickstart/rust.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/rust +> Description: Build a Rivet Actor in Rust + +--- +Rust support is in beta. The supported public Rust API is `rivetkit` and `rivetkit-client`; lower-level crates are internal implementation details and do not carry a stability guarantee. See the full API reference on [docs.rs/rivetkit](https://docs.rs/rivetkit), or the runnable [`hello-world-rust`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-rust) example. + +## Steps + +### Add Rivet + +Add the `rivetkit` crate and its companions: + +```sh +cargo add rivetkit anyhow async-trait +cargo add serde --features derive +cargo add tokio --features full +``` + +### Define Your Actor + +Put the actor in `src/lib.rs` so both your server and your client can share the same types. An actor is a type that implements `Actor`, plus one `Handles` implementation for each action. Persisted state lives in `type State`; ephemeral runtime state is just fields on your actor struct. + +```rust src/lib.rs +use std::{future::Future, pin::Pin, sync::Arc}; + +use async_trait::async_trait; +use rivetkit::prelude::*; +use serde::{Deserialize, Serialize}; + +type BoxFuture = Pin> + Send>>; + +pub struct Counter; + +#[derive(Default, Serialize, Deserialize)] +pub struct CounterState { + pub count: i64, +} + +#[derive(Serialize, Deserialize)] +pub struct Increment { + pub amount: i64, +} + +impl Action for Increment { + type Output = i64; + + const NAME: &'static str = "increment"; +} + +#[derive(Serialize, Deserialize)] +pub struct NewCount { + pub count: i64, +} + +impl Event for NewCount { + const NAME: &'static str = "newCount"; +} + +#[async_trait] +impl Actor for Counter { + type State = CounterState; + type Input = (); + type Actions = (Increment,); + type Events = (NewCount,); + type Queue = (); + type ConnParams = (); + type ConnState = (); + type Action = action::Raw; + + async fn create_state(_ctx: &Ctx, _input: Self::Input) -> Result { + Ok(CounterState::default()) + } + + async fn create(_ctx: &Ctx) -> Result { + Ok(Self) + } +} + +impl Handles for Counter { + type Future = BoxFuture; + + fn handle(self: Arc, ctx: Ctx, action: Increment) -> Self::Future { + Box::pin(async move { + let count = { + let mut state = ctx.state_mut(); + state.count += action.amount; + state.count + }; + ctx.emit(NewCount { count })?; + Ok(count) + }) + } +} + +pub fn registry() -> Registry { + let mut registry = Registry::new(); + registry.register_actor::("counter"); + registry +} +``` + +### Serve The Registry + +Your `src/main.rs` just starts the registry from the library: + +```rust src/main.rs +#[tokio::main] +async fn main() -> anyhow::Result<()> { + counter::registry().start().await +} +``` + +Replace `counter` with your crate name (the package `name` in `Cargo.toml`, with dashes as underscores). + +### Run The Server + +The Rust runtime connects to the Rivet Engine. Setting `RIVETKIT_ENGINE_AUTO_DOWNLOAD=1` lets the runtime download and cache a matching engine binary the first time you run, so there is nothing else to install: + +```sh +RIVETKIT_ENGINE_AUTO_DOWNLOAD=1 cargo run +``` + +Your server now connects to the Rivet Engine on `http://localhost:6420`. Clients connect directly to the engine on this port. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +Already have an engine binary? Set `RIVET_ENGINE_BINARY_PATH=/path/to/rivet-engine` to point at it instead. If you are working inside the [Rivet monorepo](https://github.com/rivet-dev/rivet), a local `cargo build -p rivet-engine` is discovered automatically from `target/debug`. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend: + +### Rust + +Add a `src/bin/client.rs` that imports the same actor types from your library. There is no need to redefine the actor on the client. + +```rust src/bin/client.rs +use counter::{Counter, Increment, NewCount}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + let count = counter.send(Increment { amount: 3 }).await?; + println!("New count: {count}"); + + let connection = counter.connect(); + connection + .on::(|event| println!("Count changed: {}", event.count)) + .await; + connection.send(Increment { amount: 1 }).await?; + + Ok(()) +} +``` + +With the server still running, start the client in another terminal: + +```sh +cargo run --bin client +``` + +See the [`hello-world-rust`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-rust) example for a complete runnable counter. + +### TypeScript + +A TypeScript client can call your Rust actor by name through the same engine. Actor and action names are resolved at runtime, so the client is untyped here: + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient("http://localhost:6420"); + +const counter = client.counter.getOrCreate(["my-counter"]); + +const counterConnection = counter.connect(); +counterConnection.on("newCount", (event) => { + console.log("Event count:", event.count); +}); + +const count = await counterConnection.increment(3); +console.log("New count:", count); + +await counterConnection.increment(1); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### React + +```tsx Counter.tsx @nocheck +import { createRivetKit } from "@rivetkit/react"; +import { useState } from "react"; + +const { useActor } = createRivetKit("http://localhost:6420"); + +function Counter() { + const [count, setCount] = useState(0); + + const counter = useActor({ + name: "counter", + key: ["my-counter"], + }); + + const increment = async () => { + await counter.connection?.increment(1); + }; + + counter.useEvent("newCount", (event) => { + setCount(event.count); + }); + + return ( +
+

Count: {count}

+ +
+ ); +} +``` + +See the [React documentation](/docs/clients/react) for more information. + +### Deploy + +## Next Steps + + +- [API Reference](https://docs.rs/rivetkit) — Full `rivetkit` crate documentation on docs.rs. + + +- [Actions](/docs/actors/actions) — Define the RPC surface clients call on your actor. + + +- [State](/docs/actors/state) — Persist and load actor state across sleeps and restarts. + + +- [Events](/docs/actors/events) — Broadcast realtime updates to connected clients. + +_Source doc path: /docs/actors/quickstart/rust_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/quickstart/supabase.md b/.agents/skills/ai-agent-workspace/reference/actors/quickstart/supabase.md new file mode 100644 index 0000000..eb97fe7 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/quickstart/supabase.md @@ -0,0 +1,96 @@ +# Supabase Functions Quickstart + +> Source: `src/content/docs/actors/quickstart/supabase.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/supabase +> Description: Set up a Rivet project locally targeting Supabase Edge Functions. + +--- +Set up a Rivet project locally that runs on Supabase Edge Functions. The `@rivetkit/supabase` package wires the WebAssembly runtime for you. + +Prefer to start from a complete project? See the runnable [`hello-world-supabase-functions`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-supabase-functions) example. + +## Steps + +### Prerequisites + +- [Node.js](https://nodejs.org/) +- [Supabase CLI](https://supabase.com/docs/guides/cli) +- Docker, for Supabase's local Edge Runtime + +The CLI runs the local Rivet engine as a bundled native binary, so Docker is only needed for Supabase itself. A Supabase project is only needed to deploy. + +### Create the Function + +```sh +npx supabase functions new rivet +``` + +Add the packages used by the function: + +```sh +npm install rivetkit @rivetkit/supabase +``` + +### Configure the Function + +Call `serve` from `@rivetkit/supabase`. It loads the WebAssembly runtime and serves the Rivet handler. + +```ts supabase/functions/rivet/index.ts @nocheck +import { actor } from "rivetkit"; +import { serve, setup } from "@rivetkit/supabase"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +// `setup` returns a typed registry, so a client can type itself with +// `typeof registry`. +export const registry = setup({ use: { counter } }); + +await serve(registry); +``` + +### Run Locally + +Start Rivet. The CLI runs the local engine, spawns `supabase functions serve` for you, and populates the connection values: + +```sh +npx @rivetkit/cli dev --provider supabase +``` + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Call the Actor + +Connect to your actor from a client. This connects directly to the local engine on `http://localhost:6420`: + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./supabase/functions/rivet/index"; + +const client = createClient("http://localhost:6420"); + +const counter = client.counter.getOrCreate(["my-counter"]); +const count = await counter.increment(3); +console.log("New count:", count); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### Deploy + +Ready to ship? See [Deploying to Supabase Functions](/docs/deploy/supabase). + +## Related + +- [Quickstart](/docs/actors/quickstart) +- [Deploying to Supabase Functions](/docs/deploy/supabase) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/actors/quickstart/supabase_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/request-handler.md b/.agents/skills/ai-agent-workspace/reference/actors/request-handler.md new file mode 100644 index 0000000..cfd49b3 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/request-handler.md @@ -0,0 +1,256 @@ +# Low-Level HTTP Request Handler + +> Source: `src/content/docs/actors/request-handler.mdx` +> Canonical URL: https://rivet.dev/docs/actors/request-handler +> Description: Actors can handle HTTP requests through the `onRequest` handler. + +--- +For most use cases, [actions](/docs/actors/actions) provide high-level API powered by HTTP that's easier to work with than low-level HTTP. However, low-level handlers are required when implementing custom use cases or integrating external libraries that need direct access to the underlying HTTP `Request`/`Response` objects or WebSocket connections. + +## Handling HTTP Requests + +The `onRequest` handler processes HTTP requests sent to your actor. It receives the actor context and a standard `Request` object and returns a `Response` object. + +### Raw HTTP + +```typescript +import { actor } from "rivetkit"; + +export const counterActor = actor({ + state: { + count: 0, + }, + // WinterTC compliant - accepts standard Request and returns standard Response + onRequest: (c, request) => { + const url = new URL(request.url); + + if (request.method === "GET" && url.pathname === "/count") { + return Response.json({ count: c.state.count }); + } + + if (request.method === "POST" && url.pathname === "/increment") { + c.state.count++; + return Response.json({ count: c.state.count }); + } + + return new Response("Not Found", { status: 404 }); + }, + actions: {} +}); +``` + +### Hono + +```typescript +import { actor, ActorContextOf } from "rivetkit"; +import { Hono } from "hono"; + +// Define the actor first +const counterActor = actor({ + state: { count: 0 }, + actions: {} +}); + +// Build router with typed context +function buildRouter(actorCtx: ActorContextOf) { + const app = new Hono(); + + app.get("/count", (honoCtx) => { + return honoCtx.json({ count: actorCtx.state.count }); + }); + + app.post("/increment", (honoCtx) => { + actorCtx.state.count++; + return honoCtx.json({ count: actorCtx.state.count }); + }); + + return app; +} + +// Define the full actor with onRequest +export const counterActorWithRouter = actor({ + state: { count: 0 }, + vars: { app: null as Hono | null }, + createVars: () => ({ + app: null as Hono | null + }), + onRequest: async (c, request) => { + // Build router lazily + const app = buildRouter(c as ActorContextOf); + return await app.fetch(request); + }, + actions: {} +}); +``` + +See also the [raw fetch handler example](https://github.com/rivet-dev/rivet/tree/main/examples/raw-fetch-handler). + +## Sending Requests To Actors + +### Via RivetKit Client + +Use the `.fetch()` method on an actor handle to send HTTP requests to the actor's `onRequest` handler. This can be executed from either your frontend or backend. + +```typescript index.ts @hide +import { actor, setup } from "rivetkit"; + +export const counter = actor({ + state: { count: 0 }, + onRequest: (c, request) => { + if (request.method === "POST") c.state.count++; + return Response.json(c.state); + }, + actions: {} +}); + +export const registry = setup({ use: { counter } }); +registry.start(); +``` + +```typescript client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +const actor = client.counter.getOrCreate(["my-counter"]); + +// .fetch() is WinterTC compliant, it accepts standard Request and returns standard Response +const response = await actor.fetch("/"); +const data = await response.json(); +console.log(data); // { count: 0 } +``` + +### Via getGatewayUrl + +Use `.getGatewayUrl()` to get the raw gateway URL for the actor. This is useful when you need to use the URL with external tools or custom HTTP clients. + +```typescript index.ts @hide +import { actor, setup } from "rivetkit"; + +export const counter = actor({ + state: { count: 0 }, + onRequest: (c, request) => { + if (request.method === "POST") c.state.count++; + return Response.json(c.state); + }, + actions: {} +}); + +export const registry = setup({ use: { counter } }); +registry.start(); +``` + +```typescript client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +const actor = client.counter.getOrCreate(["my-counter"]); + +// Get the raw gateway URL +const gatewayUrl = await actor.getGatewayUrl(); +// gatewayUrl = "https://...rivet.dev/..." + +// Use with native fetch +const response = await fetch(`${gatewayUrl}/request/`); +const data = await response.json(); +console.log(data); // { count: 0 } +``` + +### Via HTTP API + +This handler can be accessed with raw HTTP using `https://api.rivet.dev/gateway/{actorId}/request/{...path}`. + +For example, to call `POST /increment` on the counter actor above: + +```typescript +// Replace with your actor ID and token +const actorId = "your-actor-id"; +const token = "your-token"; + +const response = await fetch( + `https://api.rivet.dev/gateway/${actorId}/request/increment`, + { + method: "POST", + headers: { + "x-rivet-token": token, + }, + } +); +const data = await response.json(); +console.log(data); // { count: 1 } +``` + +```bash +curl -X POST "https://api.rivet.dev/gateway/{actorId}/request/increment" \ + -H "x-rivet-token: {token}" +``` + +The request is routed to the actor's `onRequest` handler where: + +- `request.method` is `"POST"` +- `request.url` ends with `/increment` (the path after `/request/`) +- Headers, body, and other request properties are passed through unchanged + +See the [HTTP API reference](/docs/actors/http-api) for more information on HTTP routing and authentication. + +### Via Proxying Requests + +You can proxy HTTP requests from your own server to actor handlers using the RivetKit client. This is useful when you need to add custom authentication, rate limiting, or request transformation before forwarding to actors. + +```typescript +import { Hono } from "hono"; +import { createClient } from "rivetkit/client"; +import { serve } from "@hono/node-server"; + +const client = createClient(); + +const app = new Hono(); + +// Proxy requests to actor's onRequest handler +app.all("/actors/:id/:path{.*}", async (c) => { + const actorId = c.req.param("id"); + const actorPath = (c.req.param("path") || ""); + + // Rewrite the incoming request to the actor-relative path, preserving + // method, headers, and body + const url = new URL(actorPath, "http://actor"); + const actorRequest = new Request(url, c.req.raw); + + // Forward the rewritten Request to the actor's onRequest handler + const actor = client.counter.get(actorId); + return await actor.fetch(actorRequest); +}); + +serve(app); +``` + +## Connection & Lifecycle Hooks + +`onRequest` will trigger the `onBeforeConnect`, `onConnect`, and `onDisconnect` hooks. Read more about [lifecycle hooks](/docs/actors/lifecycle). + +Requests in flight will be listed in `c.conns`. Read more about [connections](/docs/actors/connections). + +## WinterTC Compliance + +The `onRequest` handler is WinterTC compliant and will work with existing libraries using the standard `Request` and `Response` types. + +## Limitations + +- Does not support streaming responses & server-sent events at the moment. See the [tracking issue](https://github.com/rivet-dev/rivet/issues/3529). +- `OPTIONS` requests currently are handled by Rivet and are not passed to `onRequest` + +## Advanced + +### Skip Ready Wait + +Requests are normally held at the gateway until the actor is ready. Pass `skipReadyWait: true` on `handle.fetch()` to deliver immediately, including while the actor is still starting or in the [sleep grace period](/docs/actors/lifecycle#shutdown-sequence). See [Skip Ready Wait](/docs/clients/javascript#skip-ready-wait) for details. + +## API Reference + +- [`RequestContext`](/typedoc/interfaces/rivetkit.mod.RequestContext.html) - Context for HTTP request handlers +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining request handlers + +_Source doc path: /docs/actors/request-handler_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/scaling.md b/.agents/skills/ai-agent-workspace/reference/actors/scaling.md new file mode 100644 index 0000000..b597115 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/scaling.md @@ -0,0 +1,10 @@ +# Scaling & Concurrency + +> Source: `src/content/docs/actors/scaling.mdx` +> Canonical URL: https://rivet.dev/docs/actors/scaling +> Description: This page has moved to [design patterns](/docs/actors/design-patterns). + +--- + + +_Source doc path: /docs/actors/scaling_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/schedule.md b/.agents/skills/ai-agent-workspace/reference/actors/schedule.md new file mode 100644 index 0000000..2c491c1 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/schedule.md @@ -0,0 +1,103 @@ +# Actor Scheduling + +> Source: `src/content/docs/actors/schedule.mdx` +> Canonical URL: https://rivet.dev/docs/actors/schedule +> Description: Schedule actor actions in the future with persistent timers that survive restarts and upgrades. + +--- +Scheduling is used to trigger events in the future. The actor scheduler is like `setTimeout`, except the timeout will persist even if the actor restarts, upgrades, or crashes. + +For a pattern guide to durable recurring jobs, see the cookbook: [Cron Jobs and Scheduled Tasks](/cookbook/cron-jobs/). + +## Use Cases + +Scheduling is helpful for long-running timeouts like month-long billing periods or account trials. + +## Scheduling + +### `c.schedule.after(duration, actionName, ...args)` + +Schedules a function to be executed after a specified duration. This function persists across actor restarts, upgrades, or crashes. + +Parameters: + +- `duration` (number): The delay in milliseconds. +- `actionName` (string): The name of the action to be executed. +- `...args` (unknown[]): Additional arguments to pass to the function. + +### `c.schedule.at(timestamp, actionName, ...args)` + +Schedules a function to be executed at a specific timestamp. This function persists across actor restarts, upgrades, or crashes. + +Parameters: + +- `timestamp` (number): The exact time in milliseconds since the Unix epoch when the function should be executed. +- `actionName` (string): The name of the action to be executed. +- `...args` (unknown[]): Additional arguments to pass to the function. + +## Full Example + +```typescript +import { actor } from "rivetkit"; + +interface Reminder { + userId: string; + message: string; + scheduledFor: number; +} + +interface ReminderState { + reminders: Record; +} + +// Mock email function +function sendEmail(to: string, message: string) { + console.log(`Sending email to ${to}: ${message}`); +} + +const reminderService = actor({ + state: { reminders: {} } as ReminderState, + + actions: { + setReminder: async (c, userId: string, message: string, delayMs: number) => { + const reminderId = crypto.randomUUID(); + + // Store the reminder in state + c.state.reminders[reminderId] = { + userId, + message, + scheduledFor: Date.now() + delayMs + }; + + // Schedule the sendReminder action to run after the delay + await c.schedule.after(delayMs, "sendReminder", reminderId); + + return { reminderId }; + }, + + sendReminder: (c, reminderId: string) => { + const reminder = c.state.reminders[reminderId]; + if (!reminder) return; + + // Send reminder notification + if (c.conns.size > 0) { + // Send the reminder to all connected clients + for (const conn of c.conns.values()) { + conn.send("reminder", { + message: reminder.message, + scheduledAt: reminder.scheduledFor + }); + } + } else { + // User is offline, send an email notification + sendEmail(reminder.userId, reminder.message); + } + + // Clean up the processed reminder + delete c.state.reminders[reminderId]; + } + } +}); +``` + +_Source doc path: /docs/actors/schedule_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/sharing-and-joining-state.md b/.agents/skills/ai-agent-workspace/reference/actors/sharing-and-joining-state.md new file mode 100644 index 0000000..1fe0683 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/sharing-and-joining-state.md @@ -0,0 +1,10 @@ +# Sharing and Joining State + +> Source: `src/content/docs/actors/sharing-and-joining-state.mdx` +> Canonical URL: https://rivet.dev/docs/actors/sharing-and-joining-state +> Description: This page has moved to [design patterns](/docs/actors/design-patterns). + +--- + + +_Source doc path: /docs/actors/sharing-and-joining-state_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/sqlite-drizzle.md b/.agents/skills/ai-agent-workspace/reference/actors/sqlite-drizzle.md new file mode 100644 index 0000000..81411c9 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/sqlite-drizzle.md @@ -0,0 +1,260 @@ +# SQLite + Drizzle + +> Source: `src/content/docs/actors/sqlite-drizzle.mdx` +> Canonical URL: https://rivet.dev/docs/actors/sqlite-drizzle +> Description: Use Drizzle ORM with embedded SQLite in Rivet Actors. + +--- +Use Drizzle when you want typed schema, typed queries, and generated migrations on top of actor-local SQLite. + +For a high-level overview of where to store actor data, see [State & Storage](/docs/actors/state). For a worked multi-tenant pattern, see the cookbook: [Database per Tenant](/cookbook/per-tenant-database/). + +## What is Drizzle good for? + +- **Typed schema**: define tables in TypeScript and get typed query results. +- **Typed query builder**: write SQL-like queries with autocompletion. +- **Migration workflow**: generate SQL migration files from schema changes. +- **Raw SQL escape hatch**: use `c.db.execute(...)` for direct SQLite when needed. + +## Project structure + +Use one folder per actor database: + +```txt +src/ + actors/ + todo-list/ + index.ts + schema.ts + drizzle.config.ts + drizzle/ + 0000_init.sql + migrations.js + migrations.d.ts + meta/ + _journal.json +``` + +- `index.ts` is the actor implementation. +- `drizzle/` holds the SQL migrations (`*.sql`) and `meta/_journal.json` generated by `drizzle-kit`. +- `migrations.js` is a small RivetKit glue file you maintain by hand. It imports the journal and each `*.sql` file and exports a `{ journal, migrations }` object keyed by migration (for example `m0000`). Add a new entry here whenever `db:generate` produces a new migration. +- Commit the generated migration files and `migrations.js` to source control. + +## Basic setup + +```json package.json +{ + "scripts": { + "db:generate": "find src/actors -name drizzle.config.ts -exec drizzle-kit generate --config {} \\;" + }, + "dependencies": { + "rivetkit": "*", + "drizzle-orm": "^0.44.2" + }, + "devDependencies": { + "drizzle-kit": "^0.31.2" + } +} +``` + +```ts vite.config.ts @nocheck +import { defineConfig, type Plugin } from "vite"; +import { readFileSync } from "node:fs"; + +function sqlRawPlugin(): Plugin { + return { + name: "sql-raw", + transform(_code, id) { + if (id.endsWith(".sql")) { + const content = readFileSync(id, "utf-8"); + return { code: `export default ${JSON.stringify(content)};` }; + } + }, + }; +} + +export default defineConfig({ + plugins: [sqlRawPlugin()], +}); +``` + +```ts schema.ts +import { integer, sqliteTable, text } from "rivetkit/db/drizzle"; + +export const todos = sqliteTable("todos", { + id: integer("id").primaryKey({ autoIncrement: true }), + title: text("title").notNull(), + createdAt: integer("created_at").notNull(), +}); + +export const schema = { todos }; +``` + +```ts drizzle.config.ts @nocheck +import { defineConfig } from "rivetkit/db/drizzle"; + +export default defineConfig({ + schema: "./src/actors/todo-list/schema.ts", + out: "./src/actors/todo-list/drizzle", +}); +``` + +```sql 0000_init.sql +CREATE TABLE `todos` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `title` text NOT NULL, + `created_at` integer NOT NULL +); +``` + +```json _journal.json +{ + "version": "7", + "dialect": "sqlite", + "entries": [ + { + "idx": 0, + "version": "7", + "when": 1735689600000, + "tag": "0000_init", + "breakpoints": true + } + ] +} +``` + +```ts migrations.js @nocheck +import journal from "./meta/_journal.json"; +import m0000 from "./0000_init.sql"; + +export default { + journal, + migrations: { + m0000, + }, +}; +``` + +```ts index.ts @nocheck +import { actor } from "rivetkit"; +import { db } from "rivetkit/db/drizzle"; +import migrations from "./drizzle/migrations.js"; +import { schema, todos } from "./schema.ts"; + +export const todoList = actor({ + db: db({ schema, migrations }), + actions: { + addTodo: async (c, title: string) => { + const rows = await c.db + .insert(todos) + .values({ title, createdAt: Date.now() }) + .returning(); + return rows[0]; + }, + getTodos: async (c) => { + return await c.db.select().from(todos).orderBy(todos.id); + }, + getTodoCount: async (c) => { + const rows = (await c.db.execute( + "SELECT COUNT(*) AS count FROM todos", + )) as { count: number }[]; + return rows[0]?.count ?? 0; + }, + }, +}); +``` + +```ts index.ts @nocheck +import { setup } from "rivetkit"; +import { todoList } from "./todo-list/index.ts"; + +export const registry = setup({ use: { todoList } }); +registry.start(); +``` + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const todoList = client.todoList.getOrCreate(["main"]); + +await todoList.addTodo("Write Drizzle docs"); + +const todos = await todoList.getTodos(); +const count = await todoList.getTodoCount(); + +console.log(todos, count); +``` + +## Queries + +### Query builder + +Use Drizzle's typed query APIs for most reads and writes. + +```ts @nocheck +import { eq } from "drizzle-orm"; + +await c.db.insert(todos).values({ title, createdAt: Date.now() }); + +const rows = await c.db + .select() + .from(todos) + .where(eq(todos.title, title)); +``` + +### Raw SQL + +`rivetkit/db/drizzle` also exposes raw SQLite access through `c.db.execute(...)`. + +```ts @nocheck +await c.db.execute( + "CREATE INDEX IF NOT EXISTS idx_todos_created_at ON todos(created_at)", +); +``` + +## Queues + +Use queues for ordered mutations and keep actions read-only. Import `queue` alongside `actor` from `rivetkit`. + +```ts @nocheck +import { actor, queue } from "rivetkit"; + +// ... + +queues: { + addTodo: queue<{ title: string }>(), +}, +run: async (c) => { + for await (const message of c.queue.iter()) { + if (message.name === "addTodo") { + await c.db.insert(todos).values({ + title: message.body.title, + createdAt: Date.now(), + }); + } + } +}, +actions: { + getTodos: async (c) => await c.db.select().from(todos), +}, +``` + +## Recommendations + +- Prefer Drizzle query APIs for app code and use raw SQL for advanced SQLite features. +- Keep one `drizzle.config.ts` per actor folder. +- Re-run `db:generate` after schema changes and commit generated migration files. +- Use queues for writes and actions for reads. +- Keep related writes in one action or queue message to reduce interleaved query risk. + +## Read more + +- [Drizzle SQLite quickstart](https://orm.drizzle.team/docs/get-started-sqlite) +- [Drizzle `drizzle-kit generate`](https://orm.drizzle.team/docs/drizzle-kit-generate) +- [Drizzle + Cloudflare D1](https://orm.drizzle.team/docs/deploy-cloudflare-d1) +- [Drizzle + Cloudflare Durable Objects](https://orm.drizzle.team/docs/deploy-cloudflare-do) +- [Cloudflare Durable Objects SQLite storage](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/) + +_Source doc path: /docs/actors/sqlite-drizzle_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/sqlite.md b/.agents/skills/ai-agent-workspace/reference/actors/sqlite.md new file mode 100644 index 0000000..d7a3465 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/sqlite.md @@ -0,0 +1,267 @@ +# SQLite + +> Source: `src/content/docs/actors/sqlite.mdx` +> Canonical URL: https://rivet.dev/docs/actors/sqlite +> Description: Use embedded SQLite in Rivet Actors with raw SQL queries. + +--- +For a high-level overview of where to store actor data, including when to use `c.state` versus SQLite, see [State & Storage](/docs/actors/state). For a worked multi-tenant pattern, see the cookbook: [Database per Tenant](/cookbook/per-tenant-database/). + +## What is SQLite? + +- **Database per actor**: each actor instance has its own SQLite database, scoped to that actor. +- **High performance**: Rivet Actors keep compute and storage together, so queries avoid network round trips to an external database. +- **Larger-than-memory storage**: SQLite stores data on disk, so you can work with datasets that do not fit in actor memory. +- **Embedded relational database**: use tables, indexes, and SQL queries directly inside actor logic. + +### SQLite features + +- **Indexes**: speed up lookups on frequently queried fields. +- **Search and filtering**: use `WHERE`, `LIKE`, and `ORDER BY` instead of manual in-memory loops. +- **Relationships**: use multiple tables and `JOIN` queries for connected data. +- **Constraints**: use primary keys, unique constraints, and foreign keys for data integrity. +- **Transactions**: apply multiple writes atomically when changes must stay consistent. + +## Raw SQL vs ORM (Drizzle) + +Rivet supports both raw SQL and [Drizzle](https://orm.drizzle.team/) for actor-local SQLite. + +Use **raw SQL** when you want direct query control and minimal abstraction. + +```ts @nocheck +await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); +const rows = await c.db.execute("SELECT id, title FROM todos ORDER BY id DESC"); +``` + +Use **Drizzle** when you want typed schema and typed query APIs. + +```ts @nocheck +await c.vars.drizzle.insert(todos).values({ title }); +const rows = await c.vars.drizzle.select().from(todos).orderBy(desc(todos.id)); +``` + +You can mix both in the same actor. + +For Drizzle setup, see [SQLite + Drizzle](/docs/actors/sqlite-drizzle). + +## Basic setup + +Define `db: db({ onMigrate })` on your actor, create your schema in `onMigrate`, and execute SQL with `c.db.execute(...)`. + +RivetKit wraps `onMigrate` in a SQLite savepoint, so migration steps are atomic. If `onMigrate` throws, all SQL run by that hook is rolled back before the actor starts. + +```ts index.ts +import { actor, setup } from "rivetkit"; +import { db } from "rivetkit/db"; + +export const todoList = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL + ); + `); + + await db.execute(` + CREATE TABLE IF NOT EXISTS comments ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + todo_id INTEGER NOT NULL, + body TEXT NOT NULL, + FOREIGN KEY(todo_id) REFERENCES todos(id) + ); + `); + }, + }), + actions: { + addTodo: async (c, title: string) => { + await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); + }, + addComment: async (c, todoId: number, body: string) => { + await c.db.execute( + "INSERT INTO comments (todo_id, body) VALUES (?, ?)", + todoId, + body, + ); + }, + getTodos: async (c) => { + return (await c.db.execute( + "SELECT id, title FROM todos ORDER BY id DESC", + )) as { + id: number; + title: string; + }[]; + }, + }, +}); + +export const registry = setup({ use: { todoList } }); +registry.start(); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.todoList.getOrCreate(["main"]); + +await handle.addTodo("Write SQLite docs"); +await handle.addTodo("Ship docs update"); + +const todos = await handle.getTodos(); +console.log(todos); +``` + +## Queries + +`c.db.execute(...)` returns an array of row objects for `SELECT` queries. + +```ts @nocheck +const rows = await c.db.execute( + "SELECT id, title FROM todos WHERE title LIKE ?", + `%${query}%`, +); +``` + +### Parameterized queries + +Use `?` placeholders for dynamic values and pass parameters in order after the SQL string. + +```ts @nocheck +await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); +``` + +You can also use named SQLite bindings by passing a single properties object. + +```ts @nocheck +const rows = await c.db.execute( + "SELECT id, title FROM todos WHERE title = :title", + { title: "Write SQLite docs" }, +); +``` + +### Transactions + +Use transactions when multiple writes must succeed or fail together. + +- Start with `BEGIN`. +- End with `COMMIT` if all queries succeed. +- On error, run `ROLLBACK` and rethrow. +- A transaction is global for the entire shared `c.db` connection. Be careful with other interleaved queries. + +```ts @nocheck +await c.db.execute("BEGIN"); + +try { + await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); + await c.db.execute( + "INSERT INTO comments (todo_id, body) VALUES (last_insert_rowid(), ?)", + body, + ); + await c.db.execute("COMMIT"); +} catch (error) { + await c.db.execute("ROLLBACK"); + throw error; +} +``` + +## Queues + +It's recommended to use queues for mutations and actions for read-only queries. This is the same code structure as the basic setup, but mutation writes are routed through queues. + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; +import { db } from "rivetkit/db"; + +export const todoList = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL + ); + `); + + await db.execute(` + CREATE TABLE IF NOT EXISTS comments ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + todo_id INTEGER NOT NULL, + body TEXT NOT NULL, + FOREIGN KEY(todo_id) REFERENCES todos(id) + ); + `); + }, + }), + queues: { + addTodo: queue<{ title: string }>(), + addComment: queue<{ todoId: number; body: string }>(), + }, + run: async (c) => { + for await (const message of c.queue.iter()) { + if (message.name === "addTodo") { + await c.db.execute("INSERT INTO todos (title) VALUES (?)", message.body.title); + } else if (message.name === "addComment") { + await c.db.execute( + "INSERT INTO comments (todo_id, body) VALUES (?, ?)", + message.body.todoId, + message.body.body, + ); + } + } + }, + actions: { + getTodos: async (c) => { + return (await c.db.execute( + "SELECT id, title FROM todos ORDER BY id DESC", + )) as { + id: number; + title: string; + }[]; + }, + }, +}); + +export const registry = setup({ use: { todoList } }); +registry.start(); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.todoList.getOrCreate(["main"]); + +await handle.send("addTodo", { title: "Write SQLite docs" }); +await handle.send("addTodo", { title: "Ship docs update" }); + +const todos = await handle.getTodos(); +console.log(todos); +``` + +## Debugging + +- `GET /inspector/summary` includes `isDatabaseEnabled` so you can confirm SQLite is configured. +- `GET /inspector/database/schema` returns the tables and views discovered in the actor's SQLite database. +- `GET /inspector/database/rows?table=...&limit=100&offset=0` returns paged rows for a specific table or view. +- `POST /inspector/database/execute` lets you run ad-hoc SQL for debugging and data fixes with positional `args` or named `properties`. +- Keep a small read-only action for quick query verification while debugging. +- In non-dev mode, inspector endpoints require authorization. + +## Recommendations + +- Keep schema creation and migration steps in `onMigrate`; RivetKit runs them atomically inside a SQLite savepoint. +- Use `?` placeholders for dynamic values. +- Prefer queue-driven writes for ordered or background work. +- Use transactions for related multi-step mutations when atomicity matters. + +## Read more + +- [SQLite + Drizzle in Rivet Actors](/docs/actors/sqlite-drizzle) +- [SQLite docs](https://sqlite.org/docs.html) +- [SQLite SQL language reference](https://sqlite.org/lang.html) + +_Source doc path: /docs/actors/sqlite_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/state.md b/.agents/skills/ai-agent-workspace/reference/actors/state.md new file mode 100644 index 0000000..dc2ca27 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/state.md @@ -0,0 +1,437 @@ +# In-Memory State + +> Source: `src/content/docs/actors/state.mdx` +> Canonical URL: https://rivet.dev/docs/actors/state +> Description: Actors store state in memory for instant reads and writes. State can be persisted automatically or kept ephemeral. + +--- +## Types of State + +There are three ways to store data in an actor, depending on what it looks like and whether it needs to survive restarts. + +### Durable + +Simple, serializable data on `c.state` that is automatically persisted and restored across restarts. The default starting point. + +```typescript Basic +import { actor } from "rivetkit"; + +const counter = actor({ + // Constant initial state + state: { count: 0 }, + + actions: { + get: (c) => c.state.count, + + // Update state, changes are persisted automatically + increment: (c) => { + c.state.count += 1; + return c.state.count; + } + } +}); +``` + +```typescript Dynamic init +import { actor } from "rivetkit"; + +interface CounterState { + count: number; +} + +const counter = actor({ + // Compute the initial state when the actor is created + createState: (): CounterState => ({ count: 0 }), + + actions: { + get: (c) => c.state.count, + + increment: (c) => { + c.state.count += 1; + return c.state.count; + } + } +}); +``` + +```typescript With input +import { actor } from "rivetkit"; + +interface CounterState { + count: number; +} + +const counter = actor({ + // Compute the initial state from input passed at creation + createState: (c, input: { startingCount: number }): CounterState => ({ + count: input.startingCount, + }), + + actions: { + get: (c) => c.state.count, + + increment: (c) => { + c.state.count += 1; + return c.state.count; + } + } +}); +``` + +### Ephemeral + +Live objects on `c.vars` like database connections, API clients, and event emitters, or data loaded from an external source. Never persisted. + +```typescript Basic +import { actor } from "rivetkit"; + +const counter = actor({ + state: { count: 0 }, + + // Constant ephemeral value, reset each time the actor starts + vars: { lastAccessedAt: 0 }, + + actions: { + increment: (c) => { + // Read and write the ephemeral var + c.vars.lastAccessedAt = Date.now(); + return ++c.state.count; + }, + + getLastAccessed: (c) => c.vars.lastAccessedAt + } +}); +``` + +```typescript Dynamic init +import { actor } from "rivetkit"; + +const chatRoom = actor({ + state: { messages: [] as string[] }, + + // Build a non-serializable emitter on each start + createVars: () => ({ emitter: createEventEmitter() }), + + actions: { + broadcast: (c, text: string) => { + c.state.messages.push(text); + // Use the ephemeral emitter + c.vars.emitter.emit("message", text); + } + } +}); + +// Mock event emitter for demonstration +interface EventEmitter { + on: (event: string, callback: (data: unknown) => void) => void; + emit: (event: string, data: unknown) => void; +} + +function createEventEmitter(): EventEmitter { + const listeners: Record void)[]> = {}; + return { + on: (event, callback) => { + listeners[event] = listeners[event] || []; + listeners[event].push(callback); + }, + emit: (event, data) => { + listeners[event]?.forEach(cb => cb(data)); + } + }; +} +``` + +```typescript @nocheck External database +import { actor } from "rivetkit"; +import { Pool } from "pg"; + +// One shared pool for the whole process, created once and reused by every actor +const pool = new Pool({ connectionString: process.env.DATABASE_URL }); + +const userActor = actor({ + state: { profile: null as Record | null }, + + // Load this actor's row from the shared pool on each start + createVars: async (c) => { + const { rows } = await pool.query("SELECT * FROM users WHERE id = $1", [c.key[0]]); + return { profile: rows[0] }; + }, + + actions: { + updateEmail: async (c, email: string) => { + await pool.query("UPDATE users SET email = $1 WHERE id = $2", [email, c.key[0]]); + } + } +}); +``` + +### SQLite + +Rivet also provides an embedded SQLite database (`c.db`) for when your data needs to be queried, requires safe schema migrations, or grows too large to hold in memory. See [SQLite](/docs/actors/sqlite). + +```typescript @nocheck Basic +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +const todoList = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL + ); + `); + }, + }), + + actions: { + add: async (c, title: string) => { + await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); + }, + + list: async (c) => { + return (await c.db.execute( + "SELECT id, title FROM todos ORDER BY id DESC", + )) as { id: number; title: string }[]; + }, + }, +}); +``` + +```typescript @nocheck Load into memory +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +const counter = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS counter ( + id INTEGER PRIMARY KEY CHECK (id = 1), + count INTEGER NOT NULL + ); + `); + await db.execute("INSERT OR IGNORE INTO counter (id, count) VALUES (1, 0)"); + }, + }), + + // Load the count from SQLite into memory on every start + createVars: async (c) => { + const rows = (await c.db.execute( + "SELECT count FROM counter WHERE id = 1", + )) as { count: number }[]; + return { count: rows[0].count }; + }, + + actions: { + get: (c) => c.vars.count, + + increment: async (c) => { + // Update the in-memory value and write it back to SQLite + c.vars.count += 1; + await c.db.execute("UPDATE counter SET count = ? WHERE id = 1", c.vars.count); + return c.vars.count; + }, + }, +}); +``` + +## State Isolation + +Each actor's state is fully isolated. Other actors and clients can't touch it directly; all reads and writes go through the actor's own [Actions](/docs/actors/actions). To share state across actors, see [sharing and joining state](/docs/actors/sharing-and-joining-state). + +## Durable State + +`c.state` lives in memory and is persisted automatically, so reads and writes have no added latency while the data still survives sleeps, restarts, upgrades, and crashes. Use it for small, simple values like counters, flags, and small maps. + +`createState` runs once when the actor is first created. On later starts, state is loaded from storage instead of recreated. See [Lifecycle](/docs/actors/lifecycle). + +### When state saves + +Mutating `c.state` schedules a save automatically. Rapid mutations are batched into a single write on a throttle (`stateSaveInterval`, default 1 second). Reads never trigger a save, saves aren't tied to action or handler boundaries, and state is also flushed when the actor sleeps or shuts down. + +To force a save mid-action, call `c.saveState()`: + +- `c.saveState({ immediate: true })` writes immediately and resolves once the write completes. +- `c.saveState()` schedules a throttled save and returns right away, without waiting for the write. + +Force an immediate save before a risky side effect so a crash can't lose progress: + +```typescript +import { actor } from "rivetkit"; + +const checkout = actor({ + state: { status: "pending" as "pending" | "charged" | "fulfilled" }, + + actions: { + fulfill: async (c) => { + c.state.status = "charged"; + // Persist before the side effect so a crash can't undo it + await c.saveState({ immediate: true }); + + await chargeExternalProvider(); + + c.state.status = "fulfilled"; + return c.state.status; + } + } +}); + +async function chargeExternalProvider() { + await new Promise((resolve) => setTimeout(resolve, 100)); +} +``` + +### Supported types + +State must be serializable. + +- `null`, `undefined`, `boolean`, `string`, `number`, `BigInt` +- `Date`, `RegExp`, `Error` +- `ArrayBuffer` and typed arrays (`Uint8Array`, `Int8Array`, `Float32Array`, etc.) +- `Map`, `Set`, `Array` +- Plain objects + +When data grows large or needs querying, store it in [Embedded SQLite](#embedded-sqlite) instead. + +## Ephemeral State + +`c.vars` holds data that exists only while the actor runs and is never saved. Use it for live objects that can't be serialized (connections, clients, emitters) or for data loaded from an external source. Most actors use both: `state` for durable data, `vars` for live objects. + +`createVars` runs on every actor start, unlike `createState` which runs once. That makes it the place to open connections and load data each time the actor wakes. + +### Runtime objects + +Build non-serializable objects in `createVars` and use them from actions: + +```typescript +import { actor } from "rivetkit"; + +const room = actor({ + state: { messages: [] as string[] }, + + // EventTarget can't be serialized, so it lives in vars + createVars: () => ({ events: new EventTarget() }), + + actions: { + send: (c, text: string) => { + c.state.messages.push(text); + c.vars.events.dispatchEvent(new CustomEvent("message", { detail: text })); + } + } +}); +``` + +### Loading from external sources + +Create the connection pool once at module scope and share it across all actors, then use `createVars` (which can be `async`) to load this actor's data from it on each start: + +```typescript @nocheck +import { actor } from "rivetkit"; +import { Pool } from "pg"; + +// One shared pool for the whole process, not one per actor +const pool = new Pool({ connectionString: process.env.DATABASE_URL }); + +const profile = actor({ + state: { cachedName: "" }, + + createVars: async (c) => { + const { rows } = await pool.query("SELECT * FROM users WHERE id = $1", [c.key[0]]); + return { user: rows[0] }; + }, + + actions: { + updateEmail: async (c, email: string) => { + await pool.query("UPDATE users SET email = $1 WHERE id = $2", [email, c.key[0]]); + } + } +}); +``` + +When the actor owns its data, prefer [durable state](#durable-state) or [SQLite](#embedded-sqlite), which need no external infrastructure. + +### Cleanup + +`vars` is dropped when the actor stops, but per-actor resources like timers, subscriptions, and dedicated connections aren't cleaned up for you. Release them in `onSleep` and `onDestroy`. A shared pool stays open for the whole process, so don't close it per actor. + +```typescript @nocheck +const poller = actor({ + state: { ticks: 0 }, + + // Per-actor timer started on each wake + createVars: (c) => ({ timer: setInterval(() => c.state.ticks++, 5000) }), + + // Clear it before the actor sleeps or is destroyed + onSleep: (c) => clearInterval(c.vars.timer), + onDestroy: (c) => clearInterval(c.vars.timer), + + actions: { /* ... */ } +}); +``` + +## Embedded SQLite + +`c.db` is a SQLite database scoped to each actor and stored on disk. Use it for queryable, relational, or larger-than-memory data. Because compute and storage live together, queries run locally with no network round trips. + +A common pattern is to treat SQLite as the source of truth and keep a working copy in `c.vars`: load rows in `createVars`, serve reads from memory, and write changes back to `c.db`. + +```typescript @nocheck +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +const leaderboard = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS scores ( + player TEXT PRIMARY KEY, + score INTEGER NOT NULL + ); + `); + }, + }), + + // Load the table into memory once per start + createVars: async (c) => { + const rows = (await c.db.execute("SELECT player, score FROM scores")) as { + player: string; + score: number; + }[]; + return { scores: new Map(rows.map((r) => [r.player, r.score])) }; + }, + + actions: { + top: (c) => [...c.vars.scores].sort((a, b) => b[1] - a[1]).slice(0, 10), + + record: async (c, player: string, score: number) => { + c.vars.scores.set(player, score); + // Write through to SQLite + await c.db.execute( + "INSERT INTO scores (player, score) VALUES (?, ?) ON CONFLICT(player) DO UPDATE SET score = ?", + player, score, score, + ); + }, + }, +}); +``` + +For the full query API, schema migrations, transactions, and the Drizzle ORM, see: + +- [SQLite](/docs/actors/sqlite): raw SQL against the embedded per-actor database. +- [SQLite + Drizzle](/docs/actors/sqlite-drizzle): typed schema and query APIs. + +## Debugging + +- `GET /inspector/state` returns the actor's current state and `isStateEnabled`. +- `PATCH /inspector/state` lets you set state directly while debugging. +- In non-dev mode, inspector endpoints require authorization. + +## API Reference + +- [`CreateContext`](/typedoc/types/rivetkit.mod.CreateContext.html) - Context available during actor state creation +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - Context available throughout actor lifecycle +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining actors with state + +_Source doc path: /docs/actors/state_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/statuses.md b/.agents/skills/ai-agent-workspace/reference/actors/statuses.md new file mode 100644 index 0000000..cccf52a --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/statuses.md @@ -0,0 +1,36 @@ +# Actor Statuses + +> Source: `src/content/docs/actors/statuses.mdx` +> Canonical URL: https://rivet.dev/docs/actors/statuses +> Description: Understand the lifecycle statuses of Rivet Actors, what they mean, how they appear in the API, and how to troubleshoot common issues. + +--- +## Statuses + +These are the statuses you can see in the dashboard for each actor. + +| Status | Description | +|---|---| +| **Starting** | The actor has been created but has not yet become connectable. | +| **Running** | The actor is live and accepting connections. | +| **Destroyed** | The actor has been gracefully destroyed. | +| **Crashed** | The actor failed to start or encountered a fatal error. See [Troubleshooting](/docs/actors/troubleshooting#actor-status-is-crashed) for common failure reasons. | +| **Sleeping** | The actor has been put to sleep from inactivity. It will be woken up automatically when a new request arrives. | +| **Pending** | The actor is waiting to be allocated to a runner. This happens when no runner is available to handle the actor. See [Troubleshooting](/docs/actors/troubleshooting#actor-status-is-pending) for common causes. | +| **Crash Loop Backoff** | The actor failed to allocate and is waiting to retry with a backoff. This typically means repeated allocation failures. The backoff prevents overloading your infrastructure in the case of a widespread misconfiguration in your backend. See [Troubleshooting](/docs/actors/troubleshooting#actor-status-is-crashed) for common failure reasons. | + +## API Representation + +The actor object returned by the full engine API (used by the dashboard) includes the following timestamp fields used to derive status: + +| Field | Description | +|---|---| +| `createTs` | When the actor was first created. Always present. | +| `connectableTs` | When the actor became connectable. Null if not yet running. | +| `destroyTs` | When the actor was destroyed. | +| `sleepTs` | When the actor entered a sleeping state. | +| `pendingAllocationTs` | When the actor started waiting for an allocation. | +| `rescheduleTs` | When the actor will retry allocation after a failure. | +| `error` | Error details if the actor failed. | + +_Source doc path: /docs/actors/statuses_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/testing.md b/.agents/skills/ai-agent-workspace/reference/actors/testing.md new file mode 100644 index 0000000..2473a44 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/testing.md @@ -0,0 +1,236 @@ +# Testing + +> Source: `src/content/docs/actors/testing.mdx` +> Canonical URL: https://rivet.dev/docs/actors/testing +> Description: Rivet provides a straightforward testing framework to build reliable and maintainable applications. This guide covers how to write effective tests for your actor-based services. + +--- +## Setup + +To set up testing with Rivet: + +```bash +# Install Vitest +npm install -D vitest + +# Run tests +npm test +``` + +## Basic Testing Setup + +Rivet includes a test helper called `setupTest` that starts your registry in test mode and returns a client connected to it. This allows for fast, isolated tests without external dependencies. + +```ts +import { test, expect } from "vitest"; +import { setupTest } from "rivetkit/test"; +import { actor, setup } from "rivetkit"; + +// Define the actor +const myActor = actor({ + state: { value: "initial" }, + actions: { + someAction: (c) => { + c.state.value = "updated"; + return c.state.value; + }, + getState: (c) => { + return c.state.value; + } + } +}); + +// Create the registry +const registry = setup({ + use: { myActor } +}); + +// Test the actor +test("my actor test", async (testCtx) => { + const { client } = await setupTest(testCtx, registry); + + // Now you can interact with your actor through the client + const myActorHandle = client.myActor.getOrCreate(["test"]); + + // Test your actor's functionality + await myActorHandle.someAction(); + + // Make assertions + const result = await myActorHandle.getState(); + expect(result).toEqual("updated"); +}); +``` + +## Testing Actor State + +State persists within each test, allowing you to verify that your actor correctly maintains state between operations. + +```ts +import { test, expect } from "vitest"; +import { setupTest } from "rivetkit/test"; +import { actor, setup } from "rivetkit"; + +// Define the counter actor +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c) => { + c.state.count += 1; + c.broadcast("newCount", c.state.count); + return c.state.count; + }, + getCount: (c) => { + return c.state.count; + } + } +}); + +// Create the registry +const registry = setup({ + use: { counter } +}); + +// Test state persistence +test("actor should persist state", async (testCtx) => { + const { client } = await setupTest(testCtx, registry); + const counterHandle = client.counter.getOrCreate(["test"]); + + // Initial state + expect(await counterHandle.getCount()).toBe(0); + + // Modify state + await counterHandle.increment(); + + // Verify state was updated + expect(await counterHandle.getCount()).toBe(1); +}); +``` + +## Testing Events + +For actors that emit events, you can verify events are correctly triggered by subscribing to them: + +```ts +import { test, expect, vi } from "vitest"; +import { setupTest } from "rivetkit/test"; +import { actor, setup } from "rivetkit"; + +interface ChatMessage { + username: string; + message: string; +} + +// Define the chat room actor +const chatRoom = actor({ + state: { + messages: [] as ChatMessage[] + }, + actions: { + sendMessage: (c, username: string, message: string) => { + c.state.messages.push({ username, message }); + c.broadcast("newMessage", username, message); + }, + getHistory: (c) => { + return c.state.messages; + }, + }, +}); + +// Create the registry +const registry = setup({ + use: { chatRoom } +}); + +// Test event emission +test("actor should emit events", async (testCtx) => { + const { client } = await setupTest(testCtx, registry); + const chatRoomHandle = client.chatRoom.getOrCreate(["test"]); + + // Set up event handler with a mock function + const mockHandler = vi.fn(); + const conn = chatRoomHandle.connect(); + conn.on("newMessage", mockHandler); + + // Trigger the event + await conn.sendMessage("testUser", "Hello world"); + + // Wait for the event to be emitted + await vi.waitFor(() => { + expect(mockHandler).toHaveBeenCalledWith("testUser", "Hello world"); + }); +}); +``` + +## Testing Schedules + +Rivet's schedule functionality can be tested by scheduling work and waiting for it to run: + +```ts +import { test, expect } from "vitest"; +import { setupTest } from "rivetkit/test"; +import { actor, setup } from "rivetkit"; + +// Helper to wait for a delay +const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +// Define the scheduler actor +const scheduler = actor({ + state: { + tasks: [] as string[], + completedTasks: [] as string[] + }, + actions: { + scheduleTask: (c, taskName: string, delayMs: number) => { + c.state.tasks.push(taskName); + // Schedule "completeTask" to run after the specified delay + c.schedule.after(delayMs, "completeTask", taskName); + return { success: true }; + }, + completeTask: (c, taskName: string) => { + // This action will be called by the scheduler when the time comes + c.state.completedTasks.push(taskName); + return { completed: taskName }; + }, + getCompletedTasks: (c) => { + return c.state.completedTasks; + } + } +}); + +// Create the registry +const registry = setup({ + use: { scheduler } +}); + +// Test scheduled tasks +test("scheduled tasks should execute", async (testCtx) => { + const { client } = await setupTest(testCtx, registry); + const schedulerHandle = client.scheduler.getOrCreate(["test"]); + + // Set up a scheduled task + await schedulerHandle.scheduleTask("reminder", 100); // 100ms in the future + + // Wait for the scheduled task to run + await wait(150); + + // Verify the scheduled task executed + expect(await schedulerHandle.getCompletedTasks()).toContain("reminder"); +}); +``` + +Use a short real-time delay to wait for scheduled work to run. `setupTest` does not install fake timers, so if you want to use `vi.useFakeTimers()` you must enable it yourself and confirm it works with your selected runtime. + +## Best Practices + +1. **Isolate tests**: Each test should run independently, avoiding shared state. +2. **Test edge cases**: Verify how your actor handles invalid inputs, concurrent operations, and error conditions. +3. **Test scheduled operations**: Use short real-time delays to wait for scheduled work to run. +4. **Use realistic data**: Test with data that resembles production scenarios. + +`setupTest` starts the registry and disposes the returned client when the test finishes, so you can focus on writing effective tests for your business logic. + +## API Reference + +- [`setupTest`](/typedoc/functions/rivetkit.test_mod.setupTest.html) - Test setup helper function + +_Source doc path: /docs/actors/testing_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/troubleshooting.md b/.agents/skills/ai-agent-workspace/reference/actors/troubleshooting.md new file mode 100644 index 0000000..65b234d --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/troubleshooting.md @@ -0,0 +1,154 @@ +# Troubleshooting + +> Source: `src/content/docs/actors/troubleshooting.mdx` +> Canonical URL: https://rivet.dev/docs/actors/troubleshooting +> Description: Common issues with Rivet Actors and how to resolve them. + +--- +## Common Steps + +Before diving into specific errors, try these general troubleshooting steps: + +- Check your server logs for `level=ERROR` or `level=WARN` messages. +- Check if any of your backend processes have crashed or restarted unexpectedly. +- If you need more diagnostics, set `RIVET_LOG_LEVEL=DEBUG` for verbose logging. See [Logging](/docs/general/logging) for more options. + +## Reporting Issues + +If you're stuck, reach out on [Discord](https://rivet.dev/discord) or file an issue on [GitHub](https://github.com/rivet-dev/rivet/issues). + +When reporting, please include: + +- **Symptoms** + - Whether this is happening in local dev, deployed, or both + - The error you're seeing (screenshot or error message) + - Relevant source code related to the issue +- **What you've tried to solve it** +- **Environment** + - RivetKit version + - Runtime (Node, Bun, etc.) including version + - If applicable, provider in use (e.g. Vercel, Railway, Cloudflare) + - If applicable, HTTP router in use (e.g. Hono, Express, Elysia) + +## Actor status is crashed + +See [Actor Statuses](/docs/actors/statuses) for more about this status. + +The dashboard will show the specific failure reason. Common errors include: + +### `crashed` + +The actor's `run` handler threw an unhandled exception or exited unexpectedly. Check your actor logs for the error message and stack trace. + +### `no_capacity` + +No server was available to run your actor. The cause depends on your [runtime mode](/docs/general/runtime-modes): + +**Serverless**: + +- Your provider configuration does not have the region enabled that the actor is trying to run in. This is uncommon and usually only happens if an actor was created and then the provider config was updated to remove the region. +- There is an issue connecting to your backend. If the engine is hitting `/api/rivet/start` and failing, check your backend logs for errors. + +**Runners**: + +- You don't have enough runners online. Check your runner list in the dashboard to verify runners are visible and connected. +- Your runners are full. Each runner has a limited number of actor slots (configured via `RIVET_TOTAL_SLOTS`, default: 100,000). Check the dashboard to see if your runners have available capacity and scale up if needed. + +### `runner_no_response` + +The server running your actor did not respond in time. This can happen if your server is overloaded or experienced a network issue. Try restarting your server or checking its health. + +### `runner_connection_lost` + +The server running your actor lost its connection to Rivet. This is usually caused by a network interruption or your server restarting. + +### `runner_draining_timeout` + +Your server is shutting down and the actor did not finish in time. Consider handling graceful shutdown in your actor or increasing your shutdown timeout. + +### `concurrent_actor_limit_reached` + +The actor could not be allocated because the concurrent actor limit was reached. Reduce the number of concurrently running actors or increase your limit. + +### `no_envoys` + +No server was available to run your actor. This is equivalent to `no_capacity` on the current allocation path. See the `no_capacity` section above for the causes and fixes for your [runtime mode](/docs/general/runtime-modes). + +### `envoy_no_response` + +The server running your actor did not respond in time. This can happen if your server is overloaded or experienced a network issue. Try restarting your server or checking its health. + +### `envoy_connection_lost` + +The server running your actor lost its connection to Rivet. This is usually caused by a network interruption or your server restarting. + +### `serverless_http_error` + +Your serverless endpoint returned an HTTP error. Common causes: + +- Your backend is returning an error before the actor can start. Check your server logs. +- Your endpoint is behind authentication or a firewall that is blocking Rivet's requests. +- Your serverless function crashed during startup. Check your platform's function logs (e.g. Vercel, Cloudflare). + +### `serverless_connection_error` + +Rivet was unable to connect to your serverless endpoint. Check that: + +- Your backend is deployed and the endpoint URL is correct. +- Your server is publicly reachable from the internet. +- There are no DNS or firewall issues blocking the connection. + +### `serverless_stream_ended_early` + +The connection to your serverless endpoint was terminated before the actor finished. This usually means your serverless function hit its execution time limit. Ensure that your Rivet provider's request lifespan is configured to match the max duration of your serverless platform. + +### `serverless_invalid_sse_payload` + +Rivet received an unexpected response from your serverless endpoint. This typically means something is intercepting or modifying the request before it reaches your RivetKit handler. Check that: + +- Your server routes requests to `registry.start()`, `registry.serve()`, or `registry.handler()` correctly. +- No middleware is modifying the request or response body. + +### `internal_error` + +An unexpected error occurred within Rivet. If this persists, please [contact support](https://rivet.dev/docs). + +## Actors crashing immediately on startup + +If your actors are being created and then immediately destroyed or crashing, there is likely an error being thrown in your `createState` or `onCreate` lifecycle hooks. These hooks run during actor initialization before the actor is marked as ready. + +Check your server logs for the error message and stack trace. Common causes include: + +- An exception thrown in `createState` (e.g. invalid input, failed validation, or a runtime error when computing initial state) +- An exception thrown in `onCreate` (e.g. a failing external API call, missing configuration, or invalid setup logic) + +Fix the error in the relevant lifecycle hook and redeploy. + +## Actors not upgrading to new code + +If your actors are still running old code after deploying a new version, your [versioning](/docs/actors/versions) is likely not configured correctly. + +Without versioning, Rivet has no way to distinguish old deployments from new ones. The behavior depends on your [runtime mode](/docs/general/runtime-modes): + +- **Serverless**: Old requests may still be open from the previous deployment, so actors continue running on the old version's connection until those requests close. +- **Runners**: The old runner container is still running and will continue accepting new actors. New actors may be scheduled on the old runner instead of the new one. + +To fix this, configure a version number in your [registry configuration](/docs/general/registry-configuration). When a new version is deployed, Rivet will allocate new actors to the latest version and optionally drain old actors to migrate them. + +## Actor status is pending + +See [Actor Statuses](/docs/actors/statuses) for more about this status. + +An actor stays in "pending" status when Rivet is waiting for a server to accept it. The cause depends on your [runtime mode](/docs/general/runtime-modes): + +**Serverless**: + +- A region may have been removed from your provider configuration while an existing actor still lives in that region. The actor has no available server to start on because no provider serves that region anymore. Re-add the region to your provider config or destroy the affected actors. +- Check your backend logs for errors on the `/api/rivet/start` endpoint. + +**Runners**: + +- You don't have enough runners online. Check the dashboard to verify your runners are connected. +- Your runners may be at capacity. Check the dashboard to see if runners have available actor slots and scale up if needed. + +_Source doc path: /docs/actors/troubleshooting_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/types.md b/.agents/skills/ai-agent-workspace/reference/actors/types.md new file mode 100644 index 0000000..604381e --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/types.md @@ -0,0 +1,106 @@ +# Types + +> Source: `src/content/docs/actors/types.mdx` +> Canonical URL: https://rivet.dev/docs/actors/types +> Description: TypeScript types for working with Rivet Actors. This page covers context types used in lifecycle hooks and actions, as well as helper types for extracting types from actor definitions. + +--- +## Context Types + +Context types define what properties and methods are available in different parts of the actor lifecycle. + +```typescript +import { actor } from "rivetkit"; + +const counter = actor({ + // CreateContext in createState hook + createState: (c, input: { initial: number }): { count: number } => { + return { count: input.initial }; + }, + + // ActionContext in actions + actions: { + increment: (c) => { + c.state.count += 1; + return c.state.count; + } + } +}); +``` + +### Extracting Context Types + +When writing helper functions that work with actor contexts, use context extractor types like `CreateContextOf` or `ActionContextOf` to extract the appropriate context type from your actor definition. + +```typescript +import { actor, CreateContextOf, ActionContextOf } from "rivetkit"; + +const gameRoom = actor({ + createState: (c, input: { roomId: string }): { players: string[]; score: number } => { + initializeRoom(c, input.roomId); + return { players: [] as string[], score: 0 }; + }, + + actions: { + addPlayer: (c, playerId: string) => { + validatePlayer(c, playerId); + c.state.players.push(playerId); + } + } +}); + +// Extract CreateContext type for createState hook +function initializeRoom( + context: CreateContextOf, + roomId: string +) { + console.log(`Initializing room: ${roomId}`); + // context.state is not available here (being created) + // context.vars is not available here (not created yet) +} + +// Extract ActionContext type for actions +function validatePlayer( + context: ActionContextOf, + playerId: string +) { + // Full context available in actions + if (context.state.players.includes(playerId)) { + throw new Error("Player already in room"); + } +} +``` + +### All Context Types + +Each lifecycle hook and handler has a corresponding `*ContextOf` type, exported from `"rivetkit"`. Pass `typeof myActor` as the type parameter. + +| Hook / Handler | Context Type | +|---|---| +| `createState` | `CreateContextOf` | +| `onCreate` | `CreateContextOf` | +| `createVars` | `CreateVarsContextOf` | +| `createConnState` | `CreateConnStateContextOf` | +| `onBeforeConnect` | `BeforeConnectContextOf` | +| `onConnect` | `ConnectContextOf` | +| `onDisconnect` | `DisconnectContextOf` | +| `onDestroy` | `DestroyContextOf` | +| `onMigrate` | `MigrateContextOf` | +| `onWake` | `WakeContextOf` | +| `onSleep` | `SleepContextOf` | +| `onStateChange` | `StateChangeContextOf` | +| `onBeforeActionResponse` | `BeforeActionResponseContextOf` | +| `actions.*` | `ActionContextOf` | +| `run` | `RunContextOf` | +| `workflow` root context helpers | `WorkflowContextOf` | +| `workflow` loop helpers | `WorkflowLoopContextOf` | +| `workflow` branch helpers | `WorkflowBranchContextOf` | +| `workflow` standalone step helpers | `WorkflowStepContextOf` | +| `onRequest` | `RequestContextOf` | +| `onWebSocket` | `WebSocketContextOf` | + +`ActorContextOf`, `ConnContextOf`, and `ConnInitContextOf` are general-purpose base context types useful for helper functions that don't correspond to a specific hook. + +Workflow context extractors are exported from both `"rivetkit"` and `"rivetkit/workflow"`. + +_Source doc path: /docs/actors/types_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/versions.md b/.agents/skills/ai-agent-workspace/reference/actors/versions.md new file mode 100644 index 0000000..9790c25 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/versions.md @@ -0,0 +1,337 @@ +# Versions & Upgrades + +> Source: `src/content/docs/actors/versions.mdx` +> Canonical URL: https://rivet.dev/docs/actors/versions +> Description: When you deploy new code, Rivet ensures actors are upgraded seamlessly without downtime. + +--- +## How Versions Work + +Each runner has a **version number**. When you deploy new code with a new version, Rivet handles the transition automatically: + +- **New actors go to the newest version**: When allocating actors, Rivet always prefers runners with the highest version number +- **Multiple versions can coexist**: Old actors continue running on old versions while new actors are created on the new version +- **Drain old actors**: When enabled, a runner connecting with a newer version number will gracefully stop old actors to be rescheduled to the new version + +Versions are not configured by default. See [Registry Configuration](/docs/general/registry-configuration) to learn how to configure the runner version. + +`RIVET_ENVOY_VERSION` is only needed when self-hosting or using a custom runner. Rivet Compute handles versioning automatically. + +### Example Scenario + +### Drain Enabled + +When a new version is deployed, existing actors are gracefully stopped on the old runner and rescheduled onto the new version. + +```mermaid +sequenceDiagram + participant R1 as Runner v1 + participant R2 as Runner v2 + + Note over R1: Currently running + Note over R2: Deployed + R2->>R1: Drain old actors + R1->>R2: Reschedule actors + Note over R1: Shut down when all actors stopped +``` + +### Drain Disabled + +When a new version is deployed, both versions coexist. New actors are created on the new version while existing actors continue running on the old version until. + +```mermaid +sequenceDiagram + participant R1 as Runner v1 + participant R2 as Runner v2 + + Note over R1: Currently running + Note over R2: Deployed + Note over R1: Actor 1 sleeps from inactivity + Note over R2: Actor 1 wakes up when prompted +``` + +## Configuration + +### Setting the Version + +Configure the runner version using an environment variable or programmatically: + +```bash {{"title": "Environment Variable"}} +RIVET_ENVOY_VERSION=2 +``` + +```typescript {{"title": "Programmatic"}} +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); + +const registry = setup({ + use: { myActor }, + envoy: { + version: 2, + }, +}); +``` + +The version **must** be set at build time, not at runtime. Do not use `Date.now()` or similar runtime values in your registry setup code. This would assign a different version every time the server starts, causing actors to be drained and rescheduled on every restart instead of only on new deployments. + +### Example Configurations + +We recommend injecting a build-time value that increments with every deployment. Here are concrete examples for common setups: + +### Dockerfile + +Generate the version at build time and bake it into the image as an environment variable: + +```bash @nocheck +docker build --build-arg RIVET_ENVOY_VERSION=$(date +%s) . +``` + +```dockerfile @nocheck +FROM node:20-slim +ARG RIVET_ENVOY_VERSION +ENV RIVET_ENVOY_VERSION=$RIVET_ENVOY_VERSION +WORKDIR /app +COPY . . +RUN npm install && npm run build +CMD ["node", "dist/server.js"] +``` + +All containers from this image will share the same version. + +### Next.js + +Set the version in `next.config.ts`. Next.js evaluates this file once at build time and inlines the value into the bundle: + +```typescript @nocheck +import type { NextConfig } from "next"; + +const nextConfig: NextConfig = { + env: { + RIVET_ENVOY_VERSION: String(Math.floor(Date.now() / 1000)), + }, +}; + +export default nextConfig; +``` + +### Vite + +Use `define` in your Vite config. This is evaluated once at build time and inlined into the bundle: + +```typescript @nocheck +import { defineConfig } from "vite"; + +export default defineConfig({ + define: { + "process.env.RIVET_ENVOY_VERSION": JSON.stringify( + String(Math.floor(Date.now() / 1000)) + ), + }, +}); +``` + +### CI/CD + +Set the version from your CI pipeline: + +```yaml @nocheck +# GitHub Actions +env: + RIVET_ENVOY_VERSION: ${{ github.run_number }} +``` + +```bash @nocheck +# Railway / Render / generic CI +export RIVET_ENVOY_VERSION=$(date +%s) +``` + +```bash @nocheck +# Git commit count +export RIVET_ENVOY_VERSION=$(git rev-list --count HEAD) +``` + +### Build Script + +Generate a version file during your build step and import it: + +```json @nocheck +{ + "scripts": { + "build": "echo \"export const BUILD_VERSION = $(date +%s);\" > src/build-version.ts && tsc" + } +} +``` + +```typescript @nocheck +import { actor, setup } from "rivetkit"; +import { BUILD_VERSION } from "./build-version"; + +const myActor = actor({ state: {}, actions: {} }); + +const registry = setup({ + use: { myActor }, + envoy: { + version: BUILD_VERSION, + }, +}); +``` + +### Drain on Version Upgrade + +The `drainOnVersionUpgrade` option controls whether old actors are stopped when a new version is deployed. This is configured in the Rivet dashboard under your runner configuration. See [Pool Configuration](/docs/general/pool-configuration) for the full set of pool options, including how to rate-limit actor eviction during the drain. + +| Value | Behavior | +|-------|----------| +| `false` | Old actors continue running. New actors go to new version. Versions coexist. | +| `true` (default) | Old actors receive stop signal and have 30m to finish gracefully. | + +## Upgrading Actor State + +When you deploy a new version, existing actors may need to handle schema changes in their persisted data. + +### SQLite (recommended for complex schemas) + +**Drizzle (recommended)** + +Use [Drizzle](/docs/actors/sqlite-drizzle) for typed schemas with generated migrations. Drizzle generates versioned `.sql` migration files from your TypeScript schema and applies them in order automatically. This is the recommended approach when your schema evolves frequently. + +**Raw SQL** + +For actors using [raw SQLite](/docs/actors/sqlite), migrations run automatically via the `onMigrate` hook on every actor start. RivetKit wraps the hook in a SQLite savepoint, so the migration is fully atomic. Use SQLite's `user_version` pragma to track which migrations have run: + +```ts +import { actor, setup } from "rivetkit"; +import { db } from "rivetkit/db"; + +const todoList = actor({ + db: db({ + onMigrate: async (db) => { + const [{ user_version }] = (await db.execute( + "PRAGMA user_version", + )) as { user_version: number }[]; + + if (user_version < 1) { + await db.execute(` + CREATE TABLE todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL + ); + `); + } + + if (user_version < 2) { + await db.execute(` + ALTER TABLE todos ADD COLUMN completed INTEGER NOT NULL DEFAULT 0; + `); + } + + await db.execute("PRAGMA user_version = 2"); + }, + }), + actions: { + addTodo: async (c, title: string) => { + await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); + }, + }, +}); + +const registry = setup({ use: { todoList } }); +registry.start(); +``` + +### In-memory state (`c.state`) + +If you use `c.state` for persistence, you are responsible for handling schema changes yourself. If you add, remove, or rename fields between versions, your code must handle the old shape gracefully. + +**Manual defaults in `onWake`** + +Apply defaults for missing fields: + +```ts +import { actor, setup } from "rivetkit"; + +const myActor = actor({ + state: { count: 0, label: "" }, + onWake: (c) => { + // Added in v2. Old actors won't have this field. + c.state.label ??= "default"; + }, + actions: { + getLabel: (c) => c.state.label, + }, +}); + +const registry = setup({ use: { myActor } }); +registry.start(); +``` + +**Zod schema coercion** + +Use [Zod](https://zod.dev/) to parse persisted state on wake. Zod's `.default()` fills in missing fields automatically, so old actor state is coerced to the current schema: + +```ts +import { actor, setup } from "rivetkit"; +import { z } from "zod"; + +const stateSchema = z.object({ + count: z.number().default(0), + label: z.string().default("default"), // Added in v2 +}); + +type State = z.infer; + +const myActor = actor({ + state: { count: 0, label: "default" } as State, + onWake: (c) => { + Object.assign(c.state, stateSchema.parse(c.state)); + }, + actions: { + getLabel: (c) => c.state.label, + }, +}); + +const registry2 = setup({ use: { myActor } }); +registry2.start(); +``` + +For anything beyond simple defaults, consider moving to [SQLite](/docs/actors/sqlite) where you get proper migration tooling. + +## Advanced + +### How Version Upgrade Detection Works + +When `drainOnVersionUpgrade` is enabled, Rivet uses two mechanisms to detect version changes: + +- **New runner connection**: When a runner connects with a newer version number, the engine immediately drains all older runners with the same name. This is the primary mechanism for [runner mode](/docs/general/runtime-modes) deployments. +- **Metadata polling** (serverless only): In [serverless mode](/docs/general/runtime-modes), runners periodically poll the engine to check for newer versions and self-drain if one is found. This ensures old runners drain even if no new requests trigger a runner connection. + +### SIGTERM Handling + +When a runner process receives SIGTERM, it gracefully stops all actors before exiting: + +- Each actor's `onSleep` hook is called, giving it time to save state +- Actors are rescheduled to other available runners +- The runner waits up to **30 minutes** for all actors to finish stopping +- If the process is force-killed before actors finish (e.g. SIGKILL), actors are rescheduled with a crash backoff penalty instead of a clean handoff + +Actors have a maximum of 30 minutes to clean up during shutdown. Ensure your platform's drain grace period is at most 30 minutes. + +### Shutdown Timeouts + +Several timeouts control how long each part of the shutdown process can take: + +| Timeout | Default | Description | Configuration | +|---------|---------|-------------|---------------| +| `actor_stop_threshold` | 30m | Engine-side limit on how long each actor has to stop before being marked lost | [Engine config](/docs/self-hosting/configuration) (`pegboard.actor_stop_threshold`) | +| `sleepGracePeriod` | 15s | Total graceful sleep budget for `onSleep`, `waitUntil`, `keepAwake`, and async raw WebSocket handlers | [Actor options](/docs/actors/lifecycle#options) | +| `runner_lost_threshold` | 15s | Fallback detection if the runner dies without graceful shutdown | [Engine config](/docs/self-hosting/configuration) (`pegboard.runner_lost_threshold`) | + +Rivet has a max shutdown grace period of 30 minutes that cannot be configured. + +## Related + +- [Runtime Modes](/docs/general/runtime-modes): Serverless vs runner deployment modes +- [Lifecycle](/docs/actors/lifecycle): Actor lifecycle hooks including `onSleep` + +_Source doc path: /docs/actors/versions_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/websocket-handler.md b/.agents/skills/ai-agent-workspace/reference/actors/websocket-handler.md new file mode 100644 index 0000000..583d290 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/websocket-handler.md @@ -0,0 +1,330 @@ +# Low-Level WebSocket Handler + +> Source: `src/content/docs/actors/websocket-handler.mdx` +> Canonical URL: https://rivet.dev/docs/actors/websocket-handler +> Description: Actors can handle WebSocket connections through the `onWebSocket` handler. + +--- +For most use cases, [actions](/docs/actors/actions) and [events](/docs/actors/events) provide high-level connection handling powered by WebSockets that's easier to work with than low-level WebSockets. However, low-level handlers are required when implementing custom use cases. + +## Handling WebSocket Connections + +The `onWebSocket` handler manages low-level WebSocket connections. It receives the actor context and a `WebSocket` object. + +```typescript +import { actor } from "rivetkit"; + +export const chatActor = actor({ + state: { messages: [] as string[] }, + onWebSocket: (c, websocket) => { + websocket.addEventListener("open", () => { + // Send existing messages to new connection + websocket.send(JSON.stringify({ + type: "history", + messages: c.state.messages, + })); + }); + + websocket.addEventListener("message", (event) => { + // Store message + c.state.messages.push(event.data as string); + + // Echo message back + websocket.send(event.data as string); + + // Manually save state since WebSocket connections are long-lived + c.saveState({ immediate: true }); + }); + }, + actions: {} +}); +``` + +See also the [raw WebSocket handler example](https://github.com/rivet-dev/rivet/tree/main/examples/raw-websocket-handler). + +## Connecting To Actors + +### Via RivetKit Client + +Use the `.webSocket()` method on an actor handle to open a WebSocket connection to the actor's `onWebSocket` handler. This can be executed from either your frontend or backend. + +```typescript index.ts @hide @nocheck +import { actor, setup } from "rivetkit"; + +export const chat = actor({ + state: { messages: [] as string[] }, + onWebSocket: (c, websocket) => { + websocket.addEventListener("message", (event) => { + c.state.messages.push(event.data as string); + }); + }, + actions: {} +}); + +export const registry = setup({ use: { chat } }); +registry.start(); +``` + +```typescript client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +const actor = client.chat.getOrCreate(["my-chat"]); + +// Open WebSocket connection +const ws = await actor.webSocket("/"); + +// Listen for messages +ws.addEventListener("message", (event) => { + const message = JSON.parse(event.data as string); + console.log("Received:", message); +}); + +// Send messages +ws.send(JSON.stringify({ type: "chat", text: "Hello!" })); +``` + +The `.webSocket()` method returns a standard WebSocket. + +### Via getGatewayUrl + +Use `.getGatewayUrl()` to get the raw gateway URL for the actor. This is useful when you need to use the URL with external tools or custom WebSocket clients. + +```typescript index.ts @hide @nocheck +import { actor, setup } from "rivetkit"; + +export const chat = actor({ + state: { messages: [] as string[] }, + onWebSocket: (c, websocket) => { + websocket.addEventListener("message", (event) => { + c.state.messages.push(event.data as string); + }); + }, + actions: {} +}); + +export const registry = setup({ use: { chat } }); +registry.start(); +``` + +```typescript client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +const actor = client.chat.getOrCreate(["my-chat"]); + +// Get the raw gateway URL +const gatewayUrl = await actor.getGatewayUrl(); +// gatewayUrl = "https://...rivet.dev/..." + +// Convert to WebSocket URL and connect +const wsUrl = gatewayUrl.replace("http://", "ws://").replace("https://", "wss://"); +const ws = new WebSocket(`${wsUrl}/websocket/`); + +ws.addEventListener("message", (event) => { + const message = JSON.parse(event.data as string); + console.log("Received:", message); +}); + +ws.addEventListener("open", () => { + ws.send(JSON.stringify({ type: "chat", text: "Hello!" })); +}); +``` + +### Via HTTP API + +This handler can be accessed with raw WebSockets using `wss://api.rivet.dev/gateway/{actorId}@{token}/websocket/{...path}`. + +For example, to connect to the chat actor above: + +```typescript +// Replace with your actor ID and token +const actorId = "your-actor-id"; +const token = "your-token"; + +const ws = new WebSocket( + `wss://api.rivet.dev/gateway/${actorId}@${token}/websocket/` +); + +ws.addEventListener("message", (event) => { + const message = JSON.parse(event.data as string); + console.log("Received:", message); +}); + +ws.addEventListener("open", () => { + ws.send(JSON.stringify({ type: "chat", text: "Hello!" })); +}); +``` + +```bash +wscat -c "wss://api.rivet.dev/gateway/{actorId}@{token}/websocket/" +``` + +The path after `/websocket/` is passed to your `onWebSocket` handler and can be used to route to different functionality within your actor. For example, to connect with a custom path `/admin`: + +```typescript +// Replace with your actor ID and token +const actorId = "your-actor-id"; +const token = "your-token"; + +const ws = new WebSocket( + `wss://api.rivet.dev/gateway/${actorId}@${token}/websocket/admin` +); +``` + +```bash +wscat -c "wss://api.rivet.dev/gateway/{actorId}@{token}/websocket/admin" +``` + +See the [HTTP API reference](/docs/actors/http-api) for more information on WebSocket routing and authentication. + +### Via Proxying Connections + +You can proxy WebSocket connections from your own server to actor handlers using the RivetKit client. This is useful when you need to add custom authentication or connection management before forwarding to actors. + +```typescript +import { Hono } from "hono"; +import type { WSContext, WSMessageReceive } from "hono/ws"; +import { upgradeWebSocket } from "hono/bun"; +import { createClient } from "rivetkit/client"; +import { actor, setup } from "rivetkit"; + +const chatActor = actor({ + state: { messages: [] as string[] }, + onWebSocket: (c, websocket) => { + websocket.addEventListener("message", (event) => { + c.state.messages.push(event.data as string); + websocket.send(event.data as string); + }); + }, + actions: {} +}); + +const registry = setup({ use: { chat: chatActor } }); +const client = createClient("http://localhost:6420"); + +const app = new Hono(); + +// Proxy WebSocket connections to actor's onWebSocket handler +app.get("/ws/:id", upgradeWebSocket(async (c) => { + const actorId = c.req.param("id"); + const actorHandle = client.chat.get([actorId]); + const actorWs = await actorHandle.webSocket("/"); + + return { + onOpen: (evt: Event, ws: WSContext) => { + actorWs.addEventListener("message", (event: MessageEvent) => { + ws.send(event.data); + }); + actorWs.addEventListener("close", () => { + ws.close(); + }); + }, + onMessage: (evt: MessageEvent, ws: WSContext) => { + actorWs.send(evt.data as string); + }, + onClose: () => { + actorWs.close(); + }, + }; +})); + +export default app; +``` + +See also the [raw WebSocket handler with proxy example](https://github.com/rivet-dev/rivet/tree/main/examples/raw-websocket-handler-proxy). + +## Connection & Lifecycle Hooks + +`onWebSocket` will trigger the `onBeforeConnect`, `onConnect`, and `onDisconnect` hooks. Read more about [lifecycle hooks](/docs/actors/lifecycle). + +Open WebSockets will be listed in `c.conns`. `conn.send` and `c.broadcast` have no effect on low-level WebSocket connections. Read more about [connections](/docs/actors/connections). + +## WinterTC Compliance + +The `onWebSocket` handler uses standard WebSocket APIs and will work with existing libraries expecting WinterTC-compliant WebSocket objects. + +## Advanced + +## WebSocket Hibernation + +WebSocket hibernation allows actors to go to sleep while keeping WebSocket connections alive. Actors automatically wake up when a message is received or the connection closes. + +Enable hibernation by setting `canHibernateWebSocket: true`. You can also pass a function `(request) => boolean` for conditional control. + +```typescript +import { actor } from "rivetkit"; + +export const myActor = actor({ + state: {}, + options: { + canHibernateWebSocket: true, + }, + actions: {} +}); +``` + +Since `open` only fires once when the client first connects, use `c.conn.state` to store per-connection data that persists across sleep cycles. See [connections](/docs/actors/connections) for more details. + +### Accessing the Request + +The underlying HTTP request is available via `c.request`. This is useful for accessing the path or query parameters. + +```typescript +import { actor } from "rivetkit"; + +const myActor = actor({ + state: {}, + onWebSocket: (c, websocket) => { + if (c.request) { + const url = new URL(c.request.url); + console.log(url.pathname); // e.g., "/admin" + console.log(url.searchParams.get("foo")); // e.g., "bar" + } + }, + actions: {} +}); +``` + +### Skip Ready Wait + +Connections are normally held at the gateway until the actor is ready. Pass `skipReadyWait: true` on `handle.webSocket()` to connect immediately, including while the actor is still starting or in the [sleep grace period](/docs/actors/lifecycle#shutdown-sequence). See [Skip Ready Wait](/docs/clients/javascript#skip-ready-wait) for details. + +### Async Handlers + +The `onWebSocket` handler can be async, allowing you to perform async code before setting up event listeners: + +```typescript +import { actor } from "rivetkit"; + +const myActor = actor({ + state: {}, + onWebSocket: async (c, websocket) => { + // Perform async operations before the connection is ready + const metadata = await fetch("https://api.example.com/metadata").then(r => r.json()); + + websocket.addEventListener("open", () => { + // Send metadata on connection + websocket.send(JSON.stringify({ metadata })); + }); + + websocket.addEventListener("message", (event) => { + // Handle messages + }); + }, + actions: {} +}); +``` + +## API Reference + +- [`WebSocketContext`](/typedoc/interfaces/rivetkit.mod.WebSocketContext.html) - Context for WebSocket handlers +- [`UniversalWebSocket`](/typedoc/interfaces/rivetkit.mod.UniversalWebSocket.html) - Universal WebSocket interface +- [`handleRawWebSocketHandler`](/typedoc/functions/rivetkit.mod.handleRawWebSocketHandler.html) - Function to handle raw WebSocket +- [`UpgradeWebSocketArgs`](/typedoc/interfaces/rivetkit.mod.UpgradeWebSocketArgs.html) - Arguments for WebSocket upgrade + +_Source doc path: /docs/actors/websocket-handler_ diff --git a/.agents/skills/ai-agent-workspace/reference/actors/workflows.md b/.agents/skills/ai-agent-workspace/reference/actors/workflows.md new file mode 100644 index 0000000..1c95661 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/actors/workflows.md @@ -0,0 +1,2013 @@ +# Workflows + +> Source: `src/content/docs/actors/workflows.mdx` +> Canonical URL: https://rivet.dev/docs/actors/workflows +> Description: Build durable, replayable run loops in Rivet Actors with steps, queue waits, timers, and rollback. + +--- +Use workflows for durable, multi-step execution with replay safety. + +## What are workflows? + +A workflow is a durable, replayable run handler for a Rivet Actor. + +- Survives restarts: workflow progress is saved automatically. +- Re-runs safely: replay follows the same recorded steps. +- Event-driven: workflows can pause for queue messages, then continue. + +## Getting started + +### Simple workflow + +Use this when you need a short multi-step sequence. + +```ts index.ts +import { actor, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +export const invoiceActor = actor({ + state: { + invoiceId: null as string | null, + subtotal: 0, + tax: 0, + total: 0, + status: "idle" as "idle" | "complete", + }, + run: workflow(async (ctx) => { + const subtotal = await ctx.step("load-subtotal", async () => + loadSubtotal(), + ); + + const tax = await ctx.step("calculate-tax", async () => + calculateTax(subtotal), + ); + + await ctx.step("save-invoice", async () => + saveInvoice(ctx, subtotal, tax), + ); + }), + actions: { + getState: (c) => c.state, + }, +}); + +async function loadSubtotal(): Promise { + const response = await fetch("https://api.example.com/carts/main"); + if (!response.ok) { + throw new Error(`load subtotal failed: ${response.status}`); + } + const cart = (await response.json()) as { subtotal: number }; + return cart.subtotal; +} + +async function calculateTax(subtotal: number): Promise { + const response = await fetch("https://api.example.com/tax/quote", { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: JSON.stringify({ subtotal }), + }); + if (!response.ok) { + throw new Error(`tax quote failed: ${response.status}`); + } + const quote = (await response.json()) as { tax: number }; + return quote.tax; +} + +async function saveInvoice( + ctx: WorkflowContextOf, + subtotal: number, + tax: number, +): Promise { + const total = subtotal + tax; + const response = await fetch("https://api.example.com/invoices", { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: JSON.stringify({ subtotal, tax, total }), + }); + if (!response.ok) { + throw new Error(`save invoice failed: ${response.status}`); + } + const invoice = (await response.json()) as { id: string }; + ctx.state.invoiceId = invoice.id; + ctx.state.subtotal = subtotal; + ctx.state.tax = tax; + ctx.state.total = total; + ctx.state.status = "complete"; +} + +export const registry = setup({ use: { invoiceActor } }); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.invoiceActor.getOrCreate(["main"]); + +const state = await handle.getState(); +console.log(state.status, state.total); +``` + +### Loops + +This is the recommended workflow shape for most actor workloads. + +- Use a queue wait inside the loop to receive the next unit of work. +- Keep actor state changes in a single workflow loop. +- This gives you one durable workflow that manages all actor progress. + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +export const workflowCounter = actor({ + state: { + value: 0, + processed: 0, + lastOperationId: null as string | null, + }, + queues: { + counter: queue<{ delta: number }>(), + }, + run: workflow(async (ctx) => { + await ctx.loop("counter-loop", async (loopCtx) => { + const message = await loopCtx.queue.next("wait-counter-command"); + + await loopCtx.step("apply-counter-command", async () => + applyCounterCommand(loopCtx, message.body.delta), + ); + + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +async function applyCounterCommand( + ctx: WorkflowLoopContextOf, + delta: number, +): Promise { + const response = await fetch("https://api.example.com/counter/apply", { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: JSON.stringify({ delta }), + }); + if (!response.ok) { + throw new Error(`counter apply failed: ${response.status}`); + } + const result = (await response.json()) as { + nextValue: number; + operationId: string; + }; + ctx.state.value = result.nextValue; + ctx.state.lastOperationId = result.operationId; + ctx.state.processed += 1; +} + +export const registry = setup({ use: { workflowCounter } }); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.workflowCounter.getOrCreate(["main"]); + +await handle.send("counter", { delta: 1 }); +await handle.send("counter", { delta: 2 }); + +const state = await handle.getState(); +console.log(state.value, state.processed); +``` + +### Setup & teardown + +Use this when the workflow should initialize resources, process queued commands, then clean up. + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; +import { Loop, type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +type WorkMessage = { amount: number }; +type ControlMessage = { type: "stop"; reason: string }; + +export const setupRunTeardownActor = actor({ + state: { + phase: "idle" as "idle" | "running" | "stopped", + total: 0, + processed: 0, + stopReason: null as string | null, + workerSessionId: null as string | null, + }, + queues: { + work: queue(), + control: queue(), + }, + run: workflow(async (ctx) => { + await ctx.step("setup", async () => setupWorkerSession(ctx)); + + const stopReason = await ctx.loop("worker-loop", async (loopCtx) => { + const message = await loopCtx.queue.next("wait-command", { + names: ["work", "control"], + }); + + if (message.name === "work") { + const work = message.body as WorkMessage; + await loopCtx.step("apply-work", async () => + applyWorkerMessage(loopCtx, work), + ); + return; + } + + const control = message.body as ControlMessage; + if (control.type === "stop") { + return Loop.break(control.reason); + } + + }); + + await ctx.step("teardown", async () => + teardownWorkerSession(ctx, stopReason), + ); + }), + actions: { + getState: (c) => c.state, + }, +}); + +async function setupWorkerSession( + ctx: WorkflowContextOf, +): Promise { + const response = await fetch("https://api.example.com/workers/session", { + method: "POST", + }); + if (!response.ok) { + throw new Error(`worker setup failed: ${response.status}`); + } + const session = (await response.json()) as { sessionId: string }; + ctx.state.workerSessionId = session.sessionId; + ctx.state.phase = "running"; + ctx.state.stopReason = null; +} + +async function applyWorkerMessage( + ctx: WorkflowLoopContextOf, + work: WorkMessage, +): Promise { + const response = await fetch("https://api.example.com/workers/process", { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: JSON.stringify({ + sessionId: ctx.state.workerSessionId, + amount: work.amount, + }), + }); + if (!response.ok) { + throw new Error(`worker process failed: ${response.status}`); + } + const result = (await response.json()) as { appliedAmount: number }; + ctx.state.total += result.appliedAmount; + ctx.state.processed += 1; +} + +async function teardownWorkerSession( + ctx: WorkflowContextOf, + stopReason: string, +): Promise { + if (ctx.state.workerSessionId) { + const response = await fetch( + `https://api.example.com/workers/session/${ctx.state.workerSessionId}`, + { method: "DELETE" }, + ); + if (!response.ok) { + throw new Error(`worker teardown failed: ${response.status}`); + } + } + ctx.state.phase = "stopped"; + ctx.state.stopReason = stopReason; +} + +export const registry = setup({ use: { setupRunTeardownActor } }); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.setupRunTeardownActor.getOrCreate(["main"]); + +await handle.send("work", { amount: 5 }); +await handle.send("work", { amount: 3 }); +await handle.send("control", { type: "stop", reason: "maintenance" }); + +const state = await handle.getState(); +console.log(state.phase, state.total, state.stopReason); +``` + +## Features + +### Queue + +Use this for fire-and-forget commands where the client does not need a reply. + +Use the `Loops` example above as the baseline pattern. + +### Request/response (using queue) + +Use this when the caller needs a response from queued processing. + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +export const requestResponseActor = actor({ + state: { + handled: 0, + }, + queues: { + requests: queue<{ value: number }, { doubled: number }>(), + }, + run: workflow(async (ctx) => { + await ctx.loop("request-loop", async (loopCtx) => { + const message = await loopCtx.queue.next("wait-request", { + completable: true, + }); + + if (!message.complete) return; + + const doubled = await loopCtx.step("handle-request", async () => { + loopCtx.state.handled += 1; + return message.body.value * 2; + }); + + await message.complete({ doubled }); + }); + }), +}); + +export const registry = setup({ use: { requestResponseActor } }); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.requestResponseActor.getOrCreate(["main"]); + +const result = await handle.send( + "requests", + { value: 21 }, + { wait: true, timeout: 1_000 }, +); + +if (result.status === "completed") { + const response = result.response as { doubled: number }; + console.log(response.doubled); +} +``` + +### Timers + +Use queue messages as the trigger source, then sleep durably inside the workflow. + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +type Reminder = { + text: string; + at: number; +}; + +export const reminderActor = actor({ + state: { + fired: [] as string[], + }, + queues: { + reminders: queue(), + }, + run: workflow(async (ctx) => { + await ctx.loop("reminder-loop", async (loopCtx) => { + const message = await loopCtx.queue.next("wait-reminder"); + + const runAt = Math.max(Date.now(), message.body.at); + await loopCtx.sleepUntil("wait-until-reminder", runAt); + + await loopCtx.step("record-reminder", async () => { + loopCtx.state.fired.push(message.body.text); + }); + + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +export const registry = setup({ use: { reminderActor } }); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.reminderActor.getOrCreate(["main"]); + +await handle.send("reminders", { + text: "send weekly report", + at: Date.now() + 1_000, +}); + +await new Promise((resolve) => setTimeout(resolve, 1_300)); +console.log(await handle.getState()); +``` + +### Join + +Use `join` when several independent tasks can run in parallel. + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +export const dashboardActor = actor({ + state: { + summary: null as null | { + users: number; + orders: number; + revenue: number; + }, + }, + queues: { + refresh: queue>(), + }, + run: workflow(async (ctx) => { + await ctx.loop("dashboard-loop", async (loopCtx) => { + await loopCtx.queue.next("wait-refresh"); + + const summary = await loopCtx.join("fetch-summary", { + users: { + run: async (branchCtx) => { + return await branchCtx.step("fetch-users", () => fetchCount("/users")); + }, + }, + orders: { + run: async (branchCtx) => { + return await branchCtx.step("fetch-orders", () => fetchCount("/orders")); + }, + }, + revenue: { + run: async (branchCtx) => { + return await branchCtx.step("fetch-revenue", () => fetchCount("/revenue")); + }, + }, + }); + + await loopCtx.step("save-summary", async () => { + loopCtx.state.summary = summary; + }); + + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +async function fetchCount(path: string): Promise { + const res = await fetch(`https://api.example.com${path}`); + if (!res.ok) throw new Error(`fetch ${path} failed: ${res.status}`); + return ((await res.json()) as { count: number }).count; +} + +export const registry = setup({ use: { dashboardActor } }); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.dashboardActor.getOrCreate(["main"]); + +await handle.send("refresh", {}); +console.log(await handle.getState()); +``` + +### Race + +Use `race` when you need first-winner behavior. + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +export const auctionActor = actor({ + state: { result: null as "sold" | "expired" | null }, + queues: { + bids: queue<{ amount: number }>(), + }, + run: workflow(async (ctx) => { + await ctx.step("list-item", () => listItem("item-123")); + + const { winner } = await ctx.race("bid-or-expire", [ + { + name: "bid", + run: async (branchCtx) => { + const bid = await branchCtx.queue.next("wait-bid"); + return bid.body.amount; + }, + }, + { + name: "expire", + run: async (branchCtx) => { + await branchCtx.sleep("auction-timeout", 24 * 60 * 60 * 1000); + return 0; + }, + }, + ]); + + await ctx.step("finalize", async () => { + await finalizeAuction("item-123", winner); + ctx.state.result = winner === "bid" ? "sold" : "expired"; + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +async function listItem(itemId: string): Promise { + await fetch(`https://api.example.com/auctions/${itemId}`, { + method: "POST", + }); +} + +async function finalizeAuction( + itemId: string, + outcome: string, +): Promise { + await fetch(`https://api.example.com/auctions/${itemId}/finalize`, { + method: "POST", + body: JSON.stringify({ outcome }), + }); +} + +export const registry = setup({ use: { auctionActor } }); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.auctionActor.getOrCreate(["item-123"]); + +await handle.send("bids", { amount: 100 }); +console.log(await handle.getState()); +``` + +### Timeouts + +Use step timeouts and retries for slow or flaky dependencies. + +Step timeouts are critical by default and fail immediately. Set `retryOnTimeout: true` if a timeout should retry like any other error using `maxRetries`. + +```ts +import { actor, queue, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +async function chargeCard(orderId: string): Promise { + return `charge-${orderId}`; +} + +export const timeoutActor = actor({ + state: { + lastChargeId: null as string | null, + }, + queues: { + charge: queue<{ orderId: string }>(), + }, + run: workflow(async (ctx) => { + await ctx.loop("charge-loop", async (loopCtx) => { + const message = await loopCtx.queue.next("wait-charge"); + + const chargeId = await loopCtx.step({ + name: "charge-card", + timeout: 5_000, + retryOnTimeout: true, + maxRetries: 5, + retryBackoffBase: 200, + retryBackoffMax: 2_000, + run: async () => await chargeCard(message.body.orderId), + }); + + await loopCtx.step("save-charge", async () => { + loopCtx.state.lastChargeId = chargeId; + }); + + }); + }), +}); + +export const registry = setup({ use: { timeoutActor } }); +``` + +### Handling terminal failures as data + +Use `tryStep` when a step failure should produce data instead of failing the whole workflow. + +```ts +import { actor, setup } from "rivetkit"; +import { workflow } from "rivetkit/workflow"; + +export const paymentActor = actor({ + state: { + status: "pending" as "pending" | "manual-review" | "paid", + reason: null as string | null, + }, + run: workflow(async (ctx) => { + const charge = await ctx.tryStep({ + name: "charge-card", + maxRetries: 3, + run: async () => await chargeCard("order-123"), + }); + + await ctx.step("store-charge-result", async () => { + if (!charge.ok) { + ctx.state.status = "manual-review"; + ctx.state.reason = charge.failure.error.message; + return; + } + + ctx.state.status = "paid"; + ctx.state.reason = null; + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +async function chargeCard(orderId: string): Promise { + return `charge-${orderId}`; +} + +export const registry = setup({ use: { paymentActor } }); +``` + +Use `try` when you want to recover from terminal `step`, `join`, or `race` failures inside a named block. + +```ts +async function runPaymentFlow(ctx: any) { + return await ctx.try("payment-flow", async (blockCtx: any) => { + const auth = await blockCtx.step("authorize", async () => + authorizeOrder("order-123"), + ); + const capture = await blockCtx.step("capture", async () => + captureOrder("order-123"), + ); + return { auth, capture }; + }); +} + +async function authorizeOrder(orderId: string): Promise { + return `auth-${orderId}`; +} + +async function captureOrder(orderId: string): Promise { + return `capture-${orderId}`; +} +``` + +- `tryStep` and `try` only catch terminal failures. Retry backoff, sleeps, queue waits, eviction, and history divergence still rethrow. +- `RollbackError` is not caught by default. Pass `catch: ["rollback"]` when you want rollback failures returned as data. + +### Error hooks + +Use `onError` when you want a best-effort notification for workflow failures. + +- Step failures include the attempt number, retry counts, whether the step will retry, and the next retry delay. +- Workflow failures also include terminal errors outside steps, such as rollback failures or code/history mismatches. +- The hook is observational. It is not part of workflow replay, so use it for logging, metrics, or updating non-critical actor state. +- This is also a good place to forward workflow failures to Sentry or another error reporting pipeline. + +```ts +import { actor, event, setup } from "rivetkit"; +import { workflow, type WorkflowErrorEvent } from "rivetkit/workflow"; + +export const errorHookActor = actor({ + state: { + lastError: null as WorkflowErrorEvent | null, + }, + events: { + workflowError: event<[WorkflowErrorEvent]>(), + }, + run: workflow( + async (ctx) => { + await ctx.step({ + name: "sync-ledger", + maxRetries: 3, + retryBackoffBase: 250, + retryBackoffMax: 1_000, + run: async () => { + throw new Error("ledger unavailable"); + }, + }); + }, + { + onError: (c, event) => { + c.state.lastError = event; + c.broadcast("workflowError", event); + }, + }, + ), + actions: { + getState: (c) => c.state, + }, +}); + +export const registry = setup({ use: { errorHookActor } }); +``` + +### Rollback + +Use rollback checkpoints before steps that have compensating actions. + +```ts +import { actor, queue, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +export const checkoutActor = actor({ + state: { status: "pending" as string }, + queues: { + orders: queue<{ orderId: string }>(), + }, + run: workflow(async (ctx) => { + await ctx.loop("checkout-loop", async (loopCtx) => { + const message = await loopCtx.queue.next("wait-order"); + + await loopCtx.rollbackCheckpoint("checkout-checkpoint"); + + await loopCtx.step({ + name: "reserve-inventory", + run: () => reserveInventory(message.body.orderId), + rollback: async (_rollbackCtx, id) => { + await releaseInventory(id as string); + }, + }); + + await loopCtx.step({ + name: "charge-card", + run: () => chargeCard(message.body.orderId), + rollback: async (_rollbackCtx, chargeId) => { + await refundCharge(chargeId as string); + }, + }); + + await loopCtx.step("confirm", async () => { + loopCtx.state.status = "confirmed"; + }); + + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +async function reserveInventory(orderId: string): Promise { + const res = await fetch("https://api.example.com/inventory/reserve", { + method: "POST", + body: JSON.stringify({ orderId }), + }); + return ((await res.json()) as { reservationId: string }).reservationId; +} + +async function releaseInventory(reservationId: string): Promise { + await fetch(`https://api.example.com/inventory/${reservationId}/release`, { + method: "POST", + }); +} + +async function chargeCard(orderId: string): Promise { + const res = await fetch("https://api.stripe.com/v1/charges", { + method: "POST", + headers: { Authorization: `Bearer ${process.env.STRIPE_KEY}` }, + body: JSON.stringify({ orderId }), + }); + return ((await res.json()) as { id: string }).id; +} + +async function refundCharge(chargeId: string): Promise { + await fetch("https://api.stripe.com/v1/refunds", { + method: "POST", + headers: { Authorization: `Bearer ${process.env.STRIPE_KEY}` }, + body: JSON.stringify({ charge: chargeId }), + }); +} + +export const registry = setup({ use: { checkoutActor } }); +``` + +## Patterns + +### Store workflow progress in state + broadcast + +Store progress in `state` so replay and recovery always restore it. Broadcast state changes so clients can render progress in realtime. + +```ts index.ts +import { actor, event, queue, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +type Progress = { + stage: "idle" | "running" | "completed"; + completed: number; + total: number; +}; + +export const progressActor = actor({ + state: { + progress: { + stage: "idle", + completed: 0, + total: 0, + } as Progress, + sum: 0, + }, + events: { + progressUpdated: event(), + }, + queues: { + jobs: queue<{ value: number }>(), + }, + run: workflow(async (ctx) => { + await ctx.loop("progress-loop", async (loopCtx) => { + const message = await loopCtx.queue.next("wait-job"); + + await loopCtx.step("mark-running", async () => + markProgressRunning(loopCtx), + ); + + await loopCtx.step("apply-job", async () => + applyProgressJob(loopCtx, message.body.value), + ); + + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +function markProgressRunning(ctx: WorkflowLoopContextOf): void { + ctx.state.progress = { + stage: "running", + completed: ctx.state.progress.completed, + total: ctx.state.progress.total + 1, + }; + ctx.broadcast("progressUpdated", ctx.state.progress); +} + +function applyProgressJob( + ctx: WorkflowLoopContextOf, + value: number, +): void { + ctx.state.sum += value; + ctx.state.progress = { + stage: "completed", + completed: ctx.state.progress.completed + 1, + total: ctx.state.progress.total, + }; + ctx.broadcast("progressUpdated", ctx.state.progress); +} + +export const registry = setup({ use: { progressActor } }); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.progressActor.getOrCreate(["main"]); +const conn = handle.connect(); + +conn.on("progressUpdated", (progress) => { + console.log("progress", progress); +}); + +await handle.send("jobs", { value: 5 }); +await handle.send("jobs", { value: 7 }); + +console.log(await handle.getState()); +``` + +### Cron (queue-driven) + +Rivet scheduling triggers actions. For cron-like workflows, use a small scheduled action as a bridge that enqueues work, then process that work in the workflow loop. + +```ts +import { actor, queue, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +function nextMinute(timestamp: number): number { + const minuteMs = 60_000; + return Math.floor(timestamp / minuteMs) * minuteMs + minuteMs; +} + +export const cronActor = actor({ + state: { + runs: 0, + lastRunAt: null as number | null, + }, + queues: { + "cron-tick": queue<{ scheduledAt: number }>(), + }, + onCreate: async (c) => { + const firstTickAt = nextMinute(Date.now()); + await c.schedule.at(firstTickAt, "enqueueCronTick", firstTickAt); + }, + actions: { + enqueueCronTick: async (c, scheduledAt: number) => { + await c.queue.send("cron-tick", { scheduledAt }); + + const nextTickAt = nextMinute(scheduledAt + 1); + await c.schedule.at(nextTickAt, "enqueueCronTick", nextTickAt); + }, + getState: (c) => c.state, + }, + run: workflow(async (ctx) => { + await ctx.loop("cron-loop", async (loopCtx) => { + const message = await loopCtx.queue.next("wait-cron-tick"); + + await loopCtx.step("run-cron-job", async () => { + loopCtx.state.runs += 1; + loopCtx.state.lastRunAt = message.body.scheduledAt; + }); + + }); + }), +}); + +export const registry = setup({ use: { cronActor } }); +``` + +These are common workflow shapes used in production systems. + +### Queue-driven worker + +Use this when external systems enqueue work and the actor should process each item durably. + +```ts +import { actor, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +type Job = { id: string; amount: number }; + +export const queueWorkerActor = actor({ + state: { + processed: 0, + totalAmount: 0, + }, + run: workflow(async (ctx) => { + await ctx.loop("worker-loop", async (loopCtx) => { + const [message] = await loopCtx.queue.nextBatch("wait-job", { + timeout: 30_000, + }); + + if (!message) return; + const job = message.body as Job; + + await loopCtx.step("process-job", async () => { + loopCtx.state.processed += 1; + loopCtx.state.totalAmount += job.amount; + }); + + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +export const registry = setup({ use: { queueWorkerActor } }); +``` + +### Setup & teardown + +Use this when you need one-time initialization before a long-lived loop, plus cleanup when the actor stops sleeping or is destroyed. + +```ts +import { actor, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +function openResource(): string { + return "connected"; +} + +function closeResource(_resource: string): void {} + +export const setupRunTeardownActor = actor({ + vars: { + resource: null as string | null, + }, + state: { + initialized: false, + ticks: 0, + }, + onWake: (c) => { + c.vars.resource = openResource(); + }, + onSleep: (c) => { + if (!c.vars.resource) return; + closeResource(c.vars.resource); + c.vars.resource = null; + }, + run: workflow(async (ctx) => { + await ctx.step("setup", async () => { + if (!ctx.vars.resource) ctx.vars.resource = openResource(); + ctx.state.initialized = true; + }); + + await ctx.loop("main-loop", async (loopCtx) => { + await loopCtx.sleep("tick", 1_000); + await loopCtx.step("tick-step", async () => { + loopCtx.state.ticks += 1; + }); + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +export const registry = setup({ use: { setupRunTeardownActor } }); +``` + +### Human approval gate + +Use this when an operation must pause for a user or system decision before continuing. + +```ts +import { actor, queue, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +export const approvalGateActor = actor({ + state: { status: "pending" as string }, + queues: { + approval: queue<{ approved: boolean }>(), + }, + run: workflow(async (ctx) => { + await ctx.step("validate-order", async () => { + await validateOrder("order-123"); + ctx.state.status = "awaiting_approval"; + }); + + const decision = await ctx.queue.next("wait-approval"); + + if (decision.body.approved) { + await ctx.step("fulfill-order", async () => { + await fulfillOrder("order-123"); + ctx.state.status = "fulfilled"; + }); + } else { + await ctx.step("cancel-order", async () => { + await cancelOrder("order-123"); + ctx.state.status = "cancelled"; + }); + } + }), + actions: { + getState: (c) => c.state, + }, +}); + +async function validateOrder(orderId: string): Promise { + const res = await fetch( + `https://api.example.com/orders/${orderId}/validate`, + { method: "POST" }, + ); + if (!res.ok) throw new Error("Order validation failed"); +} + +async function fulfillOrder(orderId: string): Promise { + await fetch(`https://api.example.com/orders/${orderId}/fulfill`, { + method: "POST", + }); +} + +async function cancelOrder(orderId: string): Promise { + await fetch(`https://api.example.com/orders/${orderId}/cancel`, { + method: "POST", + }); +} + +export const registry = setup({ use: { approvalGateActor } }); +``` + +### Fan-out / fan-in (join) + +Use this when independent work items can run in parallel and you need a single merged result. + +```ts +import { actor, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +export const fanInOutActor = actor({ + state: { + total: 0, + }, + run: workflow(async (ctx) => { + await ctx.loop("join-loop", async (loopCtx) => { + const [message] = await loopCtx.queue.nextBatch("wait-refresh", { + timeout: 30_000, + }); + + if (!message) return; + + const joined = await loopCtx.join("parallel-work", { + users: { + run: async (branchCtx) => + await branchCtx.step("fetch-users", () => fetchCount("/users")), + }, + orders: { + run: async (branchCtx) => + await branchCtx.step("fetch-orders", () => fetchCount("/orders")), + }, + invoices: { + run: async (branchCtx) => + await branchCtx.step("fetch-invoices", () => fetchCount("/invoices")), + }, + }); + + await loopCtx.step("merge-results", async () => { + loopCtx.state.total = + joined.users + joined.orders + joined.invoices; + }); + + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +async function fetchCount(path: string): Promise { + const res = await fetch(`https://api.example.com${path}`); + if (!res.ok) throw new Error(`fetch ${path} failed: ${res.status}`); + return ((await res.json()) as { count: number }).count; +} + +export const registry = setup({ use: { fanInOutActor } }); +``` + +### Batch drainer + +Use this when throughput matters and handling one message at a time is too expensive. + +```ts +import { actor, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +type MetricMessage = { value: number }; + +export const batchDrainerActor = actor({ + state: { + pending: [] as number[], + flushedBatches: 0, + lastBatchTotal: 0, + }, + run: workflow(async (ctx) => { + await ctx.loop("drain-loop", async (loopCtx) => { + const [message] = await loopCtx.queue.nextBatch("wait-metric", { + timeout: 5_000, + }); + + if (message) { + const metric = message.body as MetricMessage; + await loopCtx.step("buffer-message", async () => { + loopCtx.state.pending.push(metric.value); + }); + } + + if (loopCtx.state.pending.length < 5) return; + + await loopCtx.step("flush-batch", async () => flushBatch(loopCtx)); + + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +function flushBatch(ctx: WorkflowLoopContextOf): void { + const total = ctx.state.pending.reduce( + (sum: number, value: number) => sum + value, + 0, + ); + ctx.state.lastBatchTotal = total; + ctx.state.flushedBatches += 1; + ctx.state.pending = []; +} + +export const registry = setup({ use: { batchDrainerActor } }); +``` + +### Coordinator -> worker RPC + +Use this when one actor orchestrates work by calling actions on other actors. + +```ts +import { actor, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +type TaskMessage = { + taskId: string; + workerId: string; + value: number; +}; + +export const workerActor = actor({ + actions: { + runTask: async (_c, value: number) => value * 2, + }, +}); + +export const coordinatorActor = actor({ + state: { + lastTaskId: null as string | null, + lastResult: 0, + }, + run: workflow(async (ctx) => { + await ctx.loop("orchestrator-loop", async (loopCtx) => { + const [message] = await loopCtx.queue.nextBatch("wait-task", { + timeout: 30_000, + }); + + if (!message) return; + const task = message.body as TaskMessage; + + const result = await loopCtx.step("dispatch-rpc", async () => + dispatchTask(loopCtx, task), + ); + + await loopCtx.step("record-result", async () => { + loopCtx.state.lastTaskId = task.taskId; + loopCtx.state.lastResult = result as number; + }); + + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +async function dispatchTask( + ctx: WorkflowLoopContextOf, + task: TaskMessage, +): Promise { + const client = ctx.client(); + const worker = client.workerActor.getOrCreate([task.workerId]); + return await worker.runTask(task.value); +} + +export const registry = setup({ use: { coordinatorActor, workerActor } }); +``` + +### Request/response over queue (async RPC) + +Use this when you want decoupled actor-to-actor communication with durable waits and explicit completion. + +```ts index.ts +import { actor, queue, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +type RequestMessage = { value: number }; + +export const requestResponseActor = actor({ + state: { + handled: 0, + }, + queues: { + requests: queue(), + }, + run: workflow(async (ctx) => { + await ctx.loop("request-response-loop", async (loopCtx) => { + const message = await loopCtx.queue.next("wait-request", { + completable: true, + }); + + if (!message.complete) return; + + const doubled = await loopCtx.step("handle-request", async () => { + loopCtx.state.handled += 1; + return message.body.value * 2; + }); + + await message.complete({ doubled }); + }); + }), +}); + +export const registry = setup({ use: { requestResponseActor } }); +``` + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const handle = client.requestResponseActor.getOrCreate(["main"]); + +const result = await handle.send("requests", { value: 21 }, { wait: true }); + +if (result.status === "completed") { + const response = result.response as { doubled: number }; + console.log(response.doubled); +} +``` + +### Scatter-gather across actors + +Use this when multiple actors can process independent parts of a request in parallel, then return a merged response. + +```ts +import { actor, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +type ScatterMessage = { input: number }; + +export const shardActor = actor({ + actions: { + compute: async (_c, input: number) => input * 10, + }, +}); + +export const scatterGatherActor = actor({ + state: { + lastSum: 0, + }, + run: workflow(async (ctx) => { + await ctx.loop("scatter-gather-loop", async (loopCtx) => { + const [message] = await loopCtx.queue.nextBatch("wait-scatter", { + timeout: 30_000, + }); + + if (!message) return; + const scatter = message.body as ScatterMessage; + + const gathered = await loopCtx.join("gather", { + shardA: { + run: async (joinCtx) => + await joinCtx.step("call-shard-a", async () => + callShard(joinCtx, "a", scatter.input), + ), + }, + shardB: { + run: async (joinCtx) => + await joinCtx.step("call-shard-b", async () => + callShard(joinCtx, "b", scatter.input), + ), + }, + shardC: { + run: async (joinCtx) => + await joinCtx.step("call-shard-c", async () => + callShard(joinCtx, "c", scatter.input), + ), + }, + }); + + await loopCtx.step("aggregate", async () => { + loopCtx.state.lastSum = gathered.shardA + gathered.shardB + gathered.shardC; + }); + + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +async function callShard( + ctx: WorkflowLoopContextOf, + shardId: "a" | "b" | "c", + input: number, +): Promise { + const client = ctx.client(); + const handle = client.shardActor.getOrCreate([shardId]); + return await handle.compute(input); +} + +export const registry = setup({ use: { scatterGatherActor, shardActor } }); +``` + +### Timeout + fallback actor + +Use this when a primary actor call might be slow or unavailable and you need a deterministic fallback path. + +```ts +import { actor, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +export const primaryServiceActor = actor({ + actions: { + fetchValue: async () => { + await new Promise((resolve) => setTimeout(resolve, 500)); + return "primary"; + }, + }, +}); + +export const fallbackServiceActor = actor({ + actions: { + fetchValue: async () => "fallback", + }, +}); + +export const timeoutFallbackActor = actor({ + state: { + lastSource: "none" as "none" | "primary" | "fallback", + lastValue: "", + }, + run: workflow(async (ctx) => { + await ctx.loop("timeout-loop", async (loopCtx) => { + await loopCtx.queue.nextBatch("wait-request", { + timeout: 30_000, + }); + + const winner = await loopCtx.race("primary-vs-timeout", [ + { + name: "primary", + run: async (raceCtx) => + await raceCtx.step("call-primary", async () => + callPrimaryValue(raceCtx), + ), + }, + { + name: "timeout", + run: async (raceCtx) => { + await raceCtx.sleep("primary-timeout", 200); + return "timeout"; + }, + }, + ]); + + let value = winner.value as string; + let source: "primary" | "fallback" = "primary"; + + if (winner.winner === "timeout") { + value = (await loopCtx.step("fallback-call", async () => + callFallbackValue(loopCtx), + )) as string; + source = "fallback"; + } + + await loopCtx.step("record-choice", async () => { + loopCtx.state.lastSource = source; + loopCtx.state.lastValue = value; + }); + + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +async function callPrimaryValue( + ctx: WorkflowLoopContextOf, +): Promise { + const client = ctx.client(); + const primary = client.primaryServiceActor.getOrCreate(["main"]); + return await primary.fetchValue(); +} + +async function callFallbackValue( + ctx: WorkflowLoopContextOf, +): Promise { + const client = ctx.client(); + const fallback = client.fallbackServiceActor.getOrCreate(["main"]); + return await fallback.fetchValue(); +} + +export const registry = setup({ + use: { timeoutFallbackActor, primaryServiceActor, fallbackServiceActor }, +}); +``` + +### Cross-actor saga (compensating actions) + +Use this when a workflow spans multiple actors and each side effect may need compensation. + +```ts +import { actor, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +type CheckoutMessage = { + orderId: string; + amount: number; +}; + +export const inventoryActor = actor({ + actions: { + reserve: async (_c, orderId: string) => `reserve-${orderId}`, + release: async (_c, reservationId: string) => reservationId, + }, +}); + +export const billingActor = actor({ + actions: { + charge: async (_c, amount: number) => `charge-${amount}`, + refund: async (_c, chargeId: string) => chargeId, + }, +}); + +export const checkoutSagaActor = actor({ + state: { + completedOrders: 0, + }, + run: workflow(async (ctx) => { + await ctx.loop("checkout-loop", async (loopCtx) => { + const [message] = await loopCtx.queue.nextBatch("wait-order", { + timeout: 30_000, + }); + + if (!message) return; + const checkout = message.body as CheckoutMessage; + + await loopCtx.rollbackCheckpoint("checkout-saga"); + + await loopCtx.step({ + name: "reserve-inventory", + run: async () => reserveInventoryForCheckout(loopCtx, checkout.orderId), + // Rollback callbacks only receive a rollback context, not actor + // APIs like client(). Compensate with direct external calls. + rollback: async (_rollbackCtx, output) => { + await releaseInventoryForCheckout(output as string); + }, + }); + + await loopCtx.step({ + name: "charge-card", + run: async () => chargeCheckout(loopCtx, checkout.amount), + rollback: async (_rollbackCtx, output) => { + await refundCheckout(output as string); + }, + }); + + await loopCtx.step("mark-complete", async () => markOrderComplete(loopCtx)); + + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +async function reserveInventoryForCheckout( + ctx: WorkflowLoopContextOf, + orderId: string, +): Promise { + const client = ctx.client(); + const inventory = client.inventoryActor.getOrCreate(["main"]); + return await inventory.reserve(orderId); +} + +async function releaseInventoryForCheckout( + reservationId: string, +): Promise { + await fetch("https://api.example.com/inventory/release", { + method: "POST", + body: JSON.stringify({ reservationId }), + }); +} + +async function chargeCheckout( + ctx: WorkflowLoopContextOf, + amount: number, +): Promise { + const client = ctx.client(); + const billing = client.billingActor.getOrCreate(["main"]); + return await billing.charge(amount); +} + +async function refundCheckout( + chargeId: string, +): Promise { + await fetch("https://api.example.com/billing/refund", { + method: "POST", + body: JSON.stringify({ chargeId }), + }); +} + +function markOrderComplete( + ctx: WorkflowLoopContextOf, +): void { + ctx.state.completedOrders += 1; +} + +export const registry = setup({ + use: { checkoutSagaActor, inventoryActor, billingActor }, +}); +``` + +### Signal-driven control loop + +Use this when workflow progress should be triggered by commands/events instead of fixed polling intervals. + +```ts +import { actor, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +type ControlSignal = { kind: "pause" | "resume" | "stop" }; + +export const controlLoopActor = actor({ + state: { + mode: "running" as "running" | "paused" | "stopped", + handledSignals: 0, + }, + run: workflow(async (ctx) => { + await ctx.loop("control-loop", async (loopCtx) => { + const [message] = await loopCtx.queue.nextBatch("wait-signal", { + timeout: 30_000, + }); + + if (!message) return; + const signal = message.body as ControlSignal; + + await loopCtx.step("apply-signal", async () => + applyControlSignal(loopCtx, signal.kind), + ); + + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +function applyControlSignal( + ctx: WorkflowLoopContextOf, + kind: ControlSignal["kind"], +): void { + ctx.state.handledSignals += 1; + if (kind === "pause") ctx.state.mode = "paused"; + if (kind === "resume") ctx.state.mode = "running"; + if (kind === "stop") ctx.state.mode = "stopped"; +} + +export const registry = setup({ use: { controlLoopActor } }); +``` + +### Poll + backoff loop + +Use this when an external dependency has variable availability and retries should slow down after failures. + +```ts +import { actor, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +async function pollExternal(attempt: number): Promise { + return attempt % 3 === 0; +} + +export const pollBackoffActor = actor({ + state: { + attempts: 0, + backoffMs: 100, + status: "unknown" as "unknown" | "healthy" | "retrying", + }, + run: workflow(async (ctx) => { + await ctx.loop("poll-loop", async (loopCtx) => { + const success = await loopCtx.step("poll-target", async () => { + loopCtx.state.attempts += 1; + return pollExternal(loopCtx.state.attempts); + }); + + if (success) { + await loopCtx.step("reset-backoff", async () => { + loopCtx.state.status = "healthy"; + loopCtx.state.backoffMs = 100; + }); + await loopCtx.sleep("healthy-interval", 1_000); + return; + } + + const retryDelay = await loopCtx.step("grow-backoff", async () => { + loopCtx.state.status = "retrying"; + loopCtx.state.backoffMs = Math.min(loopCtx.state.backoffMs * 2, 5_000); + return loopCtx.state.backoffMs; + }); + + await loopCtx.sleep("retry-delay", retryDelay); + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +export const registry = setup({ use: { pollBackoffActor } }); +``` + +### Child worker orchestration + +Use this when one workflow coordinates many child workers (actors or worker workflows) and manages their lifecycle. + +```ts +import { actor, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +type BatchMessage = { payload: number }; + +export const childWorkerActor = actor({ + actions: { + process: async (_c, payload: number) => payload * 3, + }, +}); + +export const orchestratorActor = actor({ + state: { + lastTotal: 0, + }, + run: workflow(async (ctx) => { + await ctx.step("start-children", async () => startChildren(ctx)); + + await ctx.loop("orchestrate-loop", async (loopCtx) => { + const [message] = await loopCtx.queue.nextBatch("wait-batch", { + timeout: 30_000, + }); + + if (!message) return; + const batch = message.body as BatchMessage; + + const results = await loopCtx.join("collect-updates", { + a: { + run: async (joinCtx) => + await joinCtx.step("run-child-a", async () => + runChildWorker(joinCtx, "child-a", batch.payload), + ), + }, + b: { + run: async (joinCtx) => + await joinCtx.step("run-child-b", async () => + runChildWorker(joinCtx, "child-b", batch.payload), + ), + }, + c: { + run: async (joinCtx) => + await joinCtx.step("run-child-c", async () => + runChildWorker(joinCtx, "child-c", batch.payload), + ), + }, + }); + + await loopCtx.step("reconcile", async () => { + loopCtx.state.lastTotal = results.a + results.b + results.c; + }); + + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +async function startChildren( + ctx: WorkflowContextOf, +): Promise { + const client = ctx.client(); + await client.childWorkerActor.getOrCreate(["child-a"]).process(0); + await client.childWorkerActor.getOrCreate(["child-b"]).process(0); + await client.childWorkerActor.getOrCreate(["child-c"]).process(0); +} + +async function runChildWorker( + ctx: WorkflowBranchContextOf, + workerId: "child-a" | "child-b" | "child-c", + payload: number, +): Promise { + const client = ctx.client(); + return await client.childWorkerActor.getOrCreate([workerId]).process(payload); +} + +export const registry = setup({ use: { orchestratorActor, childWorkerActor } }); +``` + +### Bounded drain + concurrency cap + +Use this when inbound work can spike and you need predictable per-iteration limits. + +```ts +import { actor, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +type WorkMessage = { id: string; value: number }; + +const MAX_PER_ITERATION = 10; +const CONCURRENCY_LIMIT = 3; + +async function processWork(value: number): Promise { + return value * 2; +} + +async function runWithLimit( + limit: number, + items: T[], + fn: (item: T) => Promise, +): Promise { + let nextIndex = 0; + const workers = Array.from({ length: limit }, async () => { + while (nextIndex < items.length) { + const current = items[nextIndex]; + nextIndex += 1; + await fn(current); + } + }); + await Promise.all(workers); +} + +export const boundedDrainActor = actor({ + state: { + processed: 0, + lastWindowSize: 0, + lastWindowTotal: 0, + }, + run: workflow(async (ctx) => { + await ctx.loop("bounded-drain-loop", async (loopCtx) => { + const window: WorkMessage[] = []; + + for (let i = 0; i < MAX_PER_ITERATION; i += 1) { + const [message] = await loopCtx.queue.nextBatch("wait-work", { + timeout: i === 0 ? 30_000 : 10, + }); + if (!message) break; + window.push(message.body as WorkMessage); + } + + if (window.length === 0) return; + + await loopCtx.step("process-window", async () => + processWindow(loopCtx, window), + ); + + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +async function processWindow( + ctx: WorkflowLoopContextOf, + window: WorkMessage[], +): Promise { + let windowTotal = 0; + await runWithLimit(CONCURRENCY_LIMIT, window, async (work) => { + const result = await processWork(work.value); + windowTotal += result; + }); + + ctx.state.processed += window.length; + ctx.state.lastWindowSize = window.length; + ctx.state.lastWindowTotal = windowTotal; +} + +export const registry = setup({ use: { boundedDrainActor } }); +``` + +### Versioned workflow evolution + +Use this when workflow structure changes across deployments and old histories must still replay. + +```ts +import { actor, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +export const versionedWorkflowActor = actor({ + state: { + runs: 0, + }, + run: workflow(async (ctx) => { + await ctx.step("validate-v2", async () => { + ctx.state.runs += 1; + }); + + await ctx.removed("validate-v1", "step"); + + await ctx.loop("main-loop-v2", async (loopCtx) => { + await loopCtx.sleep("idle", 500); + await loopCtx.step("heartbeat-v2", async () => { + loopCtx.state.runs += 1; + }); + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +export const registry = setup({ use: { versionedWorkflowActor } }); +``` + +### Checkpoint-friendly loop design + +Use this when you need reliable replay and resume semantics across crashes and restarts. + +```ts +import { actor, setup } from "rivetkit"; +import { type WorkflowContextOf, type WorkflowLoopContextOf, type WorkflowBranchContextOf, workflow } from "rivetkit/workflow"; + +type PaymentMessage = { id: string; amount: number }; + +export const checkpointFriendlyActor = actor({ + state: { + appliedCount: 0, + totalAmount: 0, + lastPaymentId: null as string | null, + }, + run: workflow(async (ctx) => { + await ctx.loop("payment-loop", async (loopCtx) => { + const [message] = await loopCtx.queue.nextBatch("wait-payment", { + timeout: 30_000, + }); + + if (!message) return; + const payment = message.body as PaymentMessage; + + await loopCtx.rollbackCheckpoint("apply-payment-checkpoint"); + + const plan = (await loopCtx.step("build-plan", async () => + buildPaymentPlan(payment), + )) as { paymentId: string; amount: number }; + + await loopCtx.step("apply-side-effects", async () => { + loopCtx.state.appliedCount += 1; + loopCtx.state.totalAmount += plan.amount; + loopCtx.state.lastPaymentId = plan.paymentId; + }); + + }); + }), + actions: { + getState: (c) => c.state, + }, +}); + +function buildPaymentPlan(payment: PaymentMessage): { + paymentId: string; + amount: number; +} { + return { + paymentId: payment.id, + amount: payment.amount, + }; +} + +export const registry = setup({ use: { checkpointFriendlyActor } }); +``` + +## Migrations + +- Keep workflow entry names stable once deployed. +- If an old entry was removed or renamed, call `ctx.removed(name, originalType)`. +- This keeps replay compatible across deployments. + +## Step-only access to actor APIs + +`state`, `vars`, `db`, `client()`, and connection/event APIs are only valid inside `ctx.step(...)` callbacks. + +Use non-step workflow code for orchestration only: queue waits, sleeps, loops, joins, races, and rollback boundaries. Keep actor-local side effects in steps. + +## Debugging + +- `GET /inspector/workflow-history` returns workflow history status for an actor. +- Response includes `isWorkflowEnabled` and `history`. +- In non-dev mode, inspector endpoints require authorization. + +## Recommendations + +- Prefer queue-driven loops for long-lived workflows. +- Structure long-lived workflows with setup and teardown around the main loop. +- Keep actor state changes and side effects inside steps. +- Store workflow progress in `state` and broadcast updates as progress changes. +- Use timeouts and rollback for external side effects. + +_Source doc path: /docs/actors/workflows_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/agent-to-agent.md b/.agents/skills/ai-agent-workspace/reference/agent-os/agent-to-agent.md new file mode 100644 index 0000000..a822c4d --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/agent-to-agent.md @@ -0,0 +1,111 @@ +# Agent-to-Agent Communication + +> Source: `src/content/docs/agent-os/agent-to-agent.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/agent-to-agent +> Description: Use host tools to let agents communicate with each other. + +--- +Agents communicate through [host tools](/docs/agent-os/tools). You define a toolkit that lets one agent send work to another, and the agent calls it like any other CLI command. + +## Example: code writer + reviewer + +This example creates a writer agent with a `review` tool. When the writer calls the tool, it reads the file from the writer's VM, writes it to a separate reviewer VM, and sends a review prompt. + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; +import { toolKit, hostTool } from "@rivet-dev/agent-os-core"; +import { createClient } from "rivetkit/client"; +import { z } from "zod"; + +// Tool that bridges the writer to the reviewer +const reviewToolkit = toolKit({ + name: "review", + description: "Send code to the reviewer agent", + tools: { + submit: hostTool({ + description: "Submit a file for code review", + inputSchema: z.object({ + path: z.string().describe("Path to the file to review"), + }), + execute: async (input) => { + const client = createClient("http://localhost:6420"); + const writerHandle = client.writer.getOrCreate(["my-project"]); + const reviewerHandle = client.reviewer.getOrCreate(["my-project"]); + + // Read file from writer, write to reviewer + const content = await writerHandle.readFile(input.path); + await reviewerHandle.writeFile(input.path, content); + + // Ask the reviewer to review + const session = await reviewerHandle.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, + }); + const response = await reviewerHandle.sendPrompt( + session.sessionId, + `Review the code at ${input.path} and list any issues.`, + ); + await reviewerHandle.closeSession(session.sessionId); + + return { review: response }; + }, + }), + }, +}); + +// Writer has the review toolkit, reviewer is plain +const writer = agentOs({ + options: { software: [common, pi], toolKits: [reviewToolkit] }, +}); +const reviewer = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { writer, reviewer } }); +registry.start(); +``` + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const writerAgent = client.writer.getOrCreate(["my-project"]); + +const session = await writerAgent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); + +// The writer will call `agentos-review submit --path /home/user/api.ts` +// when it's ready for a review +await writerAgent.sendPrompt( + session.sessionId, + "Write a REST API at /home/user/api.ts, then submit it for review.", +); +``` + +The writer agent sees the review tool as a CLI command: + +```bash +agentos-review submit --path /home/user/api.ts +``` + +When the writer calls this, the host tool reads the file from the writer's VM, writes it to the reviewer's VM, and sends a prompt to the reviewer. The review result is returned to the writer as JSON. + +## Why host tools? + +Host tools are the natural communication layer between agents because: + +- **The agent doesn't need to know about other agents.** It just calls a tool. You can swap the implementation without changing the agent's behavior. +- **No credentials in the VM.** The host tool executes on the server, so it can access other agents directly without exposing connection details. +- **Composable.** Chain any number of agents by adding more tools. Each tool is a self-contained bridge to another agent. + +## Recommendations + +- Each agent has its own isolated VM and filesystem. Use `readFile`/`writeFile` in host tools to pass files between them. +- Use [Queues](/docs/agent-os/queues) when agents need to process work asynchronously. +- Use [Workflows](/docs/agent-os/workflows) to make multi-agent pipelines durable across restarts. + +_Source doc path: /docs/agent-os/agent-to-agent_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/agents/pi.md b/.agents/skills/ai-agent-workspace/reference/agent-os/agents/pi.md new file mode 100644 index 0000000..c451c1d --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/agents/pi.md @@ -0,0 +1,80 @@ +# Pi + +> Source: `src/content/docs/agent-os/agents/pi.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/agents/pi +> Description: Run the Pi coding agent inside a VM with extensions and custom configuration. + +--- +## Quick start + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); + +const { text } = await agent.sendPrompt( + session.sessionId, + "What files are in the current directory?", +); +console.log(text); +``` + +Read [Sessions](/docs/agent-os/sessions) first for session options, streaming events, prompts, and lifecycle management. + +## Extensions + +Pi supports [extensions](https://github.com/badlogic/pi-mono/tree/main/packages/coding-agent/examples/extensions) that let you register custom tools, modify the system prompt, and hook into agent lifecycle events. Write a `.js` file into the VM's extensions directory before creating a session and Pi discovers it automatically. + +Pi scans two directories for `.js` extension files: + +| Directory | Scope | +|-----------|-------| +| `~/.pi/agent/extensions/` | Global — applies to all Pi sessions | +| `/.pi/extensions/` | Project — applies only when cwd matches | + +```ts @nocheck +const extensionCode = ` +module.exports = function(pi) { + // Modify the system prompt before each agent turn + pi.on("before_agent_start", async (event) => { + return { + systemPrompt: event.systemPrompt + + "\\n\\nAlways respond in formal English." + }; + }); +}; +`; + +// Write the extension before creating the session +await vm.mkdir("/home/user/.pi/agent/extensions", { recursive: true }); +await vm.writeFile("/home/user/.pi/agent/extensions/formal.js", extensionCode); + +// Pi discovers the extension automatically +const { sessionId } = await vm.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY }, +}); +``` + +See the [Pi extension documentation](https://github.com/badlogic/pi-mono/tree/main/packages/coding-agent/examples/extensions) for the full extension API. + +_Source doc path: /docs/agent-os/agents/pi_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/authentication.md b/.agents/skills/ai-agent-workspace/reference/agent-os/authentication.md new file mode 100644 index 0000000..4251a19 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/authentication.md @@ -0,0 +1,81 @@ +# Authentication + +> Source: `src/content/docs/agent-os/authentication.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/authentication +> Description: Authenticate connections to agentOS actors using hooks. + +--- +agentOS uses the same authentication system as Rivet Actors. Validate credentials in `onBeforeConnect` or extract user data with `createConnState`. + +For full documentation including JWT examples, role-based access control, rate limiting, and token caching, see [Actor Authentication](/docs/actors/authentication). + +## `onBeforeConnect` + +Validate credentials before allowing a connection. Throw an error to reject. + +```ts @nocheck +import { agentOs } from "rivetkit/agent-os"; +import { setup, UserError } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + onBeforeConnect: async (c, params: { authToken: string }) => { + const isValid = await validateToken(params.authToken); + if (!isValid) { + throw new UserError("Forbidden", { code: "forbidden" }); + } + }, + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## `createConnState` + +Extract user data from credentials and store it in connection state. Accessible in actions via `c.conn.state`. + +```ts @nocheck +import { agentOs } from "rivetkit/agent-os"; +import { setup, UserError } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +interface ConnState { + userId: string; + role: string; +} + +const vm = agentOs({ + createConnState: async (c, params: { authToken: string }): Promise => { + const payload = await validateToken(params.authToken); + if (!payload) { + throw new UserError("Forbidden", { code: "forbidden" }); + } + return { userId: payload.sub, role: payload.role }; + }, + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Client usage + +Pass credentials when connecting: + +```ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"], { + params: { authToken: "my-jwt-token" }, +}); +``` + +See [Actor Authentication](/docs/actors/authentication) for more patterns including external auth providers, role-based access control, and token caching. + +_Source doc path: /docs/agent-os/authentication_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/benchmarks.md b/.agents/skills/ai-agent-workspace/reference/agent-os/benchmarks.md new file mode 100644 index 0000000..3cab6d9 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/benchmarks.md @@ -0,0 +1,10 @@ +# Benchmarks + +> Source: `src/content/docs/agent-os/benchmarks.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/benchmarks +> Description: Performance benchmarks comparing agentOS to traditional sandbox providers. + +--- +These are the benchmark figures shown on the [agentOS page](/agent-os). All numbers are computed from the same data source used by the marketing page. For independent sandbox comparison data, see the [ComputeSDK benchmarks](https://www.computesdk.com/benchmarks/). + +_Source doc path: /docs/agent-os/benchmarks_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/configuration.md b/.agents/skills/ai-agent-workspace/reference/agent-os/configuration.md new file mode 100644 index 0000000..ee00d68 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/configuration.md @@ -0,0 +1,68 @@ +# Configuration + +> Source: `src/content/docs/agent-os/configuration.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/configuration +> Description: Configure the agentOS VM options, preview settings, and lifecycle hooks. + +--- +`agentOs()` accepts the following configuration object. + +```ts @nocheck +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { + // Custom filesystem mounts + mounts: [], + // Software packages to install in the VM (see /docs/agent-os/software) + software: [common, pi], + // Ports exempt from SSRF checks + loopbackExemptPorts: [3000], + // Host directory with node_modules + moduleAccessCwd: "/path/to/project", + // Extra instructions appended to agent system prompts + additionalInstructions: "Always write tests first.", + }, + + // Preview URL token lifetimes + preview: { + defaultExpiresInSeconds: 3600, // 1 hour (default) + maxExpiresInSeconds: 86400, // 24 hours (default) + }, + + // Called when a client connects. Throw to reject. See /docs/agent-os/authentication + onBeforeConnect: async (c, params) => { + const user = await verifyToken(params.token); + if (!user) throw new Error("Unauthorized"); + }, + // Called for every session event, server-side. Runs once per event. + onSessionEvent: async (c, sessionId, event) => { + console.log("Session event:", sessionId, event.method); + }, + // Called when an agent requests permission. See /docs/agent-os/permissions + onPermissionRequest: async (c, sessionId, request) => { + await c.respondPermission(sessionId, request.permissionId, "always"); + }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Session options + +Options passed to `createSession`. See [Sessions](/docs/agent-os/sessions) for full documentation. + +## Timeouts + +| Setting | Default | Description | +|---------|---------|-------------| +| Action timeout | 15 minutes | Maximum time for any single action | +| Sleep grace period | 15 minutes | Time before sleeping after all activity stops | + +These are set internally by the `agentOs()` factory and cannot be overridden per-call. See [Persistence & Sleep](/docs/agent-os/persistence) for details on the sleep lifecycle. + +_Source doc path: /docs/agent-os/configuration_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/core.md b/.agents/skills/ai-agent-workspace/reference/agent-os/core.md new file mode 100644 index 0000000..35f253a --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/core.md @@ -0,0 +1,270 @@ +# Core Package + +> Source: `src/content/docs/agent-os/core.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/core +> Description: Use @rivet-dev/agent-os-core standalone for direct VM control without the Rivet Actor runtime. + +--- +## agentOS vs agentOS Core + +The `agentOs()` actor (from `rivetkit/agent-os`) wraps the core package and adds: + +| | Core (`@rivet-dev/agent-os-core`) | Actor (`rivetkit/agent-os`) | +|-|---|---| +| Persistence | In-memory by default (pluggable via [mounts](#mounts)) | Persistent filesystem and sessions | +| Distributed state | Manage yourself | Built-in distributed statefulness | +| Stateful sandboxes | Complex to run yourself | Built into Rivet | +| Sleep/wake | Manual `dispose()` / `create()` | Automatic | +| Events | Direct callbacks | Broadcasted to all connected clients | +| Preview URLs | None | Built-in signed URL server | +| Multiplayer | N/A | Multiple clients on same actor | +| Orchestration | N/A | Workflows, queues, cron | +| Agent-to-agent communication | Custom | Built into [Rivet Actors](/docs/agent-os/agent-to-agent) | +| Authentication | Set up yourself | [Documentation](/docs/agent-os/authentication) | + +We recommend using [Rivet Actors](/docs/actors) because they provide a portable way to run agentOS on any infrastructure with built-in persistence, networking, and orchestration. Use the core package if you need the most bare-bones implementation possible. + +## Install + +```bash +npm install @rivet-dev/agent-os-core +``` + +## Boot a VM + +```ts @nocheck +import { AgentOs } from "@rivet-dev/agent-os-core"; +import common from "@rivet-dev/agent-os-common"; + +const vm = await AgentOs.create({ + software: [common], +}); + +// Run a command +const result = await vm.exec("echo hello"); +console.log(result.stdout); // "hello\n" + +await vm.dispose(); +``` + +## Filesystem + +```ts @nocheck +import { AgentOs } from "@rivet-dev/agent-os-core"; +import common from "@rivet-dev/agent-os-common"; + +const vm = await AgentOs.create({ software: [common] }); + +await vm.writeFile("/home/user/hello.txt", "Hello, world!"); +const content = await vm.readFile("/home/user/hello.txt"); +console.log(new TextDecoder().decode(content)); + +await vm.mkdir("/home/user/src"); +await vm.writeFiles([ + { path: "/home/user/src/index.ts", content: "console.log('hi');" }, + { path: "/home/user/src/utils.ts", content: "export const add = (a: number, b: number) => a + b;" }, +]); + +const entries = await vm.readdirRecursive("/home/user"); +for (const entry of entries) { + console.log(entry.type, entry.path); +} + +await vm.dispose(); +``` + +## Processes + +```ts @nocheck +import { AgentOs } from "@rivet-dev/agent-os-core"; +import common from "@rivet-dev/agent-os-common"; + +const vm = await AgentOs.create({ software: [common] }); + +// One-shot execution +const result = await vm.exec("ls -la /home/user"); +console.log(result.stdout); + +// Long-running process with streaming output +await vm.writeFile("/tmp/server.mjs", 'import http from "http"; http.createServer((req, res) => res.end("ok")).listen(3000); console.log("listening");'); +const proc = vm.spawn("node", ["/tmp/server.mjs"]); +vm.onProcessStdout(proc.pid, (data) => { + console.log("stdout:", new TextDecoder().decode(data)); +}); +vm.onProcessExit(proc.pid, (code) => { + console.log("exited:", code); +}); + +// Write to stdin +vm.writeProcessStdin(proc.pid, "some input\n"); + +// Stop or kill +vm.stopProcess(proc.pid); + +await vm.dispose(); +``` + +## Agent sessions + +The core package returns a `sessionId` string. All session operations are called on the `vm` instance with the session ID. + +```ts @nocheck +import { AgentOs } from "@rivet-dev/agent-os-core"; +import common from "@rivet-dev/agent-os-common"; + +const vm = await AgentOs.create({ software: [common] }); + +const { sessionId } = await vm.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); + +// Stream events +vm.onSessionEvent(sessionId, (event) => { + console.log(event.method, event.params); +}); + +// Handle permissions +vm.onPermissionRequest(sessionId, (request) => { + console.log("Permission:", request.description); + vm.respondPermission(sessionId, request.permissionId, "once"); +}); + +// Send a prompt +const response = await vm.prompt(sessionId, "Write a hello world script"); +console.log(response); + +// Configure the session +await vm.setSessionModel(sessionId, "claude-sonnet-4-6"); +await vm.setSessionMode(sessionId, "plan"); + +// Event history (returns SequencedEvent[] with .sequenceNumber and .notification) +const events = vm.getSessionEvents(sessionId); +for (const event of events) { + console.log(event.sequenceNumber, event.notification.method); +} + +vm.closeSession(sessionId); +await vm.dispose(); +``` + +## Interactive shell + +```ts @nocheck +import { AgentOs } from "@rivet-dev/agent-os-core"; +import common from "@rivet-dev/agent-os-common"; + +const vm = await AgentOs.create({ software: [common] }); + +const { shellId } = vm.openShell(); + +vm.onShellData(shellId, (data) => { + process.stdout.write(new TextDecoder().decode(data)); +}); + +vm.writeShell(shellId, "echo hello from shell\n"); + +// Resize terminal +vm.resizeShell(shellId, 120, 40); + +vm.closeShell(shellId); +await vm.dispose(); +``` + +## Networking + +```ts @nocheck +import { AgentOs } from "@rivet-dev/agent-os-core"; +import common from "@rivet-dev/agent-os-common"; + +const vm = await AgentOs.create({ software: [common] }); + +// Start a server inside the VM +await vm.writeFile("/tmp/app.mjs", 'import http from "http"; http.createServer((req, res) => res.end("hello")).listen(3000);'); +vm.spawn("node", ["/tmp/app.mjs"]); + +// Fetch from it +const response = await vm.fetch(3000, new Request("http://localhost/")); +console.log(await response.text()); + +await vm.dispose(); +``` + +## Cron jobs + +The core package supports a `"callback"` action type in addition to `"exec"` and `"session"`. + +```ts @nocheck +import { AgentOs } from "@rivet-dev/agent-os-core"; +import common from "@rivet-dev/agent-os-common"; + +const vm = await AgentOs.create({ software: [common] }); + +const job = vm.scheduleCron({ + id: "cleanup", + schedule: "0 * * * *", + action: { type: "exec", command: "rm", args: ["-rf", "/tmp/cache"] }, +}); + +// Or use a callback (not available in the actor wrapper) +vm.scheduleCron({ + schedule: "*/5 * * * *", + action: { + type: "callback", + fn: async () => { + console.log("Custom logic every 5 minutes"); + }, + }, +}); + +vm.onCronEvent((event) => { + if (event.type === "cron:fire") console.log("Job fired:", event.jobId); + if (event.type === "cron:complete") console.log("Job done:", event.jobId, event.durationMs, "ms"); + if (event.type === "cron:error") console.error("Job error:", event.error); +}); + +console.log(vm.listCronJobs()); +job.cancel(); + +await vm.dispose(); +``` + +## Mounts + +Configure filesystem backends at boot time. + +```ts @nocheck +import { AgentOs, createHostDirBackend, createInMemoryFileSystem } from "@rivet-dev/agent-os-core"; +import { createS3Backend } from "@rivet-dev/agent-os-s3"; +import common from "@rivet-dev/agent-os-common"; + +const vm = await AgentOs.create({ + software: [common], + mounts: [ + // Host directory (read-only) + { path: "/mnt/code", driver: createHostDirBackend({ hostPath: "/path/to/repo" }), readOnly: true }, + // S3 bucket + { path: "/mnt/data", driver: createS3Backend({ bucket: "my-bucket", prefix: "agent/" }) }, + // In-memory scratch space + { path: "/mnt/scratch", driver: createInMemoryFileSystem() }, + ], +}); + +const files = await vm.readdir("/mnt/code"); +console.log(files); + +await vm.dispose(); +``` + +## What you give up without the actor + +- **No built-in persistence.** The default filesystem is in-memory and lost on `dispose()`. You can configure your own [mounts](#mounts) (S3, host directories, etc.) for persistence. +- **No sleep/wake.** You manage the full VM lifecycle yourself. +- **No event broadcasting.** Events are local callbacks, not distributed to remote clients. +- **No preview URLs.** No built-in HTTP server for sharing VM services. +- **No multiplayer.** Single-process, single-client only. +- **No orchestration.** No workflows, queues, or scheduling integration. +- **No session persistence.** Session history is lost on dispose. + +If you need any of these, use the [`agentOs()` actor](/docs/agent-os/quickstart) instead. + +_Source doc path: /docs/agent-os/core_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/crash-course.md b/.agents/skills/ai-agent-workspace/reference/agent-os/crash-course.md new file mode 100644 index 0000000..4a0b417 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/crash-course.md @@ -0,0 +1,569 @@ +# Crash Course + +> Source: `src/content/docs/agent-os/crash-course.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/crash-course +> Description: Run coding agents inside isolated VMs with full filesystem, process, and network control. + +--- +agentOS is in preview and the API is subject to change. If you run into issues, please [report them on GitHub](https://github.com/rivet-dev/rivet/issues) or [join our Discord](https://rivet.dev/discord). + +## Features + +- **Isolated VMs**: Each agent gets its own filesystem, processes, and networking. No shared state, no cross-contamination. +- **Multi-Agent Support**: Run Amp, Claude Code, Codex, OpenCode, and PI with a unified API. Swap agents without changing your code. +- **Host Tools**: Expose your JavaScript functions to agents as CLI commands. Direct binding with near-zero latency and automatic code mode for up to 80% token reduction. +- **Persistent State**: Filesystem and transcripts survive sleep/wake cycles automatically. No external database needed. +- **Orchestration**: Workflows, queues, cron jobs, and multi-agent coordination built on Rivet Actors. +- **Hybrid Sandboxes**: Run agents in the lightweight VM by default. Spin up a full sandbox on demand for browsers, compilation, and desktop automation. + +## When to Use agentOS + +- **Coding agents**: Run any coding agent with full OS access, file editing, shell execution, and tool use. +- **Automated pipelines**: CI-like workflows where agents clone repos, fix bugs, run tests, and open PRs. +- **Multi-agent systems**: Coordinators dispatching to specialized agents, review pipelines, planning chains. +- **Scheduled maintenance**: Cron-based agents that audit code, update dependencies, or generate reports. +- **Collaborative workspaces**: Multiple users observing and interacting with the same agent session in realtime. + +## Minimal Project + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Subscribe to streaming events +agent.on("sessionEvent", (data) => { + console.log(data.event); +}); + +// Create a session and send a prompt +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +const response = await agent.sendPrompt( + session.sessionId, + "Write a hello world script to /home/user/hello.js", +); +console.log(response); + +// Read the file the agent created +const content = await agent.readFile("/home/user/hello.js"); +console.log(new TextDecoder().decode(content)); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +After the quickstart, customize your agent with the [Registry](/agent-os/registry). + +## Quick Reference + +### Sessions & Transcripts + +Create agent sessions, send prompts, and stream responses in realtime. Transcripts are persisted automatically across sleep/wake cycles. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Stream events as they arrive +agent.on("sessionEvent", (data) => { + console.log(data.event.method, data.event); +}); + +// Create a session with MCP servers +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, + mcpServers: [ + { + type: "local", + command: "npx", + args: ["-y", "@modelcontextprotocol/server-filesystem", "/home/user"], + env: {}, + }, + ], +}); + +// Send a prompt and wait for the response +const response = await agent.sendPrompt( + session.sessionId, + "List all files in the home directory", +); +console.log(response); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +[Documentation](/docs/agent-os/sessions) + +### Permissions + +Approve or deny agent tool use with human-in-the-loop patterns or auto-approve for trusted workloads. + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +// Auto-approve all permissions server-side +const vm = agentOs({ + onPermissionRequest: async (c, sessionId, request) => { + await c.respondPermission(sessionId, request.permissionId, "always"); + }, + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Or handle permissions client-side for human-in-the-loop +agent.on("permissionRequest", async (data) => { + console.log("Permission requested:", data.request); + // "once" | "always" | "reject" + await agent.respondPermission(data.sessionId, data.request.permissionId, "once"); +}); +``` + +[Documentation](/docs/agent-os/permissions) + +### Tools + +Expose your JavaScript functions to agents as CLI commands inside the VM. Agents call them as shell commands with auto-generated flags from Zod schemas. + +```ts @nocheck +import { toolKit, hostTool } from "@rivet-dev/agent-os-core"; +import { z } from "zod"; + +const myTools = toolKit({ + name: "myapp", + description: "Application tools", + tools: { + createTicket: hostTool({ + description: "Create a ticket in the issue tracker", + inputSchema: z.object({ + title: z.string().describe("Ticket title"), + priority: z.enum(["low", "medium", "high"]).describe("Priority level"), + }), + execute: async (input) => { + const ticket = await db.tickets.create(input); + return { id: ticket.id, url: ticket.url }; + }, + }), + }, +}); + +// Agent calls: agentos-myapp createTicket --title "Fix login" --priority high +``` + +[Documentation](/docs/agent-os/tools) + +### Filesystem + +Read, write, and manage files inside the VM. The `/home/user` directory is persisted automatically across sleep/wake cycles. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Write a file +await agent.writeFile("/home/user/config.json", JSON.stringify({ key: "value" })); + +// Read a file +const content = await agent.readFile("/home/user/config.json"); +console.log(new TextDecoder().decode(content)); + +// List directory contents recursively +const files = await agent.readdirRecursive("/home/user", { maxDepth: 2 }); +console.log(files); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +[Documentation](/docs/agent-os/filesystem) + +### Processes & Shell + +Execute commands, spawn long-running processes, and open interactive shells. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// One-shot execution +const result = await agent.exec("echo hello && ls /home/user"); +console.log("stdout:", result.stdout); +console.log("exit code:", result.exitCode); + +// Spawn a long-running process +agent.on("processOutput", (data) => { + console.log(`[${data.processId}]`, data.output); +}); + +const proc = await agent.spawn("node", ["server.js"]); +console.log("Process ID:", proc.processId); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +[Documentation](/docs/agent-os/processes) + +### Networking & Previews + +Proxy HTTP requests into VMs with `vmFetch`. Create preview URLs for port forwarding VM services to shareable public URLs. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Fetch from a service running inside the VM +const response = await agent.vmFetch(3000, "/api/health"); +console.log("Status:", response.status); + +// Create a preview URL (port forwarding to a public URL) +const preview = await agent.createSignedPreviewUrl(3000); +console.log("Public URL:", preview.path); +console.log("Expires at:", new Date(preview.expiresAt)); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +[Documentation](/docs/agent-os/networking) + +### Cron Jobs + +Schedule recurring commands and agent sessions with cron expressions. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Schedule a command every hour +await agent.scheduleCron({ + schedule: "0 * * * *", + action: { type: "exec", command: "rm", args: ["-rf", "/tmp/cache/*"] }, +}); + +// Schedule an agent session daily at 9 AM +await agent.scheduleCron({ + schedule: "0 9 * * *", + action: { + type: "session", + agent: "pi", + prompt: "Review the codebase for security issues and write a report to /home/user/audit.md", + }, +}); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +[Documentation](/docs/agent-os/cron) + +### Sandbox Mounting + +agentOS uses a hybrid model: agents run in a lightweight VM by default and spin up a full sandbox on demand for heavy workloads like browsers, compilation, and desktop automation. + +```ts @nocheck +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi], + sandbox: { + enabled: true, + }, + }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +[Documentation](/docs/agent-os/sandbox) + +### Multiplayer & Realtime + +Connect multiple clients to the same agent VM. All subscribers see session output, process logs, and shell data in realtime. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +// Client A: creates the session and sends prompts +const clientA = createClient("http://localhost:6420"); +const agentA = clientA.vm.getOrCreate(["shared-agent"]); +agentA.on("sessionEvent", (data) => console.log("[A]", data.event.method)); + +const session = await agentA.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +await agentA.sendPrompt(session.sessionId, "Build a REST API"); + +// Client B: observes the same session (separate process) +const clientB = createClient("http://localhost:6420"); +const agentB = clientB.vm.getOrCreate(["shared-agent"]); +agentB.on("sessionEvent", (data) => console.log("[B]", data.event.method)); +// Client B sees the same events as Client A +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +[Documentation](/docs/agent-os/multiplayer) + +### Agent-to-Agent + +Compose specialized agents into pipelines. Each agent gets its own isolated VM and filesystem. + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const coder = agentOs({ + options: { software: [common, pi] }, +}); +const reviewer = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { coder, reviewer } }); +registry.start(); +``` + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); + +// Coder writes the feature +const coderAgent = client.coder.getOrCreate(["feature-auth"]); +const coderSession = await coderAgent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +await coderAgent.sendPrompt(coderSession.sessionId, "Implement the login feature"); + +// Pass files to the reviewer +const src = await coderAgent.readFile("/home/user/src/auth.ts"); +const reviewerAgent = client.reviewer.getOrCreate(["feature-auth"]); +await reviewerAgent.writeFile("/home/user/src/auth.ts", src); + +// Reviewer checks the code +const reviewSession = await reviewerAgent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +await reviewerAgent.sendPrompt( + reviewSession.sessionId, + "Review auth.ts for security issues", +); +``` + +[Documentation](/docs/agent-os/agent-to-agent) + +### Workflows + +Orchestrate multi-step agent tasks with durable workflows that survive crashes and restarts. + +```ts @nocheck +import { agentOs } from "rivetkit/agent-os"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; +import { actor, setup, workflow } from "rivetkit"; + +const automator = actor({ + workflows: { + fixBug: workflow<{ repo: string; issue: string }>(), + }, + run: async (c) => { + for await (const message of c.workflow.iter("fixBug")) { + const { repo, issue } = message.body; + const agentHandle = c.actors.vm.getOrCreate([`fix-${issue}`]); + + await c.step("clone-repo", async () => { + return agentHandle.exec(`git clone ${repo} /home/user/repo`); + }); + + await c.step("fix-bug", async () => { + const session = await agentHandle.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, + }); + const response = await agentHandle.sendPrompt( + session.sessionId, + `Fix the bug described in issue: ${issue}`, + ); + await agentHandle.closeSession(session.sessionId); + return response; + }); + + await c.step("run-tests", async () => { + return agentHandle.exec("cd /home/user/repo && npm test"); + }); + + await message.complete(); + } + }, +}); + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { automator, vm } }); +registry.start(); +``` + +[Documentation](/docs/agent-os/workflows) + +### SQLite + +Use actor-local SQLite as structured long-term memory that persists across sessions and sleep/wake cycles. + +```ts @nocheck +import { actor, setup } from "rivetkit"; +import { db } from "rivetkit/db"; + +const memoryAgent = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS memories ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_id TEXT NOT NULL, + category TEXT NOT NULL, + content TEXT NOT NULL, + created_at INTEGER NOT NULL + ); + `); + }, + }), + actions: { + store: async (c, sessionId: string, category: string, content: string) => { + await c.db.execute( + "INSERT INTO memories (session_id, category, content, created_at) VALUES (?, ?, ?, ?)", + sessionId, category, content, Date.now(), + ); + }, + search: async (c, query: string) => { + return c.db.execute( + "SELECT category, content FROM memories WHERE content LIKE ? ORDER BY created_at DESC LIMIT 20", + `%${query}%`, + ); + }, + }, +}); +``` + +[Documentation](/docs/agent-os/sqlite) + +_Source doc path: /docs/agent-os/crash-course_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/cron.md b/.agents/skills/ai-agent-workspace/reference/agent-os/cron.md new file mode 100644 index 0000000..1968d15 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/cron.md @@ -0,0 +1,223 @@ +# Cron Jobs + +> Source: `src/content/docs/agent-os/cron.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/cron +> Description: Schedule recurring commands and agent sessions in agentOS VMs. + +--- +- **Cron expressions** for flexible scheduling (e.g. `"0 9 * * *"` for 9 AM daily) +- **Two action types**: `exec` for commands, `session` for agent sessions +- **Overlap modes**: `allow`, `skip`, or `queue` concurrent executions +- **Event streaming** via `cronEvent` for monitoring job execution + +## Schedule a command + +Run a shell command on a recurring schedule. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Schedule a cleanup script every hour +const { id } = await agent.scheduleCron({ + schedule: "0 * * * *", + action: { + type: "exec", + command: "rm", + args: ["-rf", "/tmp/cache/*"], + }, +}); +console.log("Cron job ID:", id); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Schedule an agent session + +Create a recurring agent session that runs a prompt on a schedule. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Run an agent every day at 9 AM to check for issues +await agent.scheduleCron({ + schedule: "0 9 * * *", + action: { + type: "session", + agentType: "pi", + prompt: "Review the logs in /home/user/logs/ and summarize any errors", + options: { cwd: "/home/user" }, + }, +}); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Overlap modes + +Control what happens when a cron job triggers while a previous execution is still running. + +| Mode | Behavior | +|------|----------| +| `"skip"` | Skip this trigger if the previous run is still active | +| `"allow"` | Allow concurrent executions (default) | +| `"queue"` | Queue this trigger and run it after the previous one finishes | + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Queue overlapping executions +await agent.scheduleCron({ + schedule: "*/5 * * * *", + overlap: "queue", + action: { + type: "session", + agentType: "pi", + prompt: "Process the next batch of tasks", + }, +}); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Monitor cron events + +Subscribe to `cronEvent` to track job execution. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +agent.on("cronEvent", (data) => { + console.log("Cron event:", data.event); +}); + +await agent.scheduleCron({ + schedule: "*/1 * * * *", + action: { type: "exec", command: "echo", args: ["heartbeat"] }, +}); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## List and cancel cron jobs + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// List all cron jobs +const jobs = await agent.listCronJobs(); +for (const job of jobs) { + console.log(job.id, job.schedule); +} + +// Cancel a specific job +await agent.cancelCronJob(jobs[0].id); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Example: Heartbeat pattern + +Schedule a recurring agent session to periodically check on a task. This is the core pattern behind [OpenClaw](https://openclaw.org), where an agent wakes up on a schedule to review progress, take action, and go back to sleep. + +```ts @nocheck +await agent.scheduleCron({ + schedule: "*/30 * * * *", + overlap: "skip", + action: { + type: "session", + agentType: "pi", + prompt: "Check the status of open issues and take any necessary action", + }, +}); +``` + +The agent sleeps between executions and only consumes resources when the cron job fires. + +## Recommendations + +- Use `"skip"` overlap mode for most jobs. This prevents unbounded concurrency if a job takes longer than the interval. The default is `"allow"`. +- Use `"queue"` when every trigger must execute, even if they back up. +- Cron jobs keep the actor alive while executing. The actor can sleep between executions. +- Provide a custom `id` when scheduling to make it easier to manage and cancel jobs later. + +_Source doc path: /docs/agent-os/cron_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/deployment.md b/.agents/skills/ai-agent-workspace/reference/agent-os/deployment.md new file mode 100644 index 0000000..bd89d8b --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/deployment.md @@ -0,0 +1,18 @@ +# Deployment + +> Source: `src/content/docs/agent-os/deployment.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/deployment +> Description: Choose the right deployment option for agentOS. + +--- +agentOS supports multiple deployment models depending on your needs. + +| Option | Description | Best for | +|--------|-------------|----------| +| **Local Dev** | Run locally with `npx rivetkit dev`. No infrastructure needed. | Development and testing | +| **[Rivet Cloud](/cloud)** | Fully managed hosting on Rivet Compute or bring your own cloud (BYOC). | Teams that want zero-ops deployment | +| **[Rivet Self-Hosted](/docs/self-hosting)** | Run the full Rivet platform on your own infrastructure. | Organizations that need full control | +| **[Rivet Enterprise](/sales)** | Self-hosted with dedicated support, custom SLAs, and compliance reviews. | Regulated industries and large-scale deployments | +| **agentOS Core** | Use `@rivet-dev/agent-os-core` directly without the Rivet platform. Embed the runtime in any Node.js backend. | Custom integrations and existing infrastructure | + +_Source doc path: /docs/agent-os/deployment_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/events.md b/.agents/skills/ai-agent-workspace/reference/agent-os/events.md new file mode 100644 index 0000000..5abf87a --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/events.md @@ -0,0 +1,195 @@ +# Events + +> Source: `src/content/docs/agent-os/events.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/events +> Description: Full event catalog with payload shapes for agentOS. + +--- +## Event types + +### sessionEvent + +Emitted for every agent session event (streaming output, errors, status changes). + +```ts @nocheck +agent.on("sessionEvent", (data) => { + // data.sessionId: string + // data.event: JsonRpcNotification (method, params) + console.log(data.sessionId, data.event.method, data.event.params); +}); +``` + +Events are also persisted to SQLite for replay via `getSessionEvents`. + +### permissionRequest + +Emitted when an agent requests permission to use a tool. + +```ts @nocheck +agent.on("permissionRequest", async (data) => { + // data.sessionId: string + // data.request: PermissionRequest (id, toolName, etc.) + console.log("Permission requested:", data.request); + + await agent.respondPermission(data.sessionId, data.request.permissionId, "once"); +}); +``` + +See [Permissions](/docs/agent-os/permissions) for approval patterns. + +### processOutput + +Emitted when a spawned process writes to stdout or stderr. + +```ts @nocheck +agent.on("processOutput", (data) => { + // data.pid: number + // data.stream: "stdout" | "stderr" + // data.data: Uint8Array + const text = new TextDecoder().decode(data.data); + console.log(`[${data.pid}] ${data.stream}: ${text}`); +}); +``` + +### processExit + +Emitted when a spawned process exits. + +```ts @nocheck +agent.on("processExit", (data) => { + // data.pid: number + // data.exitCode: number + console.log(`Process ${data.pid} exited with code ${data.exitCode}`); +}); +``` + +### shellData + +Emitted when an interactive shell produces output. + +```ts @nocheck +agent.on("shellData", (data) => { + // data.shellId: string + // data.data: Uint8Array + const text = new TextDecoder().decode(data.data); + process.stdout.write(text); +}); +``` + +### cronEvent + +Emitted when a cron job runs. + +```ts @nocheck +agent.on("cronEvent", (data) => { + // data.event: CronEvent + console.log("Cron event:", data.event); +}); +``` + +### vmBooted + +Emitted when the VM finishes booting. No payload. + +```ts @nocheck +agent.on("vmBooted", () => { + console.log("VM is ready"); +}); +``` + +### vmShutdown + +Emitted when the VM is shutting down. + +```ts @nocheck +agent.on("vmShutdown", (data) => { + // data.reason: "sleep" | "destroy" | "error" + console.log("VM shutting down:", data.reason); +}); +``` + +## Client subscription pattern + +Subscribe to events before triggering actions to avoid missing early events. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Subscribe to all relevant events first +agent.on("sessionEvent", (data) => { + console.log("Session:", data.event.method); +}); +agent.on("processOutput", (data) => { + console.log("Process:", new TextDecoder().decode(data.data)); +}); +agent.on("processExit", (data) => { + console.log("Exit:", data.pid, data.exitCode); +}); + +// Then trigger actions +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +await agent.sendPrompt(session.sessionId, "Run the test suite"); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Event replay + +There are two ways to replay session events: + +- **`getSequencedEvents`** returns events from the in-memory session. Each event has a `sequenceNumber` and a `notification` (the raw JSON-RPC notification). Use this for live reconnection while the VM is running. +- **`getSessionEvents`** returns events from persisted storage (SQLite). Each event has a `seq`, `event`, and `createdAt`. Use this for transcript history, including when the VM is not running. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Replay events from sequence 0 +const events = await agent.getSequencedEvents("session-id", { since: 0 }); +for (const e of events) { + console.log(e.sequenceNumber, e.notification.method); +} + +// Replay from persisted storage (works without running VM) +const persisted = await agent.getSessionEvents("session-id"); +for (const e of persisted) { + console.log(e.seq, e.event.method, e.createdAt); +} +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +_Source doc path: /docs/agent-os/events_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/filesystem.md b/.agents/skills/ai-agent-workspace/reference/agent-os/filesystem.md new file mode 100644 index 0000000..296e1c4 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/filesystem.md @@ -0,0 +1,243 @@ +# Filesystem + +> Source: `src/content/docs/agent-os/filesystem.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/filesystem +> Description: Read, write, mount, and manage files inside agentOS. + +--- +Every VM comes with a persistent filesystem out of the box. Files written anywhere in the VM are automatically saved to the Rivet Actor's built-in storage and restored on wake. No configuration needed. + +- **Persistent by default** backed by Rivet Actor storage, up to 10 GB +- **Full POSIX filesystem** with read, write, mkdir, stat, move, delete +- **Batch operations** for reading and writing multiple files at once +- **Mount backends** for additional storage like S3, host directories, and overlays + +## Mounting filesystems + +The default filesystem persists automatically across sleep/wake cycles with no setup required (up to 10 GB). For larger storage or external data, mount additional filesystem drivers via the `options.mounts` config. + +Each mount takes a `path` (where to mount inside the VM), a `driver` (the filesystem implementation), and an optional `readOnly` flag. + +### In-memory + +```ts @nocheck +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import { createInMemoryFileSystem } from "@rivet-dev/agent-os-core"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { + software: [common, pi], + mounts: [ + { path: "/mnt/scratch", driver: createInMemoryFileSystem() }, + ], + }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +### Host directory + +```ts @nocheck +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import { createHostDirBackend } from "@rivet-dev/agent-os-core"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { + software: [common, pi], + mounts: [ + { path: "/mnt/code", driver: createHostDirBackend({ hostPath: "/path/to/repo" }), readOnly: true }, + ], + }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +### S3 + +Install `@rivet-dev/agent-os-s3` for S3-compatible storage. + +#### Per-agent storage (recommended) + +Use `createS3BackendForAgent` to automatically scope S3 storage by agent key. Each agent instance gets its own prefix (`agents/{key}/`) within the bucket, so you don't need to manage prefixes manually. + +```ts @nocheck +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import { createS3BackendForAgent } from "@rivet-dev/agent-os-s3"; +import type { AgentOsContext } from "@rivet-dev/agent-os-s3"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +function createVm(context: AgentOsContext) { + return agentOs({ + options: { + software: [common, pi], + mounts: [ + { + path: "/mnt/data", + driver: createS3BackendForAgent(context, { + bucket: "my-bucket", + region: "us-east-1", + }), + }, + ], + }, + }); +} +``` + +The `AgentOsContext` object contains: + +- `key` — unique identifier for the agent instance (e.g. actor ID, user ID, session ID). Used as the S3 prefix. +- `metadata` — optional key-value pairs with additional agent information. + +#### Fixed prefix + +For shared storage or custom prefix schemes, use `createS3Backend` with an explicit prefix. + +```ts @nocheck +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import { createS3Backend } from "@rivet-dev/agent-os-s3"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { + software: [common, pi], + mounts: [ + { + path: "/mnt/data", + driver: createS3Backend({ + bucket: "my-bucket", + prefix: "agent-data/", + region: "us-east-1", + }), + }, + ], + }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +### Google Drive + +Install `@rivet-dev/agent-os-google-drive` for Google Drive storage. + +```ts @nocheck +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import { GoogleDriveBlockStore } from "@rivet-dev/agent-os-google-drive"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { + software: [common, pi], + mounts: [ + { + path: "/mnt/drive", + driver: new GoogleDriveBlockStore({ + credentials: { + clientEmail: process.env.GOOGLE_DRIVE_CLIENT_EMAIL!, + privateKey: process.env.GOOGLE_DRIVE_PRIVATE_KEY!, + }, + folderId: process.env.GOOGLE_DRIVE_FOLDER_ID!, + }), + }, + ], + }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Filesystem operations + +### Read and write + +```ts @nocheck +// Write a file (string or Uint8Array) +await agent.writeFile("/home/user/hello.txt", "Hello, world!"); + +// Read a file (returns Uint8Array) +const content = await agent.readFile("/home/user/hello.txt"); +console.log(new TextDecoder().decode(content)); +``` + +### Batch read and write + +```ts @nocheck +// Batch write (creates parent directories automatically) +const writeResults = await agent.writeFiles([ + { path: "/home/user/src/index.ts", content: "console.log('hello');" }, + { path: "/home/user/src/utils.ts", content: "export function add(a: number, b: number) { return a + b; }" }, +]); + +// Batch read +const readResults = await agent.readFiles([ + "/home/user/src/index.ts", + "/home/user/src/utils.ts", +]); +for (const result of readResults) { + console.log(result.path, new TextDecoder().decode(result.content)); +} +``` + +### Directories + +```ts @nocheck +// Create a directory +await agent.mkdir("/home/user/projects"); + +// List directory contents +const entries = await agent.readdir("/home/user/projects"); + +// Recursive listing with metadata +const tree = await agent.readdirRecursive("/home/user", { + maxDepth: 3, + exclude: ["node_modules"], +}); +for (const entry of tree) { + console.log(entry.type, entry.path, entry.size); +} +``` + +### File metadata + +```ts @nocheck +// Check if a path exists +const fileExists = await agent.exists("/home/user/hello.txt"); + +// Get file metadata +const info = await agent.stat("/home/user/hello.txt"); +console.log(info.size, info.isDirectory, info.mtimeMs); +``` + +### Move and delete + +```ts @nocheck +// Move/rename +await agent.move("/home/user/old.txt", "/home/user/new.txt"); + +// Delete a file +await agent.deleteFile("/home/user/new.txt"); + +// Delete a directory recursively +await agent.deleteFile("/home/user/temp", { recursive: true }); +``` + +_Source doc path: /docs/agent-os/filesystem_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/limitations.md b/.agents/skills/ai-agent-workspace/reference/agent-os/limitations.md new file mode 100644 index 0000000..81ea25f --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/limitations.md @@ -0,0 +1,35 @@ +# Limitations + +> Source: `src/content/docs/agent-os/limitations.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/limitations +> Description: What the agentOS VM does not support, and how to work around it. + +--- +agentOS is a Linux-like environment with a POSIX-compliant virtual kernel. It handles most agent workloads (coding, scripting, file I/O, networking) with near-zero overhead. + +## Sandbox mounting + +When a workload needs a full Linux OS, agents can escalate to a full sandbox on demand without changing code. The [sandbox mounting](/docs/agent-os/sandbox) extension mounts the sandbox as a filesystem and lets you execute commands on it, like mounting a hard drive on your own machine. Files written in the VM are available in the sandbox and vice versa. + +See [agentOS vs Sandbox](/docs/agent-os/versus-sandbox) for a detailed comparison. + +## Limitations + +### Software registry + +agentOS uses its own [software registry](/agent-os/registry) of popular tools cross-compiled for the runtime. Native language runtimes like Go, Rust, and C++ are supported. Standard Linux package managers (`apt`, `yum`) are not available since agentOS is not a full Linux OS. + +See [Software](/docs/agent-os/software) for how to install and configure available packages. + +### POSIX-compliant, not full Linux + +agentOS provides a POSIX-compliant virtual kernel with full filesystem operations, networking, and process management. It is not a full Linux kernel, so some Linux-specific features are not available: + +- Kernel modules and eBPF +- Container runtimes (e.g. Docker) + +### No hardware access + +The VM has no access to GPUs, USB devices, or other hardware. + +_Source doc path: /docs/agent-os/limitations_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/llm-credentials.md b/.agents/skills/ai-agent-workspace/reference/agent-os/llm-credentials.md new file mode 100644 index 0000000..403c1b5 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/llm-credentials.md @@ -0,0 +1,65 @@ +# LLM Credentials + +> Source: `src/content/docs/agent-os/llm-credentials.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/llm-credentials +> Description: Pass LLM API keys to agent sessions securely. + +--- +- **Keys stay on the server** and are injected at session creation +- **Per-tenant isolation** for multi-tenant deployments + +## Passing API keys + +Pass LLM provider keys via the `env` option on `createSession`. The VM does not inherit from the host `process.env`, so keys must be passed explicitly. + +```ts @nocheck +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +``` + +## Per-tenant credentials + +Look up each tenant's API key from your database and pass it at session creation. + +```ts @nocheck +import { agentOs } from "rivetkit/agent-os"; +import { setup, UserError } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +interface ConnState { + userId: string; + anthropicApiKey: string; +} + +const vm = agentOs({ + createConnState: async (c, params: { authToken: string }): Promise => { + const user = await validateAndLookupUser(params.authToken); + if (!user) { + throw new UserError("Forbidden", { code: "forbidden" }); + } + return { userId: user.id, anthropicApiKey: user.anthropicApiKey }; + }, + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +Then use the connection state when creating sessions: + +```ts @nocheck +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: c.conn.state.anthropicApiKey }, +}); +``` + +See [Sandbox Agent's LLM credentials documentation](https://sandboxagent.dev/docs/llm-credentials) for more details on per-tenant token patterns. + +## Embedded LLM Gateway + +The [Embedded LLM Gateway](/docs/agent-os/llm-gateway) (coming soon) will remove the need to manage API keys manually. It routes all agent LLM requests through a managed proxy built into agentOS, providing per-tenant usage metering, rate limiting, and cost controls without deploying a separate gateway service. + +_Source doc path: /docs/agent-os/llm-credentials_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/llm-gateway.md b/.agents/skills/ai-agent-workspace/reference/agent-os/llm-gateway.md new file mode 100644 index 0000000..8e5419b --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/llm-gateway.md @@ -0,0 +1,17 @@ +# Embedded LLM Gateway + +> Source: `src/content/docs/agent-os/llm-gateway.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/llm-gateway +> Description: Route, meter, and manage LLM API calls from agents. + +--- +The Embedded LLM Gateway runs as part of the agentOS library, not as an external service. It intercepts and manages all LLM API calls made by agents inside the VM. + +- **Unified routing** for all agent LLM requests +- **API keys stay on the server** so they are never exposed to agent code inside the VM +- **Usage metering** with per-session and per-agent breakdowns +- **Rate limiting** and cost controls + +Check back soon for full documentation. + +_Source doc path: /docs/agent-os/llm-gateway_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/multiplayer.md b/.agents/skills/ai-agent-workspace/reference/agent-os/multiplayer.md new file mode 100644 index 0000000..0ce5224 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/multiplayer.md @@ -0,0 +1,190 @@ +# Multiplayer + +> Source: `src/content/docs/agent-os/multiplayer.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/multiplayer +> Description: Connect multiple clients to the same agentOS actor for collaborative agent workflows. + +--- +- **Multiple clients** connected to the same agent VM simultaneously +- **Broadcast events** so all subscribers see session output, process logs, and shell data +- **Collaborative patterns** where one user prompts and others observe +- **Handoff** between human and agent control + +## Multiple clients observing a session + +All clients connected to the same actor receive broadcasted events. This enables building collaborative UIs where multiple users watch an agent work. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +// Client A: creates the session and sends prompts +const clientA = createClient("http://localhost:6420"); +const agentA = clientA.vm.getOrCreate(["shared-agent"]); + +agentA.on("sessionEvent", (data) => { + console.log("[A]", data.event.method); +}); + +const session = await agentA.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +await agentA.sendPrompt(session.sessionId, "Build a REST API"); + +// Client B: observes the same session (in a separate process) +const clientB = createClient("http://localhost:6420"); +const agentB = clientB.vm.getOrCreate(["shared-agent"]); + +agentB.on("sessionEvent", (data) => { + console.log("[B]", data.event.method); +}); + +// Client B sees the same events as Client A +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Shared process output + +All clients receive process output events from the same VM. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["shared-agent"]); + +// All connected clients see process output +agent.on("processOutput", (data) => { + const text = new TextDecoder().decode(data.data); + console.log(`[pid ${data.pid}] ${data.stream}: ${text}`); +}); + +// All connected clients see shell data +agent.on("shellData", (data) => { + const text = new TextDecoder().decode(data.data); + process.stdout.write(text); +}); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Collaborative prompt/observe pattern + +One client acts as the driver (sending prompts), while others observe. + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + onSessionEvent: async (c, sessionId, event) => { + // Server-side hook runs once per event, even with multiple clients + console.log("Session event:", sessionId, event.method); + }, + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +// Driver client +const driver = createClient("http://localhost:6420"); +const driverAgent = driver.vm.getOrCreate(["shared-agent"]); + +const session = await driverAgent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); + +// Observer client (different user, same actor) +const observer = createClient("http://localhost:6420"); +const observerAgent = observer.vm.getOrCreate(["shared-agent"]); + +observerAgent.on("sessionEvent", (data) => { + console.log("[observer]", data.event.method, data.event.params); +}); + +// Driver sends a prompt. Observer sees the streaming response. +await driverAgent.sendPrompt(session.sessionId, "Refactor the auth module"); +``` + +## Reconnection with event replay + +When a client reconnects, use `getSequencedEvents` to replay missed events and catch up. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["shared-agent"]); + +// On reconnect, replay events from the last known sequence number +const lastSeq = 42; // Track this on the client side +const missedEvents = await agent.getSequencedEvents("session-id", { + since: lastSeq, +}); +for (const event of missedEvents) { + console.log("Replaying:", event.sequenceNumber, event.notification.method); +} + +// Resume live streaming +agent.on("sessionEvent", (data) => { + console.log("Live:", data.event.method); +}); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Recommendations + +- Use the same actor key (e.g. `["shared-agent"]`) for all clients that should share the same VM. +- Events are broadcasted to all connected clients automatically. No additional setup needed. +- For reconnection, track the last sequence number on the client and use `getSequencedEvents` to replay missed events. +- Use the server-side `onSessionEvent` hook for logic that should run once per event regardless of connected clients. + +_Source doc path: /docs/agent-os/multiplayer_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/networking.md b/.agents/skills/ai-agent-workspace/reference/agent-os/networking.md new file mode 100644 index 0000000..f549f21 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/networking.md @@ -0,0 +1,169 @@ +# Networking & Previews + +> Source: `src/content/docs/agent-os/networking.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/networking +> Description: Proxy HTTP requests into agentOS VMs and create shareable preview URLs. + +--- +- **`vmFetch`** proxies HTTP requests to services running inside the VM +- **Preview URLs** create time-limited, shareable public URLs to VM services +- **Token-based access** with configurable expiration and revocation +- **CORS enabled** for browser access to preview URLs + +## Fetch from a VM service + +Use `vmFetch` to send HTTP requests to a service running inside the VM. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Start a web server inside the VM +await agent.writeFile( + "/home/user/server.js", + 'require("http").createServer((req, res) => res.end("Hello from VM")).listen(3000);', +); +await agent.spawn("node", ["/home/user/server.js"]); + +// Fetch from the VM service +const response = await agent.vmFetch(3000, "/"); +console.log("Status:", response.status); +console.log("Body:", new TextDecoder().decode(response.body)); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## vmFetch with options + +Send requests with custom methods, headers, and body. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +const response = await agent.vmFetch(3000, "/api/data", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ key: "value" }), +}); + +console.log("Status:", response.status, response.statusText); +console.log("Headers:", response.headers); +console.log("Body:", new TextDecoder().decode(response.body)); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Create a preview URL + +Preview URLs are essentially port forwarding for VM services. They create a time-limited, publicly accessible URL that proxies HTTP requests to a specific port inside the VM. Use them to share web app previews with users, embed dev servers in iframes, or give external tools access to services running inside the agent's VM. + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + preview: { + defaultExpiresInSeconds: 3600, // 1 hour default + maxExpiresInSeconds: 86400, // 24 hour maximum + }, + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Start a web app in the VM +await agent.spawn("node", ["/home/user/app.js"]); + +// Create a preview URL (default 1 hour expiration) +const preview = await agent.createSignedPreviewUrl(3000); +console.log("Preview path:", preview.path); +console.log("Token:", preview.token); +console.log("Expires at:", new Date(preview.expiresAt)); + +// Create a preview URL with custom expiration +const shortPreview = await agent.createSignedPreviewUrl(3000, 300); // 5 minutes +console.log("Short-lived preview:", shortPreview.path); +``` + +## Revoke a preview URL + +Use `expireSignedPreviewUrl` to immediately revoke a preview token. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +const preview = await agent.createSignedPreviewUrl(3000); + +// Revoke the token immediately +await agent.expireSignedPreviewUrl(preview.token); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Recommendations + +- Preview tokens are stored in SQLite and survive sleep/wake cycles. Expired tokens are cleaned up automatically. +- Default preview expiration is 1 hour. Configure `preview.maxExpiresInSeconds` to cap the maximum lifetime. +- CORS is enabled on preview URLs, allowing browser access from any origin. +- Use `vmFetch` for server-to-server access. Use preview URLs for browser or external access. +- See [Security](/docs/agent-os/security) for more on preview URL token security. + +_Source doc path: /docs/agent-os/networking_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/permissions.md b/.agents/skills/ai-agent-workspace/reference/agent-os/permissions.md new file mode 100644 index 0000000..745fa91 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/permissions.md @@ -0,0 +1,156 @@ +# Permissions + +> Source: `src/content/docs/agent-os/permissions.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/permissions +> Description: Approve or deny agent tool use with human-in-the-loop or auto-approve patterns. + +--- +- **Human-in-the-loop** approval for agent tool use (file writes, command execution, etc.) +- **Auto-approve** patterns for trusted workloads +- **Server-side hooks** for programmatic permission decisions +- **Client-side subscriptions** for building approval UIs + +## Permission request flow + +When an agent wants to use a tool (e.g. write a file, run a command), it emits a `permissionRequest` event. Your code responds with `respondPermission` to approve or deny. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Listen for permission requests +agent.on("permissionRequest", async (data) => { + console.log("Permission requested:", data.request); + + // Approve this single request + await agent.respondPermission( + data.sessionId, + data.request.permissionId, + "once", + ); +}); + +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +await agent.sendPrompt(session.sessionId, "Create a new file at /home/user/output.txt"); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Permission reply options + +| Reply | Behavior | +|-------|----------| +| `"once"` | Approve this single request | +| `"always"` | Approve this and all future requests of the same type | +| `"reject"` | Deny the request | + +## Server-side auto-approve + +Use the `onPermissionRequest` hook in the actor config to approve permissions server-side without client involvement. This is useful for fully automated pipelines. + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + onPermissionRequest: async (c, sessionId, request) => { + // Auto-approve all file operations + await c.respondPermission(sessionId, request.permissionId, "always"); + }, + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// No need to handle permissions on the client. The server auto-approves. +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +await agent.sendPrompt(session.sessionId, "Write files as needed"); +``` + +## Selective approval + +Inspect the permission request to make approval decisions based on the tool or path. + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + onPermissionRequest: async (c, sessionId, request) => { + // Auto-approve reads, require manual approval for writes + const toolName = (request as any).toolName ?? ""; + if (toolName.includes("read")) { + await c.respondPermission(sessionId, request.permissionId, "always"); + } + // Writes are forwarded to the client via the permissionRequest event + }, + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Only write permissions reach the client +agent.on("permissionRequest", async (data) => { + const approved = confirm(`Allow write: ${JSON.stringify(data.request)}?`); + await agent.respondPermission( + data.sessionId, + data.request.permissionId, + approved ? "once" : "reject", + ); +}); + +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +await agent.sendPrompt(session.sessionId, "Read config.json and update it"); +``` + +## Recommendations + +- Use `"always"` sparingly. It approves all future requests of that type for the session lifetime. +- For automated CI/CD pipelines, use the server-side `onPermissionRequest` hook to auto-approve without client round-trips. +- For interactive applications, subscribe to `permissionRequest` on the client and build an approval UI. +- If neither the server hook nor the client responds, the agent blocks until a response is given or the action times out. + +_Source doc path: /docs/agent-os/permissions_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/persistence.md b/.agents/skills/ai-agent-workspace/reference/agent-os/persistence.md new file mode 100644 index 0000000..dfa27d7 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/persistence.md @@ -0,0 +1,185 @@ +# Persistence & Sleep + +> Source: `src/content/docs/agent-os/persistence.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/persistence +> Description: How agentOS persists data and manages sleep/wake cycles. + +--- +- **Persistent filesystem** backs `/home/user` automatically +- **Session transcripts** persisted with sequence numbers for replay +- **Configurable sleep** with a 15-minute grace period by default +- **Automatic wake** when a client connects or a cron job triggers + +## What persists across sleep + +| Data | Storage | Persists? | +|------|---------|-----------| +| Files in `/home/user` | Persistent filesystem | Yes | +| Session records | SQLite (`agent_os_sessions`) | Yes | +| Session event history | SQLite (`agent_os_session_events`) | Yes | +| Preview URL tokens | SQLite (`agent_os_preview_tokens`) | Yes | +| Cron job definitions | Actor state | Yes | +| Running processes | VM kernel | No | +| Active shells | VM kernel | No | +| In-memory mounts | VM memory | No | +| VM kernel state | VM memory | No | + +## What prevents sleep + +The actor stays awake as long as any of these are active: + +- **Active sessions** (created but not closed/destroyed) +- **Running processes** (spawned but not exited) +- **Active shells** (opened but not closed) +- **Pending hooks** (server-side callbacks still executing) + +When all activity stops, the sleep grace period begins. + +## Sleep grace period + +After all activity stops, the actor waits 15 minutes before sleeping. This allows for brief pauses between interactions without restarting the VM. + +``` +Activity stops ──> 15 min grace period ──> Actor sleeps + (VM shutdown, processes killed) + +New client connects ──> Actor wakes ──> VM boots ──> Filesystem restored +``` + +## Sleep vs destroy + +| | Sleep | Destroy | +|-|-------|---------| +| Filesystem | Preserved | Deleted | +| Session records | Preserved | Deleted | +| Event history | Preserved | Deleted | +| Preview tokens | Preserved | Deleted | +| VM state | Lost | Lost | +| Processes | Killed | Killed | + +## VM boot and shutdown events + +Subscribe to `vmBooted` and `vmShutdown` events to track VM lifecycle. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +agent.on("vmBooted", () => { + console.log("VM is ready"); +}); + +agent.on("vmShutdown", (data) => { + console.log("VM shutdown reason:", data.reason); + // reason: "sleep" | "destroy" | "error" +}); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Resuming after sleep + +When the actor wakes up: + +1. The VM boots and the filesystem is restored from SQLite +2. Session records and event history are available immediately +3. Processes and shells from the previous session are gone +4. Clients can reconnect and resume sessions using `resumeSession` +5. Use `getSessionEvents` to replay missed events + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// List sessions from before sleep +const sessions = await agent.listPersistedSessions(); +console.log("Previous sessions:", sessions.length); + +// Resume the most recent session +if (sessions.length > 0) { + const last = sessions[0]; + await agent.resumeSession(last.sessionId); + + // Replay events for transcript + const events = await agent.getSessionEvents(last.sessionId); + for (const e of events) { + console.log(e.seq, e.event.method); + } +} +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Persisted tables schema + +### `agent_os_fs_entries` + +Stores the virtual filesystem. + +| Column | Type | Description | +|--------|------|-------------| +| `path` | TEXT PRIMARY KEY | File or directory path | +| `is_directory` | INTEGER | 1 for directory, 0 for file | +| `content` | BLOB | File content | +| `mode` | INTEGER | POSIX mode bits | +| `size` | INTEGER | File size in bytes | +| `atime_ms` | INTEGER | Access time (ms) | +| `mtime_ms` | INTEGER | Modification time (ms) | +| `ctime_ms` | INTEGER | Change time (ms) | +| `birthtime_ms` | INTEGER | Birth time (ms) | + +### `agent_os_sessions` + +Stores session metadata. + +| Column | Type | Description | +|--------|------|-------------| +| `session_id` | TEXT PRIMARY KEY | Unique session identifier | +| `agent_type` | TEXT | Agent type (e.g. "pi") | +| `capabilities` | TEXT (JSON) | Agent capabilities | +| `agent_info` | TEXT (JSON) | Agent metadata | +| `created_at` | INTEGER | Creation timestamp (ms) | + +### `agent_os_session_events` + +Stores session event history. + +| Column | Type | Description | +|--------|------|-------------| +| `id` | INTEGER PRIMARY KEY | Auto-incrementing ID | +| `session_id` | TEXT | Session reference | +| `seq` | INTEGER | Sequence number within session | +| `event` | TEXT (JSON) | JSON-RPC notification | +| `created_at` | INTEGER | Timestamp (ms) | + +_Source doc path: /docs/agent-os/persistence_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/processes.md b/.agents/skills/ai-agent-workspace/reference/agent-os/processes.md new file mode 100644 index 0000000..a033b5a --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/processes.md @@ -0,0 +1,253 @@ +# Processes & Shell + +> Source: `src/content/docs/agent-os/processes.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/processes +> Description: Execute commands, spawn long-running processes, and open interactive shells in agentOS VMs. + +--- +- **One-shot execution** with `exec` for simple commands +- **Long-running processes** with `spawn`, stdout/stderr streaming, and stdin writing +- **Process lifecycle** management with stop, kill, wait, and inspect +- **Interactive shells** with PTY support for terminal I/O +- **Process tree** visibility across all VM runtimes + +## One-shot execution + +Use `exec` to run a command and wait for completion. Returns stdout, stderr, and exit code. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +const result = await agent.exec("echo hello && ls /home/user"); +console.log("stdout:", result.stdout); +console.log("stderr:", result.stderr); +console.log("exit code:", result.exitCode); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Spawn a long-running process + +Use `spawn` for processes that run in the background. Output is streamed via `processOutput` and `processExit` events. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Subscribe to process output +agent.on("processOutput", (data) => { + const text = new TextDecoder().decode(data.data); + console.log(`[pid ${data.pid}] ${data.stream}: ${text}`); +}); + +agent.on("processExit", (data) => { + console.log(`[pid ${data.pid}] exited with code ${data.exitCode}`); +}); + +// Spawn a dev server +const { pid } = await agent.spawn("node", ["/home/user/server.js"]); +console.log("Started process:", pid); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Write to stdin + +Send input to a running process. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +const { pid } = await agent.spawn("cat", []); + +// Write to stdin +await agent.writeProcessStdin(pid, "hello from stdin\n"); + +// Close stdin when done +await agent.closeProcessStdin(pid); + +// Wait for the process to exit +const exitCode = await agent.waitProcess(pid); +console.log("exit code:", exitCode); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Process lifecycle + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +const { pid } = await agent.spawn("node", ["/home/user/server.js"]); + +// List all spawned processes +const processes = await agent.listProcesses(); +console.log(processes); + +// Get info about a specific process +const info = await agent.getProcess(pid); +console.log(info.running, info.exitCode); + +// Graceful stop (SIGTERM) +await agent.stopProcess(pid); + +// Force kill (SIGKILL) +await agent.killProcess(pid); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## System-wide process visibility + +View all processes across all VM runtimes, not just those started via `spawn`. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// All processes +const all = await agent.allProcesses(); +for (const p of all) { + console.log(p.pid, p.driver, p.command, p.status); +} + +// Process tree (parent-child hierarchy) +const tree = await agent.processTree(); +for (const node of tree) { + console.log(node.pid, node.command, "children:", node.children.length); +} +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Interactive shells + +Open an interactive shell with PTY support. Shell data is streamed via `shellData` events. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Subscribe to shell output +agent.on("shellData", (data) => { + const text = new TextDecoder().decode(data.data); + process.stdout.write(text); +}); + +// Open a shell +const { shellId } = await agent.openShell(); + +// Write commands to the shell +await agent.writeShell(shellId, "ls -la /home/user\n"); + +// Resize the terminal +await agent.resizeShell(shellId, 120, 40); + +// Close the shell when done +await agent.closeShell(shellId); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Recommendations + +- Use `exec` for short commands where you need the full output. Use `spawn` for long-running processes where you want streaming output. +- Subscribe to `processOutput` and `processExit` **before** calling `spawn` to avoid missing events. +- Active processes prevent the actor from sleeping. Stop or kill them when they are no longer needed. +- Active shells also prevent sleep. Close shells when the user disconnects. +- Use `allProcesses` and `processTree` for debugging. They show everything running in the VM, including agent processes. + +_Source doc path: /docs/agent-os/processes_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/queues.md b/.agents/skills/ai-agent-workspace/reference/agent-os/queues.md new file mode 100644 index 0000000..ace0eee --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/queues.md @@ -0,0 +1,191 @@ +# Queues + +> Source: `src/content/docs/agent-os/queues.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/queues +> Description: Serialize agent work with durable queues for backpressure and rate limiting. + +--- +- **Serial execution** ensures agents process one task at a time +- **Durable messages** survive sleep and restart +- **Completable messages** for request/response patterns with agents +- **Backpressure** absorbs bursts and prevents overload + +## Queue agent commands + +Use actor queues to serialize work that an agent processes one task at a time. + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; +import { actor, queue, setup } from "rivetkit"; + +const taskRunner = actor({ + queues: { + tasks: queue<{ prompt: string }>(), + }, + run: async (c) => { + const agentHandle = c.actors.vm.getOrCreate(["task-agent"]); + + for await (const message of c.queue.iter()) { + // Process one task at a time + const session = await agentHandle.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, + }); + await agentHandle.sendPrompt(session.sessionId, message.body.prompt); + await agentHandle.closeSession(session.sessionId); + } + }, +}); + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { taskRunner, vm } }); +registry.start(); +``` + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const handle = client.taskRunner.getOrCreate(["main"]); + +// Queue up work. Tasks are processed one at a time. +await handle.send("tasks", { prompt: "Review PR #123" }); +await handle.send("tasks", { prompt: "Fix the flaky test in auth.test.ts" }); +await handle.send("tasks", { prompt: "Update the README" }); +``` + +## Request/response with completable messages + +Use completable messages when the caller needs to wait for the agent to finish. + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; +import { actor, queue, setup } from "rivetkit"; + +const reviewer = actor({ + queues: { + review: queue<{ file: string }, { summary: string }>(), + }, + run: async (c) => { + const agentHandle = c.actors.vm.getOrCreate(["reviewer"]); + const session = await agentHandle.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, + }); + + for await (const message of c.queue.iter({ completable: true })) { + const content = await agentHandle.readFile(message.body.file); + const text = new TextDecoder().decode(content); + + await agentHandle.sendPrompt( + session.sessionId, + `Review this code and write a summary to /home/user/review.txt:\n\n${text}`, + ); + + const review = await agentHandle.readFile("/home/user/review.txt"); + await message.complete({ + summary: new TextDecoder().decode(review), + }); + } + }, +}); + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { reviewer, vm } }); +registry.start(); +``` + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const handle = client.reviewer.getOrCreate(["main"]); + +// Wait for the agent to complete the review +const result = await handle.send( + "review", + { file: "/home/user/src/auth.ts" }, + { wait: true, timeout: 120_000 }, +); + +if (result.status === "completed") { + console.log("Review:", result.response.summary); +} +``` + +## Ingesting from external systems + +Accept tasks from webhooks, APIs, or other services and queue them for agent processing. + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; +import { actor, queue, setup } from "rivetkit"; + +const issueWorker = actor({ + queues: { + issues: queue<{ title: string; body: string }>(), + }, + actions: { + // HTTP endpoint to receive webhook payloads + ingestIssue: async (c, title: string, body: string) => { + await c.queue.push("issues", { title, body }); + }, + }, + run: async (c) => { + const agentHandle = c.actors.vm.getOrCreate(["issue-worker"]); + + for await (const message of c.queue.iter()) { + const session = await agentHandle.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, + }); + await agentHandle.sendPrompt( + session.sessionId, + `Investigate and fix this issue:\n\nTitle: ${message.body.title}\n\n${message.body.body}`, + ); + await agentHandle.closeSession(session.sessionId); + } + }, +}); + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { issueWorker, vm } }); +registry.start(); +``` + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const handle = client.issueWorker.getOrCreate(["main"]); + +// Ingest from a webhook or external system +await handle.ingestIssue( + "Login redirect broken", + "Users are redirected to /undefined after login on mobile", +); +``` + +## Recommendations + +- Use queues when you need guaranteed serial execution. Agents process one message at a time, preventing race conditions. +- Use completable messages when the caller needs the result. Set a generous timeout since agent work can take minutes. +- Queues survive actor sleep. Messages are persisted and processed when the actor wakes up. +- See [Queues & Run Loops](/docs/actors/queues) for the full queue API reference. + +_Source doc path: /docs/agent-os/queues_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/quickstart.md b/.agents/skills/ai-agent-workspace/reference/agent-os/quickstart.md new file mode 100644 index 0000000..c49cd3f --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/quickstart.md @@ -0,0 +1,91 @@ +# Quickstart + +> Source: `src/content/docs/agent-os/quickstart.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/quickstart +> Description: Set up an agentOS actor, create a session, and run your first coding agent. + +--- +agentOS is in preview and the API is subject to change. If you run into issues, please [report them on GitHub](https://github.com/rivet-dev/rivet/issues) or [join our Discord](https://rivet.dev/discord). + +### Install + +- **rivetkit** — Actor framework with built-in persistence and orchestration +- **@rivet-dev/agent-os-common** — Standard VM software (curl, grep, git, and more) +- **@rivet-dev/agent-os-pi** — [Pi](https://github.com/mariozechner/pi-coding-agent) coding agent (Claude Code, Amp, and OpenCode coming soon) + +```bash +npm install rivetkit @rivet-dev/agent-os-common @rivet-dev/agent-os-pi +``` + +### Create the Server & Client + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Subscribe to streaming events +agent.on("sessionEvent", (data) => { + console.log(data.event); +}); + +// Create a session and send a prompt +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +await agent.sendPrompt( + session.sessionId, + "Write a hello world script to /home/user/hello.js", +); + +// Read the file the agent created +const content = await agent.readFile("/home/user/hello.js"); +console.log(new TextDecoder().decode(content)); +``` + +### Run + +Start the server: + +```bash +npx tsx server.ts +``` + +Then in a separate terminal, run the client: + +```bash +npx tsx client.ts +``` + +### Customize + +Now that you have a working agent, customize it to fit your needs: + +- **[Software](/docs/agent-os/software)** — Install software packages inside the VM +- **[Tools](/docs/agent-os/tools)** — Expose your JavaScript functions to agents as CLI commands +- **[Filesystem](/docs/agent-os/filesystem)** — Read, write, and manage files inside the VM +- **[Registry](/docs/registry)** — Browse more agents, tools, and filesystems + +## agentOS Core + +The quickstart above uses `rivetkit/agent-os`, which includes statefulness, multiplayer, and orchestration out of the box. If you only need direct VM control without those features, you can use the core package (`@rivet-dev/agent-os-core`) standalone. + +See [agentOS core documentation](/docs/agent-os/core) for reference. + +_Source doc path: /docs/agent-os/quickstart_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/sandbox.md b/.agents/skills/ai-agent-workspace/reference/agent-os/sandbox.md new file mode 100644 index 0000000..9812d46 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/sandbox.md @@ -0,0 +1,108 @@ +# Sandbox Mounting + +> Source: `src/content/docs/agent-os/sandbox.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/sandbox +> Description: Extend agentOS with full sandboxes for heavy workloads like browsers, desktop automation, and compilation. + +--- +- **Hybrid architecture** pairs agentOS with full sandboxes on demand +- **Pay-per-second billing** so sandboxes only cost money while they are running +- **Filesystem mount** projects the sandbox into the VM as a native directory, like mounting a hard drive on your own machine +- **Toolkit** exposes sandbox process management as [host tools](/docs/agent-os/tools) +- **Provider-agnostic** via [Sandbox Agent](https://sandboxagent.dev) under the hood + +## Why use agentOS with a sandbox? + +agentOS is not a replacement for sandboxes. It's designed to work alongside them. agentOS makes it easy to integrate agents into your backend with [host tools](/docs/agent-os/tools), [permissions](/docs/agent-os/permissions), the [LLM gateway](/docs/agent-os/llm-gateway), and orchestration. Sandbox mounting lets you connect a full sandbox environment when the workload needs it. + +See [agentOS vs Sandbox](/docs/agent-os/versus-sandbox) for a detailed comparison. + +## When to use a sandbox + +- **Native binaries** not yet supported in the agentOS runtime. +- **Browsers and desktop automation**: Playwright, Puppeteer, Selenium, or anything that needs a display server. +- **Heavy compilation**: Large builds or native toolchains that require a full Linux environment. +- **GUI applications**: Desktop apps, VNC sessions, or any workload that needs a graphical environment. +- **Node.js packages with native extensions** (e.g. `sharp`, `bcrypt`, `better-sqlite3`) that require a full build toolchain. + +## Getting started + +The `@rivet-dev/agent-os-sandbox` package integrates through two mechanisms: + +- **Filesystem mount**: Projects the sandbox into the VM as a native directory, like mounting a hard drive on your own machine. Read and write files through the mount directly. +- **Toolkit**: Exposes sandbox process management as [host tools](/docs/agent-os/tools). Execute commands on the sandbox from within the VM. + +Both are powered by [Sandbox Agent](https://sandboxagent.dev), so you can swap providers without changing agent code. + +```bash +npm install @rivet-dev/agent-os-sandbox sandbox-agent +``` + +```ts @nocheck +import { SandboxAgent } from "sandbox-agent"; +import { DockerProvider } from "sandbox-agent/docker"; +import { AgentOs } from "@rivet-dev/agent-os-core"; +import common from "@rivet-dev/agent-os-common"; +import { createSandboxFs, createSandboxToolkit } from "@rivet-dev/agent-os-sandbox"; + +const sandbox = await SandboxAgent.start({ + sandbox: new DockerProvider(), +}); + +const vm = await AgentOs.create({ + software: [common], + mounts: [ + { + path: "/sandbox", + driver: createSandboxFs({ client: sandbox }), + }, + ], + toolKits: [createSandboxToolkit({ client: sandbox })], +}); + +// Write code via the filesystem. The /sandbox mount maps to the sandbox root. +await vm.writeFile("/sandbox/app/index.ts", 'console.log("hello")'); + +// Run it via the toolkit. Commands execute inside the sandbox, so paths are +// relative to the sandbox root (/app/index.ts), not the VM mount (/sandbox/app/index.ts). +const result = await vm.exec("agentos-sandbox run-command --command node --json '{\"args\": [\"/app/index.ts\"]}'"); +``` + +## Tools reference + +The toolkit exposes these commands inside the VM: + +```bash +# Run a command synchronously +agentos-sandbox run-command --command "npm install" --cwd "/app" + +# Start a background process +agentos-sandbox create-process --command "npm" --json '{"args": ["run", "dev"]}' + +# List running processes +agentos-sandbox list-processes + +# Get process output +agentos-sandbox get-process-logs --id "proc_abc123" + +# Stop or kill a process +agentos-sandbox stop-process --id "proc_abc123" +agentos-sandbox kill-process --id "proc_abc123" + +# Send input to an interactive process +agentos-sandbox send-input --id "proc_abc123" --input "yes" +``` + +## Sandbox providers + +The extension works with any [Sandbox Agent](https://sandboxagent.dev) provider. See the [Sandbox Agent documentation](https://sandboxagent.dev) for available providers and setup instructions. + +## Recommendations + +- Start with the default agentOS VM for all workloads. Only spin up a sandbox when you hit a task that genuinely requires one. +- Sandboxes are billed per second of uptime. Spin them up on demand and tear them down when the task is done to minimize cost. +- The hybrid model means your agent can handle both lightweight coding tasks and heavy system operations in the same session, using the right tool for each. +- See [Tools](/docs/agent-os/tools) for how host tools work and how the agent calls them as CLI commands. +- See [Security Model](/docs/agent-os/security-model) for details on the VM isolation model. + +_Source doc path: /docs/agent-os/sandbox_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/security-model.md b/.agents/skills/ai-agent-workspace/reference/agent-os/security-model.md new file mode 100644 index 0000000..89c401a --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/security-model.md @@ -0,0 +1,52 @@ +# Security Model + +> Source: `src/content/docs/agent-os/security-model.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/security-model +> Description: Trust boundaries, isolation guarantees, and the agentOS threat model. + +--- +agentOS is in beta and still undergoing security review. The security model described here is subject to change. + +## Deny by default + +No syscalls are bound to the system by default. Everything is denied until explicitly opted in. Network access, filesystem mounts, process spawning, and all other capabilities must be configured by the host before the VM can use them. + +## Trust boundaries + +agentOS has two trust boundaries: + +1. **Runtime boundary.** The VM isolate that runs agent code. All code inside the VM is untrusted. The isolate prevents access to the host process, host filesystem, and host network. +2. **Host boundary.** Your application code that configures and manages the VM. You are responsible for hardening the host process, validating inputs, and managing secrets. + +## VM isolation + +Each agentOS actor runs in its own isolated VM: + +- **Sandboxed execution.** All agent code runs inside a V8 isolate with WebAssembly. No code escapes the isolate boundary. +- **Virtual filesystem.** The VM has its own filesystem. Agents cannot access host files unless explicitly mounted. +- **Virtual network.** The VM has no direct access to the host network. Outbound requests are proxied through the host with configurable controls. +- **Process isolation.** No host process is visible or accessible from inside the VM. + +## What agentOS guarantees + +- Agent code cannot read or write host files outside configured mounts +- Agent code cannot make network requests except through the host proxy +- Agent code cannot access host environment variables or secrets +- Each actor's filesystem, sessions, and state are isolated from other actors +- Resource limits (CPU, memory) are enforced at the VM level + +## What you are responsible for + +- Hardening the host process and deployment environment +- Validating authentication tokens in `onBeforeConnect` +- Scoping [permissions](/docs/agent-os/permissions) appropriately for your use case +- Managing API keys and secrets on the host side (use the [LLM gateway](/docs/agent-os/llm-gateway) to avoid passing keys into the VM) +- Configuring [resource limits and network controls](/docs/agent-os/security) to match your threat model + +## Further reading + +- [Security configuration](/docs/agent-os/security) for resource limits, network control, and authentication setup +- [Permissions](/docs/agent-os/permissions) for agent tool-use approval patterns +- [agentOS vs Sandbox](/docs/agent-os/versus-sandbox) for when to escalate to a full sandbox + +_Source doc path: /docs/agent-os/security-model_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/security.md b/.agents/skills/ai-agent-workspace/reference/agent-os/security.md new file mode 100644 index 0000000..fffb85c --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/security.md @@ -0,0 +1,101 @@ +# Security & Auth + +> Source: `src/content/docs/agent-os/security.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/security +> Description: Configure resource limits, network control, authentication, and filesystem isolation for agentOS. + +--- +For the isolation model and trust boundaries, see [Security Model](/docs/agent-os/security-model). + +## Resource limits + +Restrict CPU and memory per actor to prevent runaway agents. + +```ts @nocheck +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { + software: [common, pi], + maxMemoryMb: 512, + maxCpuPercent: 50, + }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Network control + +Control which ports and hosts the VM can access. + +```ts @nocheck +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; + +const vm = agentOs({ + options: { + software: [common], + loopbackExemptPorts: [8080, 3000], + }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Custom authentication + +Use the `onBeforeConnect` hook to validate clients before they access the agent. + +```ts @nocheck +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + onBeforeConnect: async (c, params) => { + const isValid = await verifyToken(params.token); + if (!isValid) { + throw new Error("Unauthorized"); + } + }, + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); + +async function verifyToken(token: string): Promise { + // Your authentication logic + return token === "valid-token"; +} +``` + +## Permission system + +Agents request permission before using tools. See [Permissions](/docs/agent-os/permissions) for auto-approve, selective approval, and human-in-the-loop patterns. + +## Preview URL security + +Preview URLs use randomly generated 32-character alphanumeric tokens with configurable expiration. See [Networking & Previews](/docs/agent-os/networking) for token management. + +- Tokens are stored in SQLite and survive sleep/wake +- Expired tokens are automatically cleaned up +- Use `expireSignedPreviewUrl` to immediately revoke a token + +## Filesystem isolation + +Each VM has its own virtual filesystem. Files are isolated per actor instance. + +- `/home/user` is persistent and survives sleep/wake +- Mount boundaries prevent escape via symlinks or path traversal +- Host directory mounts (if configured) prevent symlink escape beyond the mount point + +_Source doc path: /docs/agent-os/security_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/sessions.md b/.agents/skills/ai-agent-workspace/reference/agent-os/sessions.md new file mode 100644 index 0000000..61e9b8b --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/sessions.md @@ -0,0 +1,461 @@ +# Sessions + +> Source: `src/content/docs/agent-os/sessions.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/sessions +> Description: Create agent sessions, send prompts, stream responses, and replay event history. + +--- +- **Create sessions** with any supported agent type +- **Stream responses** in real time via `sessionEvent` subscriptions +- **Replay events** with sequence numbers for reconnection and history +- **Persist transcripts** automatically in SQLite across sleep/wake cycles +- **Universal transcript format** using the Agent Communication Protocol (ACP) + +Currently only [Pi](https://github.com/mariozechner/pi-coding-agent) is supported as an agent. Amp, Claude Code, Codex, and OpenCode are coming soon. + +## Create a session + +Use `createSession` to launch an agent inside the VM. Returns session metadata including capabilities and agent info. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +console.log(session.sessionId); +console.log(session.capabilities); +console.log(session.agentInfo); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +### `env` + +Environment variables to pass to the agent process. The VM does not inherit from the host `process.env`, so API keys must be passed explicitly. + +```ts @nocheck +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +``` + +### `cwd` + +Working directory for the agent session inside the VM. Defaults to `/home/user`. + +```ts @nocheck +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, + cwd: "/home/user/project", +}); +``` + +### `mcpServers` + +Pass MCP servers to give the agent access to additional tools. MCP servers provide typed tool definitions that the agent's LLM can discover and call natively. + +#### Local MCP server + +Run an MCP server as a child process inside the VM. + +```ts @nocheck +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, + mcpServers: [ + { + type: "local", + command: "npx", + args: ["-y", "@modelcontextprotocol/server-filesystem", "/home/user"], + env: {}, + }, + ], +}); +``` + +#### Remote MCP server + +Connect to an MCP server running outside the VM. + +```ts @nocheck +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, + mcpServers: [ + { + type: "remote", + url: "https://mcp.example.com/sse", + headers: { + Authorization: "Bearer my-token", + }, + }, + ], +}); +``` + +### `additionalInstructions` + +Append custom instructions to the agent's system prompt. + +```ts @nocheck +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, + additionalInstructions: "Always write tests before implementation.", +}); +``` + +### `skipOsInstructions` + +Skip the base OS instructions injection. Tool documentation is still included even when this is `true`. + +```ts @nocheck +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, + skipOsInstructions: true, +}); +``` + +## Send a prompt + +Use `sendPrompt` to send a message to an active session. The response contains the agent's reply. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +const response = await agent.sendPrompt( + session.sessionId, + "Create a TypeScript function that checks if a number is prime", +); +console.log(response); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Stream responses + +Subscribe to `sessionEvent` to receive real-time streaming output from the agent. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Subscribe to session events before sending the prompt +agent.on("sessionEvent", (data) => { + console.log(`[${data.sessionId}]`, data.event.method, data.event.params); +}); + +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +await agent.sendPrompt(session.sessionId, "Explain how async/await works"); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Cancel a prompt + +Use `cancelPrompt` to stop an in-progress prompt. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); + +// Start a long-running prompt +const promptPromise = agent.sendPrompt( + session.sessionId, + "Refactor the entire codebase to use TypeScript strict mode", +); + +// Cancel after 10 seconds +setTimeout(async () => { + await agent.cancelPrompt(session.sessionId); +}, 10_000); + +const response = await promptPromise; +console.log(response); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Resume, close, and destroy sessions + +- `resumeSession` reconnects to a session that was suspended (e.g. after sleep) +- `closeSession` gracefully closes a session +- `destroySession` removes the session and all persisted data + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Resume a previously created session +const resumed = await agent.resumeSession("session-id-from-earlier"); + +// Close without destroying persisted data +await agent.closeSession(resumed.sessionId); + +// Destroy session and all persisted events +await agent.destroySession(resumed.sessionId); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Runtime configuration + +Change model, mode, and thought level on a live session. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); + +// Change model +await agent.setModel(session.sessionId, "claude-sonnet-4-6"); + +// Change mode (e.g. "plan", "auto") +await agent.setMode(session.sessionId, "plan"); + +// Change thought level +await agent.setThoughtLevel(session.sessionId, "high"); + +// Query available options +const modes = await agent.getModes(session.sessionId); +console.log(modes); + +const options = await agent.getConfigOptions(session.sessionId); +console.log(options); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Replay events + +Use `getSequencedEvents` to replay in-memory session events (for live reconnection while the VM is running), or `getSessionEvents` to replay from persisted storage (for transcript history, including when the VM is not running). See [Events](/docs/agent-os/events#event-replay) for details on the difference. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +await agent.sendPrompt(session.sessionId, "Hello"); + +// Get all events +const events = await agent.getEvents(session.sessionId); +console.log(events); + +// Get events with sequence numbers (for pagination/reconnection) +const sequenced = await agent.getSequencedEvents(session.sessionId, { + since: 0, +}); +console.log(sequenced); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Persisted session history + +Query session history from SQLite. Works even when the VM is not running. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// List all persisted sessions +const sessions = await agent.listPersistedSessions(); +for (const s of sessions) { + console.log(s.sessionId, s.agentType, s.createdAt); +} + +// Get full event history for a session +const events = await agent.getSessionEvents(sessions[0].sessionId); +for (const e of events) { + console.log(e.seq, e.event.method, e.createdAt); +} +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Multiple sessions + +A single VM can run multiple sessions simultaneously. Each session has its own agent process but shares the same filesystem. Use different session IDs to manage them independently. + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +// Create two sessions in the same VM +const coder = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +const reviewer = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); + +// Coder writes code +await agent.sendPrompt(coder.sessionId, "Write a REST API at /home/user/api.ts"); + +// Reviewer reads and reviews the same file +await agent.sendPrompt(reviewer.sessionId, "Review /home/user/api.ts for issues"); + +// Close each session independently +await agent.closeSession(coder.sessionId); +await agent.closeSession(reviewer.sessionId); +``` + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +## Recommendations + +- Subscribe to `sessionEvent` **before** calling `sendPrompt` to avoid missing early events. +- Use `getSequencedEvents` with `since` for reconnection. Track the last sequence number you processed. +- Use `listPersistedSessions` and `getSessionEvents` to build transcript history UIs without requiring a running VM. +- Call `closeSession` when done to release resources. Use `destroySession` only when you want to permanently delete session data. + +_Source doc path: /docs/agent-os/sessions_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/software.md b/.agents/skills/ai-agent-workspace/reference/agent-os/software.md new file mode 100644 index 0000000..ca54ab0 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/software.md @@ -0,0 +1,56 @@ +# Software + +> Source: `src/content/docs/agent-os/software.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/software +> Description: Install software packages and configure the commands available inside agentOS. + +--- +agentOS starts with no commands installed. The `software` option lets you declare which packages to include. Each package provides one or more CLI commands. + +## Install + +```bash +npm install @rivet-dev/agent-os-core @rivet-dev/agent-os-common +``` + +`@rivet-dev/agent-os-common` is a meta-package that includes coreutils, sed, grep, gawk, findutils, diffutils, tar, and gzip. For a smaller footprint, install individual packages instead. + +## Usage + +```ts @nocheck +import { AgentOs } from "@rivet-dev/agent-os-core"; +import common from "@rivet-dev/agent-os-common"; + +const vm = await AgentOs.create({ + software: [common], +}); + +const result = await vm.exec("echo hello | grep hello"); +console.log(result.stdout); // "hello\n" + +await vm.dispose(); +``` + +You can mix individual packages and meta-packages: + +```ts @nocheck +import { AgentOs } from "@rivet-dev/agent-os-core"; +import coreutils from "@rivet-dev/agent-os-coreutils"; +import grep from "@rivet-dev/agent-os-grep"; +import jq from "@rivet-dev/agent-os-jq"; +import ripgrep from "@rivet-dev/agent-os-ripgrep"; + +const vm = await AgentOs.create({ + software: [coreutils, grep, jq, ripgrep], +}); +``` + +## Available Packages + +Browse all available software packages on the [Registry](/agent-os/registry). + +## Publishing Custom Packages + +See the [agent-os-registry contributing guide](https://github.com/rivet-dev/agent-os/blob/main/registry/CONTRIBUTING.md) for how to add new software packages to the registry. + +_Source doc path: /docs/agent-os/software_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/sqlite.md b/.agents/skills/ai-agent-workspace/reference/agent-os/sqlite.md new file mode 100644 index 0000000..e46b657 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/sqlite.md @@ -0,0 +1,66 @@ +# SQLite + +> Source: `src/content/docs/agent-os/sqlite.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/sqlite +> Description: Give agents access to a persistent SQLite database via host tools. + +--- +Each agentOS actor has a built-in SQLite database that persists across sessions and sleep/wake cycles. Expose it to agents as a host tool so they can run arbitrary SQL queries. + +## Example + +Give the agent a single `sql` tool that executes any SQL query against the actor's SQLite database. + +```ts @nocheck +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; +import { db } from "rivetkit/db"; +import { toolKit, hostTool } from "@rivet-dev/agent-os-core"; +import { z } from "zod"; + +const actorDb = db({}); + +const sqlToolkit = toolKit({ + name: "db", + description: "SQLite database", + tools: { + sql: hostTool({ + description: "Execute a SQL query against the actor's SQLite database. Use this for creating tables, inserting data, and querying data. Returns rows for SELECT queries.", + inputSchema: z.object({ + query: z.string().describe("SQL query to execute"), + }), + execute: async (input) => { + const result = await actorDb.execute(input.query); + return result; + }, + }), + }, +}); + +const vm = agentOs({ + db: actorDb, + options: { software: [common, pi], toolKits: [sqlToolkit] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +The agent calls it as a CLI command: + +```bash +agentos-db sql --query "CREATE TABLE notes (id INTEGER PRIMARY KEY, content TEXT, created_at INTEGER)" +agentos-db sql --query "INSERT INTO notes (content, created_at) VALUES ('auth uses JWT with 24h expiry', 1711843200000)" +agentos-db sql --query "SELECT * FROM notes WHERE content LIKE '%auth%'" +``` + +The database persists in the actor's storage across sessions and sleep/wake cycles. The agent can create whatever schema it needs and build up structured data over time. + +## Recommendations + +- See [SQLite](/docs/actors/sqlite) for the full SQLite API reference. +- See [Tools](/docs/agent-os/tools) for how host tools work. + +_Source doc path: /docs/agent-os/sqlite_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/system-prompt.md b/.agents/skills/ai-agent-workspace/reference/agent-os/system-prompt.md new file mode 100644 index 0000000..89dd022 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/system-prompt.md @@ -0,0 +1,24 @@ +# System Prompt + +> Source: `src/content/docs/agent-os/system-prompt.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/system-prompt +> Description: How agentOS injects context into agent sessions. + +--- +agentOS automatically injects a system prompt into every agent session that describes the VM environment and available tools. The prompt is additive and never replaces the agent's own instructions (CLAUDE.md, AGENTS.md, etc.). + +The base prompt lives at `/etc/agentos/instructions.md` inside the VM. + +## Customization + +```ts @nocheck +const session = await vm.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, + // Append custom instructions + additionalInstructions: "Always write tests before implementation.", + // Suppress the base OS prompt (tool docs are still injected) + skipOsInstructions: true, +}); +``` + +_Source doc path: /docs/agent-os/system-prompt_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/tools.md b/.agents/skills/ai-agent-workspace/reference/agent-os/tools.md new file mode 100644 index 0000000..a9df6c5 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/tools.md @@ -0,0 +1,151 @@ +# Tools + +> Source: `src/content/docs/agent-os/tools.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/tools +> Description: Expose custom tools to agents as CLI commands inside the VM. + +--- +Expose your JavaScript functions to agents as CLI commands inside the VM. + +- **Define tools on the host** with Zod input schemas +- **Auto-generated CLI commands** installed at `/usr/local/bin/agentos-{toolkit}` +- **Code mode compatible** for up to 80% token reduction since tool calls are just shell commands +- **Tool list injected** into the agent's [system prompt](/docs/agent-os/system-prompt) automatically + +## Getting started + +Define a toolkit with Zod input schemas and pass it to `agentOs()`. Each tool becomes a CLI command inside the VM. + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; +import { toolKit, hostTool } from "@rivet-dev/agent-os-core"; +import { z } from "zod"; + +const weatherToolkit = toolKit({ + name: "weather", + description: "Weather data tools", + tools: { + forecast: hostTool({ + description: "Get the weather forecast for a city", + inputSchema: z.object({ + city: z.string().describe("City name"), + days: z.number().optional().describe("Number of days"), + }), + execute: async (input) => { + const res = await fetch(`https://api.weather.example/forecast?city=${input.city}&days=${input.days ?? 3}`); + return res.json(); + }, + examples: [ + { description: "3-day forecast for Paris", input: { city: "Paris", days: 3 } }, + ], + }), + }, +}); + +const vm = agentOs({ + options: { software: [common, pi], + toolKits: [weatherToolkit], + }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const agent = client.vm.getOrCreate(["my-agent"]); + +const session = await agent.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, +}); +await agent.sendPrompt(session.sessionId, "What's the weather in Paris?"); +``` + +### Zod to CLI mapping + +Zod schema fields are converted to CLI flags automatically. Field names are converted from camelCase to kebab-case. + +| Zod type | CLI syntax | Example | +|---|---|---| +| `z.string()` | `--name value` | `--path /tmp/out.png` | +| `z.number()` | `--name 42` | `--limit 5` | +| `z.boolean()` | `--flag` / `--no-flag` | `--full-page` | +| `z.enum(["a","b"])` | `--name a` | `--format json` | +| `z.array(z.string())` | `--name a --name b` | `--tags foo --tags bar` | + +Optional fields (via `.optional()`) become optional flags. Required fields are enforced at validation time. + +### What the agent sees + +When toolkits are registered, CLI shims are installed at `/usr/local/bin/agentos-{name}` inside the VM and the tool list is injected into the agent's [system prompt](/docs/agent-os/system-prompt). + +The agent interacts with tools as shell commands: + +```bash +# List all available toolkits +agentos list-tools + +# List tools in a specific toolkit +agentos list-tools weather + +# Get help for a tool +agentos-weather forecast --help + +# Call a tool with flags +agentos-weather forecast --city Paris --days 3 + +# Call a tool with inline JSON +agentos-weather forecast --json '{"city":"Paris","days":3}' + +# Call a tool with JSON from a file +agentos-weather forecast --json-file /tmp/input.json + +# Pipe JSON via stdin +echo '{"city":"Paris"}' | agentos-weather forecast +``` + +Tool responses are JSON: + +```json +{"ok":true,"result":{"temperature":22,"condition":"sunny"}} +``` + +Error responses include an error code and message: + +```json +{"ok":false,"error":"VALIDATION_ERROR","message":"Expected string at \"city\", received number"} +``` + +## Tools vs MCP servers + +agentOS supports two ways to give agents access to external functionality: **host tools** and **MCP servers**. Both work, but they have different tradeoffs. + +| | Host Tools | MCP Servers | +|---|---|---| +| **How it works** | Call JavaScript functions on the host directly | Connect to a standard MCP server | +| **Authentication** | None required. Direct binding to the agent's OS. | Requires custom auth configuration per server | +| **Code mode** | Built-in. Tools are exposed as CLI commands, so agents can call them inside scripts for up to 80% token reduction. | Requires extra work to make code mode work out of the box | +| **Latency** | Near-zero. Bound directly to the host process. | Extra network hop to reach the MCP server | +| **Setup** | Define tools in your actor code with Zod schemas | Configure any standard MCP server | + +Use host tools when you want to expose your own JavaScript functions to agents. Use MCP servers when you want to connect to existing third-party services. See [Sessions](/docs/agent-os/sessions#mcpservers) for MCP server configuration. + +## Security + +Tool calls from the agent securely invoke your `execute()` functions on the host. Your functions run with full access to the host environment, so you can call databases, APIs, and services directly without proxying credentials into the VM. The agent never sees the credentials — it only sees the tool's input/output contract. + +## Recommendations + +- Keep tool descriptions concise. They are injected into the agent's system prompt and consume tokens. +- Use `.describe()` on Zod fields to generate useful `--help` output. +- Set explicit timeouts on long-running tools instead of relying on the 30s default. +- Tools execute on the host with full access to the host environment. Do not expose tools that could compromise the host without appropriate safeguards. + +_Source doc path: /docs/agent-os/tools_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/versus-sandbox.md b/.agents/skills/ai-agent-workspace/reference/agent-os/versus-sandbox.md new file mode 100644 index 0000000..9a4ef9e --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/versus-sandbox.md @@ -0,0 +1,54 @@ +# agentOS vs Sandbox + +> Source: `src/content/docs/agent-os/versus-sandbox.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/versus-sandbox +> Description: When to use the lightweight agentOS VM, a full sandbox, or both together. + +--- +- **agentOS** is a lightweight VM that runs inside your process. Near-zero cold start, low memory, direct backend integration via [host tools](/docs/agent-os/tools). +- **Sandboxes** are full Linux environments with root access, system packages, and native binary support. +- **You can use both.** agentOS works with sandboxes through [sandbox mounting](/docs/agent-os/sandbox). Agents run in the lightweight VM by default and spin up a full sandbox on demand. + +## Comparison + +| | agentOS VM | Full Sandbox | +|---|---|---| +| **Cost** | Very low. Runs in your process. | Pay per second of uptime. | +| **Startup** | Near-zero cold start (~6 ms). | Seconds to spin up. | +| **Backend integration** | Direct. [Host tools](/docs/agent-os/tools) call your functions with zero latency. | Indirect. Requires network calls back to your backend. | +| **API keys** | Stay on the server via the [LLM gateway](/docs/agent-os/llm-gateway). | Must be injected into the sandbox environment. | +| **Permissions** | Granular, deny-by-default. | Coarse-grained (container-level). | +| **Infrastructure** | `npm install` | Vendor account + API keys. | +| **Best for** | Coding, file manipulation, scripting, API calls, orchestration. | Browsers, desktop automation, native compilation, dev servers. | + +## When to use each + +### agentOS VM + +Use the lightweight VM for most agent workloads: + +- Coding and file editing +- Running scripts and CLI tools +- Calling APIs and services via host tools +- Multi-agent orchestration and workflows +- Tasks where backend integration matters (permissions, tool access, LLM routing) + +### Full sandbox + +Spin up a sandbox when the workload needs a real Linux kernel: + +- Browsers and desktop automation (Playwright, Puppeteer, Selenium) +- Heavy compilation and native toolchains +- Dev servers with hot reload, databases, and system ports +- GUI applications and VNC sessions + +### Both together + +Use agentOS with [sandbox mounting](/docs/agent-os/sandbox) for workflows that need both: + +- Agent runs in the agentOS VM with full access to host tools and permissions +- Sandbox spins up on demand for heavy tasks +- Sandbox filesystem is mounted into the VM as a native directory +- Agent reads and writes sandbox files the same way it reads local files + +_Source doc path: /docs/agent-os/versus-sandbox_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/webhooks.md b/.agents/skills/ai-agent-workspace/reference/agent-os/webhooks.md new file mode 100644 index 0000000..e8166ee --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/webhooks.md @@ -0,0 +1,103 @@ +# Webhooks + +> Source: `src/content/docs/agent-os/webhooks.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/webhooks +> Description: Trigger agent workflows from external webhooks using Hono and queues. + +--- +Use a lightweight HTTP server to receive webhooks and queue them for agent processing. This example uses [Hono](https://hono.dev) to receive Slack webhooks and dispatch them to an agent via queues. + +## Example: Slack webhook to agent + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; +import { actor, queue, setup } from "rivetkit"; +import { Hono } from "hono"; +import { createClient } from "rivetkit/client"; + +// Actor that processes Slack messages via a queue +const slackWorker = actor({ + queues: { + messages: queue<{ channel: string; text: string; user: string }>(), + }, + run: async (c) => { + const agentHandle = c.actors.vm.getOrCreate(["slack-agent"]); + + for await (const message of c.queue.iter()) { + const { channel, text, user } = message.body; + + const session = await agentHandle.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, + }); + const response = await agentHandle.sendPrompt( + session.sessionId, + `Slack message from ${user} in #${channel}:\n\n${text}\n\nRespond helpfully.`, + ); + await agentHandle.closeSession(session.sessionId); + + // Post the response back to Slack + await fetch("https://slack.com/api/chat.postMessage", { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${process.env.SLACK_BOT_TOKEN}`, + }, + body: JSON.stringify({ channel, text: response }), + }); + } + }, +}); + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { slackWorker, vm } }); +registry.start(); + +// Hono server to receive Slack webhooks +const app = new Hono(); +const client = createClient("http://localhost:6420"); + +app.post("/slack/events", async (c) => { + const body = await c.req.json(); + + // Handle Slack URL verification + if (body.type === "url_verification") { + return c.json({ challenge: body.challenge }); + } + + // Queue the message for the agent + if (body.event?.type === "message" && !body.event?.bot_id) { + const worker = client.slackWorker.getOrCreate(["main"]); + await worker.send("messages", { + channel: body.event.channel, + text: body.event.text, + user: body.event.user, + }); + } + + return c.json({ ok: true }); +}); + +export default app; +``` + +## How it works + +1. Slack sends an HTTP POST to `/slack/events` +2. The Hono handler validates the event and pushes it to the actor's queue +3. The queue processes messages one at a time, creating agent sessions for each +4. The agent responds and the worker posts the reply back to Slack + +The queue provides backpressure and durability. If the agent is busy, messages wait in the queue. If the server restarts, queued messages are replayed. + +## Recommendations + +- Use [Queues](/docs/agent-os/queues) to decouple webhook ingestion from agent processing. This prevents slow agent responses from blocking the webhook endpoint. +- Return `200` from the webhook handler immediately after queuing. External services like Slack have short timeout windows. +- Store webhook secrets in environment variables, not in code. + +_Source doc path: /docs/agent-os/webhooks_ diff --git a/.agents/skills/ai-agent-workspace/reference/agent-os/workflows.md b/.agents/skills/ai-agent-workspace/reference/agent-os/workflows.md new file mode 100644 index 0000000..930a46e --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/agent-os/workflows.md @@ -0,0 +1,163 @@ +# Workflow Automation + +> Source: `src/content/docs/agent-os/workflows.mdx` +> Canonical URL: https://rivet.dev/docs/agent-os/workflows +> Description: Orchestrate multi-step agent tasks with durable workflows. + +--- +- **Durable workflows** that survive crashes and restarts +- **Multi-step orchestration** with sessions, file operations, and process execution +- **Error handling and retry** via `ctx.step()` for each operation +- **Agent chaining** where output of one session feeds into the next + +## Basic workflow + +Use the actor `workflow()` primitive to orchestrate a multi-step agent task. Each step is durable and will resume from where it left off after a restart. + +Session creation and prompting must happen within the same step because sessions are ephemeral and won't survive a replay. + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; +import { actor, setup, workflow } from "rivetkit"; + +const automator = actor({ + workflows: { + fixBug: workflow<{ repo: string; issue: string }>(), + }, + run: async (c) => { + for await (const message of c.workflow.iter("fixBug")) { + const { repo, issue } = message.body; + const agentHandle = c.actors.vm.getOrCreate([`fix-${issue}`]); + + // Step 1: Clone the repo + await c.step("clone-repo", async () => { + return agentHandle.exec(`git clone ${repo} /home/user/repo`); + }); + + // Step 2: Agent fixes the bug (session lives within this step) + await c.step("fix-bug", async () => { + const session = await agentHandle.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, + }); + await agentHandle.sendPrompt( + session.sessionId, + `Fix the bug described in issue: ${issue}`, + ); + await agentHandle.closeSession(session.sessionId); + }); + + // Step 3: Run tests + const tests = await c.step("run-tests", async () => { + return agentHandle.exec("cd /home/user/repo && npm test"); + }); + + console.log("Tests exit code:", tests.exitCode); + await message.complete(); + } + }, +}); + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { automator, vm } }); +registry.start(); +``` + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const handle = client.automator.getOrCreate(["main"]); + +// Trigger the workflow +await handle.send("fixBug", { + repo: "https://github.com/example/repo.git", + issue: "Fix the login redirect bug", +}); +``` + +## Agent chaining + +Output of one agent session feeds into the next. Each session is created and completed within its own step. + +```ts @nocheck server.ts +import { agentOs } from "rivetkit/agent-os"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; +import { actor, setup, workflow } from "rivetkit"; + +const pipeline = actor({ + workflows: { + codeReview: workflow<{ filePath: string }>(), + }, + run: async (c) => { + for await (const message of c.workflow.iter("codeReview")) { + const agentHandle = c.actors.vm.getOrCreate([`review-${Date.now()}`]); + + // Step 1: Agent reviews code and writes findings to a file + await c.step("review", async () => { + const session = await agentHandle.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, + }); + await agentHandle.sendPrompt( + session.sessionId, + `Review the code at ${message.body.filePath} and write your findings to /home/user/review.md`, + ); + await agentHandle.closeSession(session.sessionId); + }); + + // Step 2: Read the review from the filesystem + const review = await c.step("read-review", async () => { + const content = await agentHandle.readFile("/home/user/review.md"); + return new TextDecoder().decode(content); + }); + + // Step 3: Second session applies fixes based on the review + await c.step("fix", async () => { + const session = await agentHandle.createSession("pi", { + env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! }, + }); + await agentHandle.sendPrompt( + session.sessionId, + `Apply the following review feedback:\n\n${review}`, + ); + await agentHandle.closeSession(session.sessionId); + }); + + await message.complete(); + } + }, +}); + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { pipeline, vm } }); +registry.start(); +``` + +```ts @nocheck client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./server"; + +const client = createClient("http://localhost:6420"); +const handle = client.pipeline.getOrCreate(["main"]); + +await handle.send("codeReview", { filePath: "/home/user/src/auth.ts" }); +``` + +## Recommendations + +- Create and close sessions within the same step. Sessions are ephemeral and won't exist after a workflow replays. +- Pass data between steps via the filesystem or step return values, not session state. +- Keep step names stable across code changes. Renaming a step breaks replay for in-progress workflows. +- Use separate actors for the workflow orchestrator and the agentOS VM. +- See [Workflows](/docs/actors/workflows) for the full workflow API reference including timers, joins, and races. + +_Source doc path: /docs/agent-os/workflows_ diff --git a/.agents/skills/ai-agent-workspace/reference/cli.md b/.agents/skills/ai-agent-workspace/reference/cli.md new file mode 100644 index 0000000..34880ea --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/cli.md @@ -0,0 +1,103 @@ +# CLI + +> Source: `src/content/docs/cli.mdx` +> Canonical URL: https://rivet.dev/docs/cli +> Description: Reference for the optional rivet CLI: deploy to Rivet Compute and run local dev for serverless platforms. + +--- +The `rivet` CLI (`@rivetkit/cli`) is optional. You only need it for: + +| Use case | Command | +| --- | --- | +| Deploy to Rivet Compute | `rivet deploy` | +| Local dev for serverless platforms (Cloudflare, Supabase) | `rivet dev --provider ` | + +Run it with your package runner: + +```bash +npx @rivetkit/cli +``` + +| Command | Description | +| --- | --- | +| `rivet dev` | Run a local engine and your handler's dev server. | +| `rivet deploy` | Build and deploy the project to Rivet Cloud. | +| `rivet engine` | Run the bundled `rivet-engine` binary directly. | +| `rivet setup-ci` | Install the GitHub Actions deploy workflow. | + +## `rivet dev` + +Starts a local engine, spawns your dev server, and registers the serverless runner pointing at it. The engine keeps running across restarts; Ctrl-C stops only the dev server. + +```bash +rivet dev [--provider ] [--port N] [--fn-name NAME] [--url URL] [-- ...] +``` + +`--provider` selects how the dev server is launched. Anything after `--` is appended to the preset command (or is the command to run when no provider is set). + +| `--provider` | Spawns | Port | +| --- | --- | --- | +| _(omitted)_ | your `-- ` (needs `--port`) | from `--port` | +| `serverless` | your `-- ` (gets `PORT`) | auto | +| `cloudflare` | `wrangler dev` | `8787` | +| `supabase` | `supabase functions serve` | `54321` | +| `none` | nothing (engine only) | — | + +For `cloudflare`, the CLI also passes the engine endpoint as `--var RIVET_ENDPOINT:...`, so the Worker connects back with no `wrangler.toml` config. + +| Flag | Description | +| --- | --- | +| `--port` | Handler port. Required without a provider unless `--url` is set. | +| `--fn-name` | Supabase function name (default `rivet`). | +| `--url` | Explicit handler URL, overriding port and path. | +| `--engine-binary` | Path to a `rivet-engine` binary. | + +## `rivet deploy` + +Builds and pushes your project's Docker image and upserts the managed pool, printing the dashboard URL. See [Deploying to Rivet Compute](/docs/deploy/rivet-compute). + +```bash +rivet deploy --token cloud_api_xxxxx +``` + +The token is saved to `~/.rivet/credentials` (also read from `RIVET_CLOUD_TOKEN`), so later deploys can omit it. + +| Flag | Default | Description | +| --- | --- | --- | +| `--token` | env / credentials | Rivet Cloud API token. | +| `--namespace` | `production` | Cloud namespace. | +| `--project` / `--org` | from token | Override project/org. | +| `--dockerfile` | `Dockerfile` | Dockerfile to build. | +| `--build-context` | `.` | Docker build context. | +| `--env KEY=VAL` | — | Environment override, repeatable. | +| `--image` | project slug | Image repository name. | +| `--tag` | git short SHA | Image tag. | + +## `rivet engine` + +Runs the bundled `rivet-engine` binary directly, against the same local database and ports as `rivet dev`. Arguments are forwarded verbatim. + +```bash +rivet engine nuke # wipe local engine state +rivet engine wf list # inspect workflows +``` + +## `rivet setup-ci` + +Installs `.github/workflows/rivet-deploy.yml`, which deploys to Rivet Cloud on push and pull request. Add `--force` to overwrite. Then set the token secret: + +```bash +gh secret set RIVET_CLOUD_TOKEN +``` + +## Engine binary resolution + +`rivet dev` and `rivet engine` resolve the `rivet-engine` binary from, in order: `--engine-binary`, `RIVET_ENGINE_BINARY_PATH`, a binary bundled next to the CLI, a local `target/{debug,release}` build, then an auto-downloaded release. Set `RIVETKIT_ENGINE_AUTO_DOWNLOAD=0` to require a local binary. + +## Related + +- [Deploying to Rivet Compute](/docs/deploy/rivet-compute) +- [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) +- [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) + +_Source doc path: /docs/cli_ diff --git a/.agents/skills/ai-agent-workspace/reference/clients/javascript.md b/.agents/skills/ai-agent-workspace/reference/clients/javascript.md new file mode 100644 index 0000000..304db1f --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/clients/javascript.md @@ -0,0 +1,288 @@ +# Node.js & Bun + +> Source: `src/content/docs/clients/javascript.mdx` +> Canonical URL: https://rivet.dev/docs/clients/javascript +> Description: Connect JavaScript apps to Rivet Actors. + +--- +## Getting Started + +See the [backend quickstart guide](/docs/actors/quickstart/backend) for getting started. + +## Minimal Client + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient({ + endpoint: "https://my-namespace:pk_...@api.rivet.dev", +}); +const counter = client.counter.getOrCreate(["my-counter"]); +const count = await counter.increment(1); +``` + +```ts index.ts @hide +import { actor, setup } from "rivetkit"; + +export const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, x: number) => { + c.state.count += x; + return c.state.count; + }, + }, +}); + +export const registry = setup({ + use: { counter }, +}); + +registry.start(); +``` + +## Stateless vs Stateful + +```typescript +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.counter.getOrCreate(["my-counter"]); + +// Stateless: each call is independent +await handle.increment(1); + +// Stateful: keep a connection open for realtime events +const conn = handle.connect(); +conn.on("count", (value) => console.log(value)); +await conn.increment(1); +``` + +## Getting Actors + +```typescript +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const room = client.chatRoom.getOrCreate(["room-42"]); +const existing = client.chatRoom.get(["room-42"]); + +const created = await client.game.create(["game-1"], { + input: { mode: "ranked" }, +}); + +const byId = client.chatRoom.getForId("actor-id"); +const resolvedId = await room.resolve(); +``` + +## Connection Parameters + +```typescript params +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const chat = client.chatRoom.getOrCreate(["general"], { + params: { authToken: "jwt-token-here" }, +}); + +const conn = chat.connect(); +``` + +```typescript getParams +import { createClient } from "rivetkit/client"; + +async function getAuthToken(): Promise { + return "jwt-token-here"; +} + +const client = createClient(); +const chat = client.chatRoom.getOrCreate(["general"], { + getParams: async () => ({ + authToken: await getAuthToken(), + }), +}); + +const conn = chat.connect(); +``` + +Use `params` for static connection parameters. Use `getParams` when the value can change between connection attempts, such as refreshing a JWT before each `.connect()` or reconnect. + +## Subscribing to Events + +```typescript +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const conn = client.chatRoom.getOrCreate(["general"]).connect(); +conn.on("message", (msg) => console.log(msg)); +conn.once("gameOver", () => console.log("done")); +``` + +## Connection Lifecycle + +```typescript +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const conn = client.chatRoom.getOrCreate(["general"]).connect(); + +conn.onOpen(() => console.log("connected")); +conn.onClose(() => console.log("disconnected")); +conn.onError((err) => console.error("error:", err)); +conn.onStatusChange((status) => console.log("status:", status)); + +await conn.dispose(); +``` + +## Low-Level HTTP & WebSocket + +For actors that implement `onRequest` or `onWebSocket`, call them directly: + +```ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("history"); +const history = await response.json(); + +const ws = await handle.webSocket("stream"); +ws.addEventListener("message", (event) => { + console.log("message:", event.data); +}); +ws.send("hello"); +``` + +## Calling from Backend + +```typescript +import { Hono } from "hono"; +import { createClient } from "rivetkit/client"; + +const app = new Hono(); +const client = createClient(); + +app.post("/increment/:name", async (c) => { + const counterHandle = client.counter.getOrCreate([c.req.param("name")]); + const newCount = await counterHandle.increment(1); + return c.json({ count: newCount }); +}); +``` + +## Error Handling + +```typescript +import { ActorError } from "rivetkit/client"; +import { createClient } from "rivetkit/client"; + +const client = createClient(); + +try { + await client.user.getOrCreate(["user-123"]).updateUsername("ab"); +} catch (error) { + if (error instanceof ActorError) { + console.log(error.code, error.metadata); + } +} +``` + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```ts client.ts +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +// Compound key: [org, room] +client.chatRoom.getOrCreate(["org-acme", "general"]); +``` + +```ts index.ts @hide +import { actor, setup } from "rivetkit"; + +export const chatRoom = actor({ + state: { messages: [] as string[] }, + actions: { + getRoomInfo: (c) => ({ org: c.key[0], room: c.key[1] }), + }, +}); + +export const registry = setup({ + use: { chatRoom }, +}); + +registry.start(); +``` + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`createClient()` automatically reads: + +- `RIVET_ENDPOINT` (endpoint) +- `RIVET_NAMESPACE` +- `RIVET_TOKEN` +- `RIVET_RUNNER` + +Defaults to `http://localhost:6420` when unset. RivetKit runs on port 6420 by default. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, use your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## Advanced + +### Skip Ready Wait + +Requests are normally held at the gateway until the actor is ready to accept traffic. An actor is not ready while it's still starting (before `onWake` finishes) or while it's in the [sleep grace period](/docs/actors/lifecycle#shutdown-sequence) (running `onSleep`, `waitUntil`, and pending disconnects). + +Pass `skipReadyWait: true` on the [low-level HTTP and WebSocket APIs](#low-level-http--websocket) to deliver immediately and reach the actor's `onRequest` / `onWebSocket` handler in either window: + +```ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("/healthz", { + skipReadyWait: true, +}); + +const ws = await handle.webSocket("probe", undefined, { + skipReadyWait: true, +}); +``` + +Requests can still return transient lifecycle or gateway errors. Retry once the actor is available again. + +- `actor.stopping`: the actor has fully stopped, i.e. the sleep grace period has ended but it has not yet restarted. +- `guard.actor_stopped_while_waiting`: the request reached the actor tunnel, but the actor stopped before the gateway received a response. +- `guard.tunnel_request_aborted`: the actor tunnel aborted the request before a response started. +- `guard.tunnel_message_timeout`: the gateway dropped the in-flight tunnel request after its tunnel message timeout. +- `guard.tunnel_response_closed`: the actor tunnel closed before sending a response. +- `guard.gateway_response_start_timeout`: the gateway timed out waiting for the actor response to start. + +## API Reference + +**Package:** [rivetkit](https://www.npmjs.com/package/rivetkit) + +See the [RivetKit client overview](/docs/clients). + +- [`createClient`](/typedoc/functions/rivetkit.client_mod.createClient.html) - Create a client +- [`Client`](/typedoc/types/rivetkit.mod.Client.html) - Client type + +_Source doc path: /docs/clients/javascript_ diff --git a/.agents/skills/ai-agent-workspace/reference/clients/react.md b/.agents/skills/ai-agent-workspace/reference/clients/react.md new file mode 100644 index 0000000..dadd70f --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/clients/react.md @@ -0,0 +1,273 @@ +# React + +> Source: `src/content/docs/clients/react.mdx` +> Canonical URL: https://rivet.dev/docs/clients/react +> Description: Connect React apps to Rivet Actors. + +--- +## Getting Started + +See the [React quickstart guide](/docs/actors/quickstart/react) for getting started. + +## Install + +## Minimal Client + +```tsx Counter.tsx +import { createRivetKit } from "@rivetkit/react"; +import type { registry } from "./index"; + +const { useActor } = createRivetKit({ + endpoint: "https://my-namespace:pk_...@api.rivet.dev", +}); + +function Counter() { + const { connection, connStatus } = useActor({ name: "counter", key: ["my-counter"] }); + + if (connStatus !== "connected" || !connection) return
Connecting...
; + return ; +} +``` + +```ts index.ts @hide +import { actor, setup } from "rivetkit"; + +export 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; + }, + }, +}); + +export const registry = setup({ + use: { counter }, +}); + +registry.start(); +``` + +## Stateless vs Stateful + +```tsx +import { createRivetKit } from "@rivetkit/react"; + +const { useActor } = createRivetKit(); + +function Counter() { + const counter = useActor({ name: "counter", key: ["my-counter"] }); + + const increment = async () => { + await counter.connection?.increment(1); + }; + + return ; +} +``` + +```tsx +// Stateless: use createClient for one-off calls (SSR or utilities) +import { createClient } from "rivetkit/client"; + +const client = createClient(); +await client.counter.getOrCreate(["my-counter"]).increment(1); +``` + +## Getting Actors + +```tsx +import { createRivetKit } from "@rivetkit/react"; +import { createClient } from "rivetkit/client"; + +const { useActor } = createRivetKit(); + +function ChatRoom() { + const room = useActor({ name: "chatRoom", key: ["room-42"] }); + return
{room.connStatus}
; +} + +// For get/getOrCreate/create/getForId, use createClient +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["room-42"]); +const existing = client.chatRoom.get(["room-42"]); +const created = await client.game.create(["game-1"], { input: { mode: "ranked" } }); +const byId = client.chatRoom.getForId("actor-id"); +const resolvedId = await handle.resolve(); +``` + +## Connection Parameters + +```tsx +import { createRivetKit } from "@rivetkit/react"; + +const { useActor } = createRivetKit(); + +function Chat() { + const chat = useActor({ + name: "chatRoom", + key: ["general"], + params: { authToken: "jwt-token-here" }, + }); + + return
{chat.connStatus}
; +} +``` + +## Subscribing to Events + +```tsx +import { createRivetKit } from "@rivetkit/react"; + +const { useActor } = createRivetKit(); + +function Chat() { + const chat = useActor({ name: "chatRoom", key: ["general"] }); + + chat.useEvent("message", (msg) => { + console.log("message:", msg); + }); + + return null; +} +``` + +## Connection Lifecycle + +```tsx +import { createRivetKit } from "@rivetkit/react"; + +const { useActor } = createRivetKit(); + +function CounterStatus() { + const actor = useActor({ name: "counter", key: ["my-counter"] }); + + if (actor.connStatus === "connected") { + console.log("connected"); + } + + if (actor.error) { + console.error(actor.error); + } + + return null; +} +``` + +## Low-Level HTTP & WebSocket + +Use the JavaScript client for raw HTTP and WebSocket access: + +```tsx @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("history"); +const history = await response.json(); + +const ws = await handle.webSocket("stream"); +ws.addEventListener("message", (event) => { + console.log("message:", event.data); +}); +ws.send("hello"); +``` + +## Calling from Backend + +Use the JavaScript client on your backend (Node.js/Bun). See the [JavaScript client docs](/docs/clients/javascript). + +## Error Handling + +```tsx +import { ActorError } from "rivetkit/client"; +import { createRivetKit } from "@rivetkit/react"; + +const { useActor } = createRivetKit(); + +function Profile() { + const actor = useActor({ name: "user", key: ["user-123"] }); + + const updateUsername = async () => { + try { + await actor.connection?.updateUsername("ab"); + } catch (error) { + if (error instanceof ActorError) { + console.log(error.code, error.metadata); + } + } + }; + + return ; +} +``` + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```tsx ChatRoom.tsx +import { createRivetKit } from "@rivetkit/react"; +import type { registry } from "./index"; + +const { useActor } = createRivetKit("http://localhost:6420"); + +function ChatRoom() { + const room = useActor({ name: "chatRoom", key: ["org-acme", "general"] }); + return
{room.connStatus}
; +} +``` + +```ts index.ts @hide +import { actor, setup } from "rivetkit"; + +export const chatRoom = actor({ + state: { messages: [] as string[] }, + actions: { + getRoomInfo: (c) => ({ org: c.key[0], room: c.key[1] }), + }, +}); + +export const registry = setup({ + use: { chatRoom }, +}); + +registry.start(); +``` + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`createRivetKit()` (and the underlying `createClient()` instance) automatically read: + +- `RIVET_ENDPOINT` +- `RIVET_NAMESPACE` +- `RIVET_TOKEN` +- `RIVET_RUNNER` + +Defaults to `http://localhost:6420` when unset. RivetKit runs on port 6420 by default. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, use your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## API Reference + +**Package:** [@rivetkit/react](https://www.npmjs.com/package/@rivetkit/react) + +- [`createRivetKit`](/docs/clients/react) - Create hooks for React +- [`useActor`](/docs/clients/react) - Hook for actor instances + +_Source doc path: /docs/clients/react_ diff --git a/.agents/skills/ai-agent-workspace/reference/clients/swift.md b/.agents/skills/ai-agent-workspace/reference/clients/swift.md new file mode 100644 index 0000000..c760645 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/clients/swift.md @@ -0,0 +1,454 @@ +# Swift + +> Source: `src/content/docs/clients/swift.mdx` +> Canonical URL: https://rivet.dev/docs/clients/swift +> Description: Connect Swift apps to Rivet Actors. + +--- +## Install + +Add the Swift package dependency and import `RivetKitClient`: + +```swift +// Package.swift +dependencies: [ + .package(url: "https://github.com/rivet-dev/rivetkit-swift", from: "2.0.0") +] + +targets: [ + .target( + name: "MyApp", + dependencies: [ + .product(name: "RivetKitClient", package: "rivetkit-swift") + ] + ) +] +``` + +## Minimal Client + +### Endpoint URL + +```swift +import RivetKitClient + +let config = try ClientConfig( + endpoint: "https://my-namespace:pk_...@api.rivet.dev" +) +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["my-counter"]) +let count: Int = try await handle.action("increment", 1, as: Int.self) +``` + +### Explicit Fields + +```swift +import RivetKitClient + +let config = try ClientConfig( + endpoint: "https://api.rivet.dev", + namespace: "my-namespace", + token: "pk_..." +) +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["my-counter"]) +let count: Int = try await handle.action("increment", 1, as: Int.self) +``` + +## Stateless vs Stateful + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["my-counter"]) + +// Stateless: each call is independent +let current: Int = try await handle.action("getCount", as: Int.self) +print("Current count: \(current)") + +// Stateful: keep a connection open for realtime events +let conn = handle.connect() + +// Subscribe to events using AsyncStream +let eventTask = Task { + for await count in await conn.events("count", as: Int.self) { + print("Event: \(count)") + } +} + +_ = try await conn.action("increment", 1, as: Int.self) + +eventTask.cancel() +await conn.dispose() +await client.dispose() +``` + +## Getting Actors + +```swift +import RivetKitClient + +struct GameInput: Encodable { + let mode: String +} + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +// Get or create an actor +let room = client.getOrCreate("chatRoom", ["room-42"]) + +// Get an existing actor (fails if not found) +let existing = client.get("chatRoom", ["room-42"]) + +// Create a new actor with input +let created = try await client.create( + "game", + ["game-1"], + options: CreateOptions(input: GameInput(mode: "ranked")) +) + +// Get actor by ID +let byId = client.getForId("chatRoom", "actor-id") + +// Resolve actor ID +let resolvedId = try await room.resolve() +print("Resolved ID: \(resolvedId)") + +await client.dispose() +``` + +Actions support positional overloads for 0–5 args: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("counter", ["my-counter"]) + +let count: Int = try await handle.action("getCount") +let updated: String = try await handle.action("rename", "new-name") +let ok: Bool = try await handle.action("setScore", "user-1", 42) + +print("Count: \(count), Updated: \(updated), OK: \(ok)") +await client.dispose() +``` + +If you need more than 5 arguments, use the raw JSON fallback: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("counter", ["my-counter"]) + +let args: [JSONValue] = [ + .string("user-1"), + .number(.int(42)), + .string("extra"), + .string("more"), + .string("args"), + .string("here") +] +let ok: Bool = try await handle.action("setScore", args: args, as: Bool.self) +print("OK: \(ok)") + +await client.dispose() +``` + +## Connection Parameters + +```swift +import RivetKitClient + +struct ConnParams: Encodable { + let authToken: String +} + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +let chat = client.getOrCreate( + "chatRoom", + ["general"], + options: GetOrCreateOptions(params: ConnParams(authToken: "jwt-token-here")) +) + +let conn = chat.connect() + +// Use the connection... +for await status in await conn.statusChanges() { + print("Status: \(status.rawValue)") + if status == .connected { + break + } +} + +await conn.dispose() +await client.dispose() +``` + +## Subscribing to Events + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let conn = client.getOrCreate("chatRoom", ["general"]).connect() + +// Subscribe to events using AsyncStream +let messageTask = Task { + for await (from, body) in await conn.events("message", as: (String, String).self) { + print("\(from): \(body)") + } +} + +// For one-time events, break after receiving +let gameOverTask = Task { + for await _ in await conn.events("gameOver", as: Void.self) { + print("done") + break + } +} + +// Let it run for a bit +try await Task.sleep(for: .seconds(5)) + +// Cancel when done +messageTask.cancel() +gameOverTask.cancel() +await conn.dispose() +await client.dispose() +``` + +Event streams support 0–5 typed arguments. If you need raw values or more than 5 arguments, use `JSONValue`: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let conn = client.getOrCreate("chatRoom", ["general"]).connect() + +let rawTask = Task { + for await args in await conn.events("message") { + print(args) + } +} + +try await Task.sleep(for: .seconds(5)) +rawTask.cancel() +await conn.dispose() +await client.dispose() +``` + +## Connection Lifecycle + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let conn = client.getOrCreate("chatRoom", ["general"]).connect() + +// Monitor status changes (immediately yields current status) +let statusTask = Task { + for await status in await conn.statusChanges() { + print("status: \(status.rawValue)") + } +} + +// Monitor errors +let errorTask = Task { + for await error in await conn.errors() { + print("error: \(error.group).\(error.code)") + } +} + +// Monitor open/close events +let openTask = Task { + for await _ in await conn.opens() { + print("connected") + } +} + +let closeTask = Task { + for await _ in await conn.closes() { + print("disconnected") + } +} + +// Check current status +let current = await conn.currentStatus +print("Current status: \(current.rawValue)") + +// Let it run for a bit +try await Task.sleep(for: .seconds(5)) + +// Cleanup +statusTask.cancel() +errorTask.cancel() +openTask.cancel() +closeTask.cancel() +await conn.dispose() +await client.dispose() +``` + +## Low-Level HTTP & WebSocket + +For actors that implement `onRequest` or `onWebSocket`, you can call them directly: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("chatRoom", ["general"]) + +// Raw HTTP request +let response = try await handle.fetch("history") +let history: [String] = try response.json([String].self) +print("History: \(history)") + +// Raw WebSocket connection +let websocket = try await handle.websocket(path: "stream") +try await websocket.send(text: "hello") +let message = try await websocket.receive() +print("Received: \(message)") + +await client.dispose() +``` + +## Calling from Backend + +Use the same client in server-side Swift (Vapor, Hummingbird, etc.): + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["server-counter"]) +let count: Int = try await handle.action("increment", 1, as: Int.self) +print("Count: \(count)") + +await client.dispose() +``` + +## Error Handling + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +do { + _ = try await client.getOrCreate("user", ["user-123"]) + .action("updateUsername", "ab", as: String.self) +} catch let error as ActorError { + print("Error code: \(error.code)") + print("Metadata: \(String(describing: error.metadata))") +} + +await client.dispose() +``` + +If you need an untyped response, you can decode to `JSONValue`: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("data", ["raw"]) + +let value: JSONValue = try await handle.action("getRawPayload") +print("Raw value: \(value)") + +await client.dispose() +``` + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +// Use compound keys for hierarchical addressing +let room = client.getOrCreate("chatRoom", ["org-acme", "general"]) +let actorId = try await room.resolve() +print("Actor ID: \(actorId)") + +await client.dispose() +``` + +Don't build keys with string interpolation like `"org:\(userId)"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`ClientConfig` reads optional values from environment variables: + +- `RIVET_NAMESPACE` - Namespace (can also be in endpoint URL) +- `RIVET_TOKEN` - Authentication token (can also be in endpoint URL) +- `RIVET_RUNNER` - Runner name (defaults to `"default"`) + +The `endpoint` parameter is always required. There is no default endpoint. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, set the endpoint to your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## API Reference + +### Client +- `RivetKitClient(config:)` - Create a client with a config +- `ClientConfig` - Configure endpoint, namespace, and token +- `client.get()` / `getOrCreate()` / `getForId()` / `create()` - Get actor handles +- `client.dispose()` - Dispose the client and all connections + +### ActorHandle +- `handle.action(name, args..., as:)` - Stateless action call +- `handle.connect()` - Create a stateful connection +- `handle.resolve()` - Get the actor ID +- `handle.getGatewayUrl()` - Get the raw gateway URL +- `handle.fetch(path, request:)` - Raw HTTP request +- `handle.websocket(path:)` - Raw WebSocket connection + +### ActorConnection +- `conn.action(name, args..., as:)` - Action call over WebSocket +- `conn.events(name, as:)` - AsyncStream of typed events +- `conn.statusChanges()` - AsyncStream of status changes +- `conn.errors()` - AsyncStream of connection errors +- `conn.opens()` - AsyncStream that yields on connection open +- `conn.closes()` - AsyncStream that yields on connection close +- `conn.currentStatus` - Current connection status +- `conn.dispose()` - Close the connection + +### Types +- `ActorConnStatus` - Connection status enum (`.idle`, `.connecting`, `.connected`, `.disconnected`, `.disposed`) +- `ActorError` - Typed actor errors with `group`, `code`, `message`, `metadata` +- `JSONValue` - Raw JSON value for untyped responses + +_Source doc path: /docs/clients/swift_ diff --git a/.agents/skills/ai-agent-workspace/reference/clients/swiftui.md b/.agents/skills/ai-agent-workspace/reference/clients/swiftui.md new file mode 100644 index 0000000..4ae65d8 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/clients/swiftui.md @@ -0,0 +1,359 @@ +# SwiftUI + +> Source: `src/content/docs/clients/swiftui.mdx` +> Canonical URL: https://rivet.dev/docs/clients/swiftui +> Description: Build SwiftUI apps with Rivet Actors. + +--- +## Install + +Add the Swift package dependency and import `RivetKitSwiftUI`: + +```swift +// Package.swift +dependencies: [ + .package(url: "https://github.com/rivet-dev/rivetkit-swift", from: "2.0.0") +] + +targets: [ + .target( + name: "MyApp", + dependencies: [ + .product(name: "RivetKitSwiftUI", package: "rivetkit-swift") + ] + ) +] +``` + +`RivetKitSwiftUI` re-exports `RivetKitClient` and `SwiftUI`, so a single import covers both. + +## Minimal Client + +```swift HelloWorldApp.swift +import RivetKitSwiftUI +import SwiftUI + +@main +struct HelloWorldApp: App { + var body: some Scene { + WindowGroup { + ContentView() + .rivetKit(endpoint: "https://my-namespace:pk_...@api.rivet.dev") + } + } +} +``` + +```swift ContentView.swift +import RivetKitSwiftUI +import SwiftUI + +struct ContentView: View { + @Actor("counter", key: ["my-counter"]) private var counter + @State private var count = 0 + + var body: some View { + VStack(spacing: 16) { + Text("\(count)") + .font(.system(size: 64, weight: .bold, design: .rounded)) + + Button("Increment") { + counter.send("increment", 1) + } + .disabled(!counter.isConnected) + } + .task { + count = (try? await counter.action("getCount")) ?? 0 + } + .onActorEvent(counter, "newCount") { (newCount: Int) in + count = newCount + } + } +} +``` + +## Actor Options + +The `@Actor` property wrapper always uses get-or-create semantics and accepts: + +- `name` (required) +- `key` as `String` or `[String]` (required) +- `params` (optional connection parameters) +- `createWithInput` (optional creation input) +- `createInRegion` (optional creation hint) +- `enabled` (toggle connection lifecycle) + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct ConnParams: Encodable { + let authToken: String +} + +struct ChatView: View { + @Actor( + "chatRoom", + key: ["general"], + params: ConnParams(authToken: "jwt-token"), + enabled: true + ) private var chat + + var body: some View { + Text("Chat: \(chat.connStatus.rawValue)") + } +} +``` + +## Actions + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct CounterView: View { + @Actor("counter", key: ["my-counter"]) private var counter + @State private var count = 0 + @State private var name = "" + + var body: some View { + VStack { + Text("Count: \(count)") + Text("Name: \(name)") + + Button("Fetch") { + Task { + count = try await counter.action("getCount") + name = try await counter.action("rename", "new-name") + } + } + + Button("Increment") { + counter.send("increment", 1) + } + } + } +} +``` + +## Subscribing to Events + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct GameView: View { + @Actor("game", key: ["game-1"]) private var game + @State private var count = 0 + @State private var isGameOver = false + + var body: some View { + VStack { + Text("Count: \(count)") + if isGameOver { + Text("Game Over!") + } + } + .onActorEvent(game, "newCount") { (newCount: Int) in + count = newCount + } + .onActorEvent(game, "gameOver") { + isGameOver = true + } + } +} +``` + +## Async Event Streams + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct ChatView: View { + @Actor("chatRoom", key: ["general"]) private var chat + @State private var messages: [String] = [] + + var body: some View { + List(messages, id: \.self) { message in + Text(message) + } + .task { + for await message in chat.events("message", as: String.self) { + messages.append(message) + } + } + } +} +``` + +## Connection Status + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct StatusView: View { + @Actor("counter", key: ["my-counter"]) private var counter + @State private var count = 0 + + var body: some View { + VStack { + Text("Status: \(counter.connStatus.rawValue)") + + if counter.connStatus == .connected { + Text("Connected!") + .foregroundStyle(.green) + } + + Button("Fetch via Handle") { + Task { + if let handle = counter.handle { + count = try await handle.action("getCount", as: Int.self) + } + } + } + .disabled(!counter.isConnected) + } + } +} +``` + +## Error Handling + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct UserView: View { + @Actor("user", key: ["user-123"]) private var user + @State private var errorMessage: String? + @State private var username = "" + + var body: some View { + VStack { + TextField("Username", text: $username) + + Button("Update Username") { + Task { + do { + let _: String = try await user.action("updateUsername", username) + } catch let error as ActorError { + errorMessage = "\(error.code): \(String(describing: error.metadata))" + } + } + } + + if let errorMessage { + Text(errorMessage) + .foregroundStyle(.red) + } + } + .onActorError(user) { error in + errorMessage = "\(error.group).\(error.code): \(error.message)" + } + } +} +``` + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct OrgChatView: View { + @Actor("chatRoom", key: ["org-acme", "general"]) private var room + + var body: some View { + Text("Room: \(room.connStatus.rawValue)") + } +} +``` + +Don't build keys with string interpolation like `"org:\(userId)"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Configuration + +Call `.rivetKit(endpoint:)` or `.rivetKit(client:)` once at the root of your view tree: + +```swift +// With endpoint string (recommended for most apps) +@main +struct MyApp: App { + var body: some Scene { + WindowGroup { + ContentView() + .rivetKit(endpoint: "https://my-namespace:pk_...@api.rivet.dev") + } + } +} + +// With custom client (for advanced configuration) +@main +struct MyApp: App { + private let client = RivetKitClient( + config: try! ClientConfig(endpoint: "https://api.rivet.dev", token: "pk_...") + ) + + var body: some Scene { + WindowGroup { + ContentView() + .rivetKit(client: client) + } + } +} +``` + +When using `.rivetKit(endpoint:)`, the client is created once and cached per endpoint. When using `.rivetKit(client:)`, store the client as a property on `App` (not inside `body`) since SwiftUI can call `body` multiple times. + +### Environment Variables + +`ClientConfig` reads optional values from environment variables: + +- `RIVET_NAMESPACE` - Namespace (can also be in endpoint URL) +- `RIVET_TOKEN` - Authentication token (can also be in endpoint URL) +- `RIVET_RUNNER` - Runner name (defaults to `"default"`) + +The endpoint is always required. There is no default endpoint. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, set the endpoint to your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## API Reference + +### Property Wrapper +- `@Actor(name, key:, params:, createWithInput:, createInRegion:, enabled:)` - SwiftUI property wrapper for actor connections + +### View Modifiers +- `.rivetKit(endpoint:)` - Configure client with an endpoint URL (creates cached client) +- `.rivetKit(client:)` - Configure client with a custom instance +- `.onActorEvent(actor, event) { ... }` - Subscribe to actor events (supports 0–5 typed args) +- `.onActorError(actor) { error in ... }` - Handle actor errors + +### ActorObservable +- `actor.action(name, args..., as:)` - Async action call +- `actor.send(name, args...)` - Fire-and-forget action +- `actor.events(name, as:)` - AsyncStream of typed events +- `actor.connStatus` - Current connection status +- `actor.isConnected` - Whether connected +- `actor.handle` - Underlying `ActorHandle` (optional) +- `actor.connection` - Underlying `ActorConnection` (optional) +- `actor.error` - Most recent error (optional) + +### Types +- `ActorConnStatus` - Connection status enum (`.idle`, `.connecting`, `.connected`, `.disconnected`, `.disposed`) +- `ActorError` - Typed actor errors with `group`, `code`, `message`, `metadata` + +_Source doc path: /docs/clients/swiftui_ diff --git a/.agents/skills/ai-agent-workspace/reference/cookbook/ai-agent-workspace.md b/.agents/skills/ai-agent-workspace/reference/cookbook/ai-agent-workspace.md new file mode 100644 index 0000000..066e1ef --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/cookbook/ai-agent-workspace.md @@ -0,0 +1,181 @@ +# AI Agent Workspaces + +> Source: `src/content/cookbook/ai-agent-workspace.mdx` +> Canonical URL: https://rivet.dev/cookbook/ai-agent-workspace +> Description: Give every AI agent its own computer: a persistent workspace with a filesystem, processes, shells, networking, and agent sessions on a lightweight in-process OS. + +--- +Patterns for giving every AI agent its own computer with [agentOS](/docs/agent-os): one Rivet Actor per agent that owns a portable, lightweight in-process OS running on Wasm and V8. Use it for code interpreters that keep state between runs, agents that ship artifacts behind shareable preview URLs, per-user dev environments, and scheduled maintenance agents. agentOS is in preview and the API is subject to change. + +This entry is about giving an agent a workspace. For conversation memory, message queues, and streaming chat patterns, see [AI Agent](/cookbook/ai-agent/). + +## Starter Code + +The [agent-os](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os) collection is reference code, one sub-example per capability; treat it as patterns to copy into your project rather than a turnkey app. The [agent-os-e2e](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os-e2e) example is the complete end-to-end walkthrough. + +| Example | Starter Code | Use When | +| --- | --- | --- | +| Hello World | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/hello-world) | You want the minimal loop: boot a VM lazily on the first action, write a file, read it back. | +| Filesystem | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/filesystem) | The agent needs the full file surface: recursive listing, stat, move, delete, and custom mounts. | +| Git | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/git) | The agent works with real git repos inside the workspace: init, commit, branch, and clone via `exec`. | +| Processes | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/processes) | The agent runs shell commands with pipes and long-lived spawned programs. | +| Network | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/network) | The agent serves HTTP inside the VM and you need `vmFetch` or signed preview URLs. | +| Cron | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/cron) | The workspace runs scheduled commands or recurring agent work. | +| Tools | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/tools) | You want your backend functions exposed as CLI commands inside the workspace. | +| Agent Session | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/agent-session) | You drive a Pi coding agent session inside the workspace. Requires `ANTHROPIC_API_KEY`. | +| Sandbox Mounting | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/sandbox) | The agent needs native binaries or a real OS, mounted into the VM from a Docker-backed sandbox. Requires Docker. | +| End-to-End Walkthrough | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os-e2e) | You want one runnable script covering files, processes, preview URLs, and a streaming Pi agent session. | + +## Setup + +The whole backend is one registry with one `agentOs()` actor: + +```typescript +import { agentOs } from "rivetkit/agent-os"; +import { setup } from "rivetkit"; +import common from "@rivet-dev/agent-os-common"; +import pi from "@rivet-dev/agent-os-pi"; + +const vm = agentOs({ + options: { software: [common, pi] }, +}); + +export const registry = setup({ use: { vm } }); +registry.start(); +``` + +See the [Quickstart](/docs/agent-os/quickstart) for the client side and project layout. + +## Workspace Model + +- **One actor per workspace, key as identity.** `client.vm.getOrCreate(["my-agent"])` gives each agent its own workspace; key by user id for per-user dev environments. Each workspace has its own filesystem, processes, and networking with no shared state and no cross-contamination (see the [overview](/docs/agent-os)). +- **Software packages choose what is installed.** agentOS starts with no commands installed. The `software` option installs packages such as `@rivet-dev/agent-os-common` (a meta-package of Wasm command-line tools: coreutils, sed, grep, gawk, findutils, diffutils, tar, and gzip), `@rivet-dev/agent-os-git` (git), and `@rivet-dev/agent-os-pi` (the Pi coding agent). See [Software](/docs/agent-os/software). +- **The VM boots lazily and sleeps when idle.** The first action boots the VM (clients see a `vmBooted` event); when nothing is active, the actor sleeps and broadcasts `vmShutdown`, then wakes on the next action. + +What survives a sleep/wake cycle (see [Persistence](/docs/agent-os/persistence)): + +| Data | Across sleep/wake | +| --- | --- | +| Session transcripts and event history | Persist in actor SQLite as events stream. `listPersistedSessions` and `getSessionEvents` read them back without booting the VM, and `resumeSession` picks a session back up in a rebooted VM. | +| Signed preview URL tokens | Persist in actor SQLite. Requests are validated against the stored token and the VM reboots lazily to serve them, so preview URLs keep working after sleep. | +| Files | Persist when the mount is backed by a persistent driver (database-backed, S3, or a sandbox mount). In-memory mounts come back empty on wake. | +| Processes, shells, and cron jobs | Do not persist. Restart long-running processes and reschedule cron jobs on wake (recommended extension). | + +The actor holds itself awake while sessions, processes, shells, or hooks are active, then sleeps after a grace period. + +## Capability Tour + +| Area | Use It For | Key Actions | Docs | Example | +| --- | --- | --- | --- | --- | +| Filesystem | Give the agent a file tree to read and write | `readFile`, `writeFile`, `mkdir`, `readdir`, `move` | [Filesystem](/docs/agent-os/filesystem) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/filesystem) | +| Processes | Run commands and long-lived programs | `exec`, `spawn`, `waitProcess`, `killProcess` | [Processes](/docs/agent-os/processes) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/processes) | +| Shells | Interactive terminals with streamed output | `openShell`, `writeShell`, `resizeShell`, `closeShell` | [Processes](/docs/agent-os/processes) | No standalone example | +| Networking and preview URLs | Reach services inside the VM and share them externally | `vmFetch`, `createSignedPreviewUrl`, `expireSignedPreviewUrl` | [Networking](/docs/agent-os/networking) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/network) | +| Cron | Scheduled commands and recurring agent sessions | `scheduleCron`, `listCronJobs`, `cancelCronJob` | [Cron](/docs/agent-os/cron) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/cron) | +| Agent sessions | Drive a coding agent inside the workspace | `createSession`, `sendPrompt`, `resumeSession`, `closeSession` | [Sessions](/docs/agent-os/sessions) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/agent-session) | + +Two details worth knowing up front: + +- `createSignedPreviewUrl` returns a relative path plus the token and expiry. Build the full URL with the client handle's `getGatewayUrl()` method; it is a client method, not an actor action. +- Schedule cron jobs through the actor with the `exec` and `session` action types only. Callback cron actions are defined in server code and do not serialize through `listCronJobs`. + +## Driving a Coding Agent Session + +Only the Pi agent (`@rivet-dev/agent-os-pi`) is currently supported as a session agent; Amp, Claude Code, Codex, and OpenCode are coming soon. See [Sessions](/docs/agent-os/sessions). + +1. `createSession("pi", { env: { ANTHROPIC_API_KEY } })` returns a `sessionId`. The VM does not inherit the host `process.env`, so API keys are passed explicitly per session or kept server-side through the [LLM gateway](/docs/agent-os/llm-gateway). +2. Open a realtime connection and subscribe to `sessionEvent` to stream the agent's output, such as message chunks, as it works. +3. `sendPrompt(sessionId, ...)` starts a turn; `cancelPrompt` stops one in flight. +4. When the agent asks to use a tool, clients receive a `permissionRequest` event and answer with `respondPermission`, or the server auto-approves with the `onPermissionRequest` config hook (see [Permissions](/docs/agent-os/permissions)). +5. Transcripts are persisted automatically in the universal transcript format (Agent Communication Protocol, ACP). After sleep, `resumeSession` continues a session in the rebooted VM, and `listPersistedSessions` plus `getSessionEvents` read history without booting the VM at all. + +## Host Tools + +Expose your backend functions to the agent as CLI commands inside the workspace. Define a toolkit with `toolKit()` and `hostTool()` (Zod-schema'd JavaScript functions on the host), pass it via `agentOs({ options: { toolKits: [...] } })`, and it is installed as a command such as `agentos-weather forecast --city Paris --days 3` and injected into the agent's system prompt. The agent calls your backend with no HTTP endpoints or MCP servers to stand up, and CLI-shaped tools are code mode compatible for large token savings. See [Tools](/docs/agent-os/tools) and the [tools example](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os/src/tools). + +## When to Mount a Full Sandbox + +agentOS is not a replacement for sandboxes; it is designed to work alongside them. When a workspace needs native binaries, browsers, compilation, or desktop automation, use sandbox mounting: start a Docker-backed sandbox with `SandboxAgent.start({ sandbox: docker() })`, project its filesystem into the VM as a native directory (for example `/sandbox`) with `createSandboxFs`, and expose sandbox process control as host tools with `createSandboxToolkit`. Filesystem actions like `writeFile` and `readFile` project transparently through the mount while heavy workloads run in the container. + +See [Sandbox Mounting](/docs/agent-os/sandbox) for the hybrid model and [agentOS vs Sandboxes](/docs/agent-os/versus-sandbox) for when each side wins: the lightweight VM has a near-zero cold start (~6 ms) and installs with `npm install`, while sandboxes are full Linux environments billed per second of uptime. + +## Architecture + +| Topic | Summary | +| --- | --- | +| Topology | One `vm[workspaceId]` actor per agent or per user; the actor key is the workspace identity. | +| Ingress | Actor actions for files, processes, networking, cron, and sessions; a realtime connection for streamed events. | +| Streaming | `sessionEvent` per agent event, `processOutput` and `processExit` for spawned processes, `shellData` for interactive shells. | +| Persistence | Session transcripts, event history, and preview tokens in actor SQLite; files persist through persistent mounts. | + +**Actors** + +- **Key**: `vm[workspaceId]`, for example `client.vm.getOrCreate(["my-agent"])` +- **Responsibility**: Owns one workspace. Boots the VM lazily on the first action, serves all capability actions, proxies signed preview URL requests into the VM's virtual network, and persists sessions and tokens to actor SQLite. +- **Actions** (grouped; the most load-bearing of each area) + - Filesystem: `readFile`, `writeFile`, `mkdir`, `readdir`, `readdirRecursive`, `stat`, `exists`, `move`, `deleteFile` + - Processes: `exec`, `spawn`, `writeProcessStdin`, `waitProcess`, `listProcesses`, `killProcess` + - Shells: `openShell`, `writeShell`, `resizeShell`, `closeShell` + - Network: `vmFetch`, `createSignedPreviewUrl`, `expireSignedPreviewUrl` + - Cron: `scheduleCron`, `listCronJobs`, `cancelCronJob` + - Sessions: `createSession`, `sendPrompt`, `cancelPrompt`, `respondPermission`, `resumeSession`, `closeSession`, `destroySession`, `listPersistedSessions`, `getSessionEvents` +- **Queues** + - None +- **Events** + - `vmBooted` + - `vmShutdown` + - `sessionEvent` + - `permissionRequest` + - `processOutput` + - `processExit` + - `shellData` + - `cronEvent` +- **State** + - SQLite + - `agent_os_sessions` and `agent_os_session_events` (session metadata plus seq-ordered transcript events) + - `agent_os_preview_tokens` (signed preview URL tokens with expiry) + - `agent_os_fs_entries` (file content for database-backed mounts) + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant A as vm actor + participant V as agentOS VM + participant P as Pi session + + C->>A: getOrCreate(["my-agent"]) + C->>A: writeFile("/tmp/hello.txt", ...) + Note over A,V: first action boots the VM + A-->>C: vmBooted + C->>A: exec("echo hello | tr a-z A-Z") + A->>V: run command + V-->>A: {exitCode: 0, stdout} + C->>A: spawn("node", ["/tmp/server.mjs"]) + C->>A: createSignedPreviewUrl(8080, 60) + A-->>C: {path, token, expiresAt} + C->>A: fetch(gatewayUrl + path) + Note over A: token checked in SQLite, request proxied into the VM network + C->>A: createSession("pi", {env}) + A->>P: start session + C->>A: sendPrompt(sessionId, ...) + loop streamed agent output + P-->>A: agent event + A-->>C: sessionEvent + end + Note over A: idle, sleeps after grace period (vmShutdown) + C->>A: resumeSession(sessionId) + Note over A,V: wake reboots the VM, restoring transcripts, preview tokens, and persistent mounts +``` + +## Security Checklist + +- **Authenticate connections**: Add the `onBeforeConnect` hook in the `agentOs()` config so only authorized callers reach a workspace. Signed preview URL requests deliberately skip it because the token is the credential; browsers navigating a preview URL cannot supply actor connection params. +- **Gate agent tool use with permissions**: Session permission requests broadcast as `permissionRequest` events for human-in-the-loop approval via `respondPermission`, or run a server-side `onPermissionRequest` policy for automated pipelines. See [Permissions](/docs/agent-os/permissions). +- **Treat preview URLs as bearer credentials**: Tokens are randomly generated 32-character values with a default expiry of 1 hour and a maximum of 24; revoke early with `expireSignedPreviewUrl`. Preview responses carry permissive CORS headers, so do not serve private data on a preview port without app-level auth. +- **Keep LLM credentials off the browser**: Create sessions from trusted server code with the key in `createSession` env, or keep keys entirely server-side with the [LLM gateway](/docs/agent-os/llm-gateway). Session keys are injected into the session environment inside the VM and are never stored in actor config or SQLite. +- **Treat mounted sandboxes as their own trust boundary**: A mounted sandbox is a full Linux environment outside the workspace's Wasm and V8 isolate. Scope what its network and filesystem can reach before projecting it into an agent's VM. +- **Set resource and cost limits**: Cap per-workspace memory and CPU (`maxMemoryMb`, `maxCpuPercent`, see [Security](/docs/agent-os/security)). Active sessions, processes, and shells hold the actor awake, so add per-workspace session caps and token budgets as a recommended extension. + +_Source doc path: /cookbook/ai-agent-workspace_ diff --git a/.agents/skills/ai-agent-workspace/reference/cookbook/ai-agent.md b/.agents/skills/ai-agent-workspace/reference/cookbook/ai-agent.md new file mode 100644 index 0000000..b0db26a --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/cookbook/ai-agent.md @@ -0,0 +1,128 @@ +# AI Agent + +> Source: `src/content/cookbook/ai-agent.mdx` +> Canonical URL: https://rivet.dev/cookbook/ai-agent +> Description: Build an AI agent backend with persistent memory: one Rivet Actor per conversation, queued message handling, and streaming LLM responses as realtime events. + +--- +Patterns for building AI agent backends with RivetKit, where each conversation is one Rivet Actor that owns its memory, its message queue, and its streaming output. + +## Starter Code + +Start with one of the working examples on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/ai-agent) and adapt it. The sections below describe the flagship `ai-agent` example unless a variant is called out explicitly. + +| Variant | Starter Code | Use When | +| --- | --- | --- | +| Queue-driven AI SDK agent | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/ai-agent) | You want a streaming chat agent where each conversation keeps its own persistent memory and processes one message at a time. | +| Sandbox coding agent | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/sandbox-coding-agent) | The agent should run a coding agent (Codex by default) inside an isolated [sandbox](/docs/actors/sandbox) via Docker, Daytona, or E2B. | +| Durable streams agent (experimental) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/experimental-durable-streams-ai-agent) | You want replayable, restart-safe prompt and response delivery through durable streams instead of actor state and events. | +| Agent with a workspace (agentOS) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/agent-os) | The agent needs its own persistent computer: a filesystem, processes, shells, and preview URLs. See the cookbook: [AI Agent Workspaces](/cookbook/ai-agent-workspace/). | + +## Conversation Memory + +Use one actor per conversation, keyed by a conversation or agent id (see [Actor Keys](/docs/actors/keys)). The agent actor's persistent [state](/docs/actors/state) is the conversation memory: in the `ai-agent` example, `messages` and `status` live in JSON actor state and survive sleep and restarts with no external database. Every model call rebuilds the prompt from `c.state.messages` plus a system prompt, so memory and inference input are the same data. + +| Variant | Where Memory Lives | Persisted State Fields | +| --- | --- | --- | +| `ai-agent` | JSON actor state | `messages`, `status` | +| `sandbox-coding-agent` | JSON actor state plus the sandbox ACP session | `messages`, `status`, `sessionId` | +| `experimental-durable-streams-ai-agent` | Durable streams; the actor stores only its conversation id and a read cursor | `conversationId`, `promptStreamOffset` | + +## Message Handling + +In the `ai-agent` example, the client pushes user input onto the agent's `message` [queue](/docs/actors/queues) with `agent.connection.send("message", { text, sender })`. This is a queue push, not an action call. The actor's `run` hook (see [Lifecycle](/docs/actors/lifecycle)) consumes the queue serially with `for await (const queued of c.queue.iter())`. + +Serial queue consumption is the per-conversation concurrency guarantee: at most one in-flight model call per actor, with no extra locking. The `status` field (`thinking` while a model call is in flight) is UI signal only; the run loop is the actual lock. The loop also checks `c.aborted` inside the token stream so shutdown exits gracefully. + +| Variant | Message Ingress | Serialization Guarantee | +| --- | --- | --- | +| `ai-agent` | `message` queue pushed via `connection.send` | `run` hook pops one queued message at a time with `c.queue.iter()`. | +| `sandbox-coding-agent` | `sendMessage` [action](/docs/actors/actions), no queue | Each call awaits the sandbox round trip before broadcasting the result. | +| `experimental-durable-streams-ai-agent` | Durable prompt stream long-polled from `onWake` | `promptStreamOffset` is persisted per chunk, so restarts resume without reprocessing prompts. | + +## Streaming Responses + +The `ai-agent` actor broadcasts a `response` [event](/docs/actors/events) for every model text delta. The payload carries `messageId`, the per-token `delta`, the cumulative `content`, and a `done` flag (plus `error` on failure), so clients can either append deltas or idempotently replace the message by `messageId` using `content`. The example frontend replaces by `messageId`, which tolerates dropped events. The terminal broadcast has an empty `delta`, the full `content`, and `done: true`. + +Because the assistant message object lives in `c.state.messages` and is mutated in place during streaming, partial content persists if the actor restarts mid-stream. The example broadcasts once per AI SDK delta with no throttling; batching or throttling deltas is a recommended extension for high-traffic deployments, not something the example implements. + +Variant differences: `sandbox-coding-agent` sends a single `response` broadcast with `done: true` after the sandbox finishes (no incremental streaming), and `experimental-durable-streams-ai-agent` appends per-token chunks to a durable response stream, then broadcasts `responseComplete` or `responseError`. + +## Architecture + +| Topic | Summary | +| --- | --- | +| Topology | `agentManager["primary"]` singleton directory plus one `agent[agentId]` actor per conversation. | +| Ingress | Client pushes `AgentQueueMessage` payloads onto the agent's `message` queue with `connection.send`. | +| Streaming | One `response` broadcast per model delta, terminal broadcast with `done: true`. | +| Memory | Full transcript and status in JSON actor state; no external database. | + +The manager creates `AgentInfo` records and warms each agent through [actor-to-actor communication](/docs/actors/communicating-between-actors): `createAgent` calls `c.client()`, then `client.agent.getOrCreate([info.id])` and awaits `getStatus()` so the conversation actor exists before the client connects. The sandbox variant extends this topology with a `codingSandbox` actor that shares the agent's key (`codingSandbox.getOrCreate([c.key[0]])`), so the agent-to-sandbox mapping is implicit in the key space. + +**Actors** + +- **Key**: `agentManager["primary"]` +- **Responsibility**: Directory actor. Creates `AgentInfo` records, lists agents, and warms each agent actor via `c.client()`. +- **Actions** + - `createAgent` + - `listAgents` +- **Queues** + - None +- **State** + - JSON + - `agents` + +- **Key**: `agent[agentId]` +- **Responsibility**: One actor per conversation. Holds the full message history and status, consumes queued user messages in its `run` loop, calls the model via the AI SDK, and broadcasts streaming deltas. +- **Actions** + - `getHistory` + - `getStatus` +- **Queues** + - `message` +- **Events** + - `messageAdded` + - `status` + - `response` +- **State** + - JSON + - `messages` + - `status` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant AM as agentManager + participant A as agent + participant LLM as Model API + + C->>AM: createAgent(name) + AM->>A: getOrCreate([info.id]) + getStatus() + AM-->>C: AgentInfo + C->>A: connection.send("message", {text, sender}) + Note over A: run loop pops queue via c.queue.iter() + A-->>C: messageAdded (user message) + A-->>C: messageAdded (assistant placeholder) + A-->>C: status (thinking) + A->>LLM: streamText(system prompt + history) + loop each text delta + LLM-->>A: delta + A-->>C: response {messageId, delta, content, done: false} + end + A-->>C: response {delta: "", content, done: true} + A-->>C: status (idle) +``` + +## Security Checklist + +The examples ship without auth so they stay minimal. Apply this baseline before exposing an agent backend. + +- **API keys stay server-side**: `OPENAI_API_KEY` (or `ANTHROPIC_API_KEY`) is read by the AI SDK inside the actor process. The key never reaches the browser; clients only talk to the actor over RivetKit. The sandbox variant forwards keys into the sandbox env, never to the client. +- **Add authentication**: The examples have no auth, so anyone who reaches the server can create agents, list them, and message any agent whose key they can guess. Add `onBeforeConnect` or `createConnState` checks with scoped tokens as a recommended extension. See [Authentication](/docs/actors/authentication). +- **Validate and rate-limit queue payloads**: The example only skips bodies without a string `text`. Enforce payload size limits, schema validation, and per-connection rate limits as a recommended extension. +- **Derive sender identity server-side**: The example trusts the client-supplied `sender` field verbatim. Bind sender identity to the authenticated connection instead. +- **Cap or trim message history**: The example sends the full transcript on every model call with no cap. Trim or summarize old messages as a recommended extension so prompts and state stay bounded. +- **Set cost ceilings per conversation**: Add per-agent token budgets and quotas as a recommended extension. The sandbox variant runs real compute, so also enforce per-user sandbox quotas and restrict sandbox network egress. + +_Source doc path: /cookbook/ai-agent_ diff --git a/.agents/skills/ai-agent-workspace/reference/cookbook/chat-room.md b/.agents/skills/ai-agent-workspace/reference/cookbook/chat-room.md new file mode 100644 index 0000000..cb8dbe4 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/cookbook/chat-room.md @@ -0,0 +1,114 @@ +# Chat Room + +> Source: `src/content/cookbook/chat-room.mdx` +> Canonical URL: https://rivet.dev/cookbook/chat-room +> Description: Build a realtime chat room backend with Rivet Actors: one actor per room, SQLite-backed message history, and WebSocket broadcast to every connected client. + +--- +Patterns for building a chat room backend with RivetKit: room-scoped actors, persistent message history, and realtime delivery over WebSocket connections. + +## Starter Code + +Start with the working example on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room) and adapt it. The backend is a single `chatRoom` actor; the frontend is a React app using `@rivetkit/react` (see the [React quickstart](/docs/actors/quickstart/react)). + +| Topic | Summary | +| --- | --- | +| Room model | One `chatRoom` actor per room key. The frontend defaults the key to `general`; typing a different room name connects to a different actor. | +| History | SQLite `messages` table created in `db({ onMigrate })`, read back with `ORDER BY id ASC`. | +| Delivery | `sendMessage` inserts the row, then broadcasts a typed `newMessage` event to every connected client. | +| Identity | None in the example. `sender` is a plain action argument; production should bind identity to the connection. | + +## Room-Per-Actor Model + +Each room is one Rivet Actor instance, addressed by [key](/docs/actors/keys). The client calls `useActor({ name: "chatRoom", key: [roomId] })`, which gets-or-creates the actor for that room. This gives you: + +- **Isolation**: each room's history and connections are fully scoped to its key. Switching the room input re-keys the hook and connects to a different actor with separate history. +- **A single serialized writer**: all `sendMessage` calls for one room run through one actor, so message ordering is consistent without locks. The SQLite `AUTOINCREMENT` id is the canonical order, which is why `getHistory` sorts by `id` rather than by timestamp. +- **Natural scaling**: rooms spread across the cluster independently. A hot room does not slow down other rooms. + +## Message History Storage + +This example stores history in the actor's SQLite database, not in JSON state. Pick based on history size and query needs: + +| Approach | Use When | Implementation Guidance | +| --- | --- | --- | +| [SQLite](/docs/actors/sqlite) (what this example uses) | Large or long-lived history that needs ordering, caps, pagination, or search | Create the `messages` table in `db({ onMigrate })`, insert with parameterized queries (`c.db.execute("INSERT ... VALUES (?, ?, ?)", ...)`), and read with `ORDER BY id ASC`. History survives actor sleep and scales past what you want in memory. | +| [JSON state](/docs/actors/state) | Small recent history, for example the last 50 to 100 messages | Push onto a `messages` array in actor state and trim to a cap on every send. Simplest option, but the whole history lives in memory and there is no query layer, so it only fits bounded recent-history use cases. | + +## Broadcast Delivery + +New messages reach connected clients through a typed [event](/docs/actors/events): + +- The actor declares `events: { newMessage: event() }`, where `Message` is `{ sender, text, timestamp }`. +- The `sendMessage` [action](/docs/actors/actions) builds the message with a server-side `Date.now()` timestamp, inserts it into the `messages` table, then calls `c.broadcast("newMessage", message)` and returns the message to the caller. +- Each client subscribes with `useEvent("newMessage", ...)` and appends to its local list. The sender renders its own message through the same broadcast path as everyone else, so all clients stay on one code path. +- History load is connection-gated: once the connection is ready, the client calls `getHistory()` once to render the backlog, then relies on events for everything after. + +Use `c.broadcast(...)` for room-wide messages. For private or per-recipient payloads (such as DMs inside a room), send on the individual connection instead, which is a recommended extension beyond this example. + +## Typing Indicators And Presence (Extension) + +The example does not implement typing indicators, presence, or join/leave handling of any kind. There is no `createConnState`, `onConnect`, or `onDisconnect` in the code. If you need them, add them as ephemeral [connection](/docs/actors/connections) behavior: + +- **Keep it ephemeral**: store the username and typing flag in per-connection state, never in SQLite or persisted actor state. Presence is derived from live connections and should disappear with them. +- **Broadcast on change only**: emit a typing event when a user starts or stops typing, and a presence event from `onConnect` / `onDisconnect`, rather than polling or ticking. +- **Expire on the client**: clear a typing indicator after a short client-side timeout so a dropped connection never leaves a stuck "is typing" row. + +## Per-User Inbox (Extension) + +For offline delivery, DMs, unread counts, or notification fanout, add a `userInbox[userId]` actor per user. This is an extension beyond the example: + +- The room actor forwards each message to the inbox actor of every member via [actor-to-actor calls](/docs/actors/communicating-between-actors), so users who are not connected to the room still accumulate messages. +- The inbox actor owns per-user unread state and serves it when the user comes online, independent of which rooms they are in. +- DMs become a degenerate room: either a `chatRoom` keyed by the sorted pair of user ids, or direct inbox-to-inbox delivery if you do not need shared history semantics. + +## Actors + +- **Key**: `chatRoom[roomId]` +- **Responsibility**: Owns one chat room. Persists the room's message history in its SQLite database and broadcasts each new message to every connected client. +- **Actions** + - `sendMessage` + - `getHistory` +- **Queues** + - None +- **Events** + - `newMessage` +- **State** + - SQLite + - `messages` table: `id` (autoincrement primary key), `sender`, `text`, `timestamp` + +## Lifecycle + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant R as chatRoom + + A->>R: connect with key [roomId] + Note over R: every start runs onMigrate (CREATE TABLE IF NOT EXISTS messages) + A->>R: getHistory() + R-->>A: Message[] ordered by id + B->>R: connect with key [roomId] + B->>R: getHistory() + R-->>B: Message[] ordered by id + A->>R: sendMessage(sender, text) + Note over R: INSERT row with server timestamp + R-->>A: newMessage (broadcast) + R-->>B: newMessage (broadcast) + A->>R: disconnect + Note over R: history stays in SQLite for the next connection +``` + +## Security Checklist + +The example is intentionally minimal and skips all of the following. Add them before production: + +- **Auth before join**: any client can join any room by knowing its name, and `sender` is arbitrary client input on every call. Validate a token during [connection auth](/docs/actors/authentication), bind identity to [connection state](/docs/actors/connections), and check room membership before serving history. Never trust a sender name passed as an action argument. +- **Message length clamps**: the example accepts empty messages and has no length limit. Trim server-side, reject empty text, and clamp to a maximum length. +- **Per-connection rate limiting**: rate limit `sendMessage` per connection to stop spam and broadcast amplification. +- **Server-side timestamps and ids**: the example already does this correctly. `timestamp` comes from `Date.now()` inside the action and `id` from SQLite `AUTOINCREMENT`. Keep it that way; never accept client-supplied timestamps or ids. +- **History caps**: `getHistory` returns every row with no limit. Add a `LIMIT` plus pagination, and prune or archive old rows so a long-lived room cannot grow unbounded. +- **Parameterized queries**: the example already inserts with `?` placeholders. Keep all user-supplied text out of SQL string interpolation. + +_Source doc path: /cookbook/chat-room_ diff --git a/.agents/skills/ai-agent-workspace/reference/cookbook/collaborative-text-editor.md b/.agents/skills/ai-agent-workspace/reference/cookbook/collaborative-text-editor.md new file mode 100644 index 0000000..cacbc1f --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/cookbook/collaborative-text-editor.md @@ -0,0 +1,157 @@ +# Collaborative Text Editor + +> Source: `src/content/cookbook/collaborative-text-editor.mdx` +> Canonical URL: https://rivet.dev/cookbook/collaborative-text-editor +> Description: Build a collaborative text editor backend with Yjs CRDTs and Rivet Actors: per-document actors relay sync and awareness updates and persist snapshots. + +--- +Patterns for building a Yjs server on RivetKit: CRDT document sync, presence and cursors, and snapshot persistence, with one Rivet Actor per document acting as a relay. + +## Starter Code + +Start with the working example on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/collaborative-document) and adapt it to your editor. It ships a React frontend with a plain textarea, remote cursor overlays, and a workspace document index. + +| Use Case | Starter Code | Common Examples | +| --- | --- | --- | +| Shared document editing | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/collaborative-document) | Notion-style docs, shared notes, pair-writing tools, form co-editing | + +## CRDT vs OT + +Two families of algorithms solve concurrent text editing. The choice decides what your server has to do. + +| Dimension | CRDT (Yjs) | Operational Transformation | +| --- | --- | --- | +| Conflict resolution model | Commutative merges. Updates apply in any order on any peer and converge to the same result. | Server transforms each operation against every concurrent operation. Correctness depends on a central sequencer. | +| Offline support | Strong. Clients keep editing locally and merge buffered updates on reconnect. | Weak. Long-lived divergence makes transformation chains complex and fragile. | +| Server role | Relay plus persistence. The server applies opaque updates and rebroadcasts them. It never needs to understand document semantics. | Authoritative transformer. The server must implement transformation logic for every operation type. | +| Library maturity | Yjs is mature and widely deployed, with bindings for ProseMirror, CodeMirror, Monaco, and others. | Production-grade implementations are mostly proprietary (Google Docs) or aging (ShareDB). | + +The example uses Yjs because CRDTs let the server stay a relay-style Rivet Actor. The actor applies each incoming update to a server-side `Y.Doc` so it can persist the merged state and serve late joiners, but it never transforms operations or arbitrates conflicts. Ordering does not matter because Yjs merges are commutative. + +## Document Actor Model + +| Topic | Summary | +| --- | --- | +| Topology | One `document[workspaceId, documentId]` actor per document plus one `documentList[workspaceId]` coordinator per workspace. | +| Sync model | Each client holds a local `Y.Doc`. The document actor relays incremental Yjs updates as broadcast [events](/docs/actors/events) and keeps a server-side merged copy in vars. | +| Persistence | Full merged Yjs snapshot overwritten in one binary [actor KV](/docs/actors/kv) key (`yjs:doc`) on every sync update. Document metadata lives in JSON [state](/docs/actors/state). | +| Queues | None. The example is purely [actions](/docs/actors/actions) plus broadcast events. | +| Presence | Yjs Awareness relayed through the same `applyUpdate` action. Per-connection `connState` tracks asserted awareness clientIds for disconnect cleanup. | + +The two-actor split follows the coordinator pattern from [Design Patterns](/docs/actors/design-patterns): the coordinator owns discovery and creation, and each document actor owns one document's realtime state. Multi-part [keys](/docs/actors/keys) scope both actors to a workspace. + +**Actors** + +- **Key**: `document[workspaceId, documentId]` +- **Responsibility**: Applies incoming sync and awareness updates to a server-side `Y.Doc` and `Awareness`, persists the merged Yjs snapshot to actor KV, and broadcasts updates to all connected collaborators. +- **Actions** + - `getContent` + - `applyUpdate` + - `getAwareness` +- **Queues** + - None +- **State** + - JSON metadata only: `title`, `createdAt`, `updatedAt` + - Binary KV key `yjs:doc` holding the full merged Yjs snapshot + - Ephemeral vars: the live `Y.Doc` and `Awareness`, created in `createVars` and rehydrated from KV on actor start + - Per-connection `connState`: `clientIds` of awareness clients asserted by that connection + +- **Key**: `documentList[workspaceId]` +- **Responsibility**: Coordinator for one workspace. Creates document actors through the actor-to-actor client and maintains the index of document summaries. +- **Actions** + - `createDocument` + - `listDocuments` + - `deleteDocument` +- **Queues** + - None +- **State** + - JSON + - `documents` array of `DocumentSummary` entries (`id`, `title`, `createdAt`, `updatedAt`) + +The coordinator's `createDocument` generates a UUID, then explicitly creates the document actor with `c.client()` and passes `{ title, createdAt }` as creation [input](/docs/actors/input), which the document actor's `createState` consumes. See [Communicating Between Actors](/docs/actors/communicating-between-actors) for the actor-to-actor client. + +## Update Relay + +A single `applyUpdate(update, kind, clientId?)` action handles both update kinds. Updates cross the action boundary as `number[]` byte arrays and are converted back to `Uint8Array` on each side. + +| Kind | Server Applies To | Persists | Broadcasts | +| --- | --- | --- | --- | +| `"sync"` | `c.vars.doc` via `Y.applyUpdate` with origin `"client"` | Full merged snapshot to KV key `yjs:doc`, then bumps `updatedAt` | `sync` event carrying the incremental update | +| `"awareness"` | `c.vars.awareness` via `applyAwarenessUpdate` with origin `"client"` | Nothing. Presence is ephemeral. | `awareness` event carrying the update | + +Note the asymmetry on the sync branch: the broadcast carries only the small incremental update, while the KV write stores the full merged document re-encoded with `Y.encodeStateAsUpdate`. + +Yjs origin tags are the echo guards that keep the relay loop-free: + +| Origin Tag | Set Where | Effect | +| --- | --- | --- | +| `"local"` | Client edits inside `doc.transact(..., "local")` | The client's update listener fires and sends `applyUpdate` to the actor. | +| `"client"` | Server applying an incoming update to its `Y.Doc` or `Awareness` | Marks the change as client-originated on the server copy. | +| `"remote"` | Client applying broadcast events or initial sync data | Update listeners early-return on `"remote"`, so a client never re-sends its own echo. | + +On connect or reconnect, the client calls `getContent` and `getAwareness`, then applies both results to its local `Y.Doc` and `Awareness` with origin `"remote"`. After that, every change flows through `applyUpdate` and the broadcast events. + +## Awareness And Presence + +Presence (user names, colors, cursor positions) rides on the Yjs Awareness protocol instead of actor state: + +- Clients set presence with `awareness.setLocalStateField` for the `user` and `cursor` fields. The awareness update listener encodes the change and sends `applyUpdate(update, "awareness", awareness.clientID)`. +- The actor records each asserted `clientId` in that connection's `connState.clientIds`, applies the update to the server-side `Awareness`, and broadcasts the `awareness` event to all peers. See [Connections](/docs/actors/connections) for per-connection state. +- `onDisconnect` reads the connection's `clientIds`, calls `removeAwarenessStates` on the server-side `Awareness`, and broadcasts the encoded removal so every remaining client drops the departed user's cursor. See [Lifecycle](/docs/actors/lifecycle) for the hook. + +Because the actor tracks which awareness clientIds belong to which connection, presence cleanup is automatic on disconnect with no client cooperation required. + +## Persistence And Compaction + +The example persists with a full-snapshot overwrite: on every `"sync"` update, the actor re-encodes the entire merged document with `Y.encodeStateAsUpdate` and overwrites the single binary KV key `yjs:doc`. There is no append-only update log and no separate compaction job. Compaction is implicit because `Y.encodeStateAsUpdate` emits one compact merged representation of the document, so Yjs merge semantics keep the stored blob compact on their own. + +| Property | Full-Snapshot Overwrite (the example) | +| --- | --- | +| Write cost | One full-document KV write per sync update, so every keystroke rewrites the whole blob. | +| Read cost | One binary KV read in `createVars` rehydrates the document on actor start. | +| Crash safety | The last completed `applyUpdate` is durable. No log replay needed. | +| Sweet spot | Small to medium documents where simplicity beats write amplification. | + +**Recommended extension (not in the example)**: for large documents or very high edit rates, switch to appending incremental updates to a KV update log and writing a merged snapshot only periodically (for example every N updates). Boot becomes snapshot plus log replay, and the snapshot write becomes the explicit compaction step that truncates the log. Adopt this only when full-snapshot writes become the measured bottleneck or the blob approaches KV value size limits. + +## Lifecycle + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant DL as documentList + participant D as document + + A->>DL: listDocuments() + A->>DL: createDocument(title) + DL->>D: create([workspaceId, documentId], input) + DL-->>A: DocumentSummary + A->>D: connect + B->>D: connect + Note over D: createVars rehydrates Y.Doc from KV "yjs:doc" + A->>D: getContent() + getAwareness() + D-->>A: encoded doc + awareness state + Note over A: local edit with origin "local" + A->>D: applyUpdate(update, "sync") + Note over D: apply with origin "client", overwrite KV snapshot + D-->>B: sync event (incremental update) + Note over B: apply with origin "remote", no echo + A->>D: applyUpdate(update, "awareness", clientId) + D-->>B: awareness event + B-->>D: disconnect + Note over D: onDisconnect removes B's awareness clientIds + D-->>A: awareness event (removal) +``` + +## Security Checklist + +The example ships with no authentication or authorization. Harden it with this baseline before production. None of these are implemented in the example. + +- **Authenticate before connect**: Anyone who knows or guesses a workspace ID can connect, and because `useActor` implicitly getOrCreates, connecting with a nonexistent workspace ID silently creates a blank `documentList` coordinator. Add connection auth so unauthenticated clients never reach an actor. See [Authentication](/docs/actors/authentication). +- **Per-document access control**: Validate that the authenticated user is allowed to access the specific `[workspaceId, documentId]` key, not just any document. +- **Cap and rate limit `applyUpdate`**: Update payloads are unvalidated `number[]` arrays with no size limit, and the example client sends one action per keystroke and per cursor move with zero throttling. Enforce payload size caps and per-connection rate limits on the server, and debounce on the client. +- **Do not trust client-asserted awareness clientIds**: The `clientId` argument to `applyUpdate` is client-supplied and trusted as-is. Derive or verify presence identity from connection-scoped server state instead. +- **Destroy actors and KV on delete**: `deleteDocument` only filters the entry out of the coordinator's index. The document actor and its KV snapshot are orphaned. On delete, also destroy the document actor and its storage, with a permission check on who may delete. + +_Source doc path: /cookbook/collaborative-text-editor_ diff --git a/.agents/skills/ai-agent-workspace/reference/cookbook/cron-jobs.md b/.agents/skills/ai-agent-workspace/reference/cookbook/cron-jobs.md new file mode 100644 index 0000000..cf24b4a --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/cookbook/cron-jobs.md @@ -0,0 +1,141 @@ +# Cron Jobs and Scheduled Tasks + +> Source: `src/content/cookbook/cron-jobs.mdx` +> Canonical URL: https://rivet.dev/cookbook/cron-jobs +> Description: Durable cron jobs with Rivet Actors: schedule.after and schedule.at timers survive restarts and crashes, plus re-arming recurring jobs and idempotent handlers. + +--- +Patterns for running durable cron jobs and scheduled tasks on Rivet Actors. Actor schedules are persistent timers owned by the engine, so a job keeps its deadline through actor sleep, restarts, upgrades, deploys, and crashes. + +## Starter Code + +Start from the working [Scheduling example on GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/scheduling). It implements a reminder service with one-shot timers, a React frontend, and live trigger events. + +## The Scheduling API + +The full API is documented in [Scheduling](/docs/actors/schedule). There are two methods, both available on the actor context: + +| Method | Behavior | +| --- | --- | +| `c.schedule.after(duration, actionName, ...args)` | Runs the named action after `duration` milliseconds. | +| `c.schedule.at(timestamp, actionName, ...args)` | Runs the named action at an exact epoch timestamp in milliseconds. | + +Key properties: + +- **Durable**: The schedule is persisted by the engine and the timer survives actor sleep, restart, upgrade, and crash. If the actor is asleep at the deadline, the engine wakes it to run the action. See [Lifecycle](/docs/actors/lifecycle). +- **Plain actions as callbacks**: The scheduled callback is an ordinary [action](/docs/actors/actions) on the same actor, invoked by name. Arguments after the action name are forwarded positionally, for example `c.schedule.after(delayMs, "triggerReminder", reminder.id)`. +- **No cancellation API**: Rivet does not currently support canceling a scheduled action. The pattern is a tombstone guard: remove the entry from [state](/docs/actors/state) and have the scheduled action no-op when it cannot find its entry. The example's `cancelReminder` and `triggerReminder` actions implement exactly this. + +## Recurring Jobs Via Re-Arm + +`c.schedule` is one-shot, so recurring jobs are built by having the scheduled action re-arm itself at the end of each run: + +```typescript +import { actor } from "rivetkit"; + +const DAY_MS = 24 * 60 * 60 * 1000; + +export const dailyReport = actor({ + state: { lastRunAt: 0 }, + actions: { + runReport: (c) => { + // Do the job's work, then record the run. + c.state.lastRunAt = Date.now(); + // Re-arm the next run before returning. + c.schedule.after(DAY_MS, "runReport"); + }, + }, +}); +``` + +Arm the first run from `onCreate` or a setup action; after that, the action keeps the chain alive by rescheduling itself. + +Re-arming with `after` measures the next run from the end of the current one, so the cadence drifts later by the job's runtime on every cycle. If runs must stay aligned to a fixed cadence, re-arm with `c.schedule.at(c.state.lastRunAt + DAY_MS, "runReport")` instead. + +The Scheduling example itself only uses one-shot reminders. A real re-arm implementation lives in the [idle world actor](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/idle/), where the `collectProduction` action credits production, updates `lastCollectedAt`, and calls a `scheduleCollection` helper that re-arms with `c.schedule.after(delayMs, "collectProduction", { buildingId })`. It also shows catch-up handling: if the action runs late, it computes how many whole intervals elapsed since the last run and credits them in one batch before re-arming. + +For multi-step jobs that need retries and progress tracking inside a single run, consider [Workflows](/docs/actors/workflows) instead of chaining schedules. + +## Durability Comparison + +| Approach | Timer Durability | Horizontal Scaling | Deploys And Restarts | +| --- | --- | --- | --- | +| `setTimeout` / `setInterval` | In-process memory only | Every replica arms its own timer, so jobs run once per instance | All pending timers are lost on restart or crash | +| `node-cron` and similar libraries | In-process memory only | Every instance runs the job unless you add external locking | Schedule resets on deploy; runs missed during downtime are skipped | +| External cron service | Lives outside your app | Needs a public HTTP endpoint plus its own dedupe and retry state | Survives your deploys but is separate infrastructure to operate | +| Rivet Actor scheduling | Persisted by the engine as a durable timer | Exactly one actor per key, so the timer is armed once rather than once per replica | Survives actor sleep, restart, upgrade, and crash | + +## Idempotency + +A scheduled action can fire more than you expect: a crash between doing the work and re-arming can cause the action to run again, and because schedules cannot be cancelled, an action can fire for an entry that was already removed. Design handlers so a duplicate firing is harmless: + +- **Store a run marker in state**: Keep a `lastRunAt` timestamp or a sequence number in actor state and update it inside the action. On each firing, compute elapsed time since the marker and skip or batch accordingly. The idle world actor's `collectProduction` does this with `lastCollectedAt` and whole-interval batching. +- **Tombstone guard for cancelled entries**: The example's `triggerReminder` looks the reminder up in `c.state.reminders` first and returns with a warning if it is gone, so a fire-after-cancel is a safe no-op. +- **Keep work and marker updates in the same action**: Actor state writes are persisted with the action, so updating the marker in the same handler that does the work keeps the two consistent. + +## Topology + +| Topology | Use When | Example Key | +| --- | --- | --- | +| Singleton job actor | One global job such as a nightly report or cleanup pass | `job["daily-report"]` | +| Actor per scheduled entity | Per-user or per-resource timers such as reminders, trials, or billing periods | `reminder[userId]` | + +The Scheduling example uses a single shared `reminderActor["main"]` key for demo simplicity. For production reminder systems, prefer one actor per user so timers, state, and load are isolated per entity. See [Keys](/docs/actors/keys). + +## Reminder Service Example + +| Topic | Summary | +| --- | --- | +| Scheduling | One-shot timers armed with `c.schedule.after(delayMs, "triggerReminder", reminder.id)` or `c.schedule.at(timestamp, "triggerReminder", reminder.id)`. | +| State | JSON state holding `reminders` and `completedCount`; the scheduled action mutates state when it fires. | +| Events | `triggerReminder` broadcasts a `reminderTriggered` event to all connected clients. See [Events](/docs/actors/events). | +| Cancellation | `cancelReminder` only removes the reminder from state; the scheduled action may still fire and no-ops via a state lookup guard. | + +**Actors** + +- **Key**: `reminderActor["main"]` +- **Responsibility**: Stores reminders in persistent state, arms a future self-action per reminder via `c.schedule`, marks reminders completed when the scheduled action fires, and broadcasts `reminderTriggered` to connected clients. +- **Actions** + - `scheduleReminder` + - `scheduleReminderAt` + - `triggerReminder` + - `getReminders` + - `cancelReminder` + - `getStats` +- **Queues** + - None +- **State** + - JSON + - `reminders` + - `completedCount` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant R as reminderActor + participant E as Engine + + C->>R: scheduleReminder(message, delayMs) + R->>E: schedule.after(delayMs, triggerReminder, id) + Note over E: schedule persisted + alarm armed + R-->>C: reminder + Note over R: actor sleeps + E->>R: alarm fires, actor wakes + Note over R: triggerReminder(id) runs + R-->>C: reminderTriggered event + Note over R: recurring jobs re-arm here with schedule.after +``` + +## Security Checklist + +The example is intentionally open: any client can connect to the shared `["main"]` key and schedule or cancel anything. Treat all of the following as required extensions for production: + +- **Validate schedule inputs**: Clamp `delayMs` and `timestamp` from clients. Reject negative delays, timestamps in the past, and absurdly far-future deadlines, and bound message or payload sizes. +- **Never schedule client-chosen actions**: Expose specific actions like `scheduleReminder` that internally arm a fixed callback. Do not pass a client-supplied action name or unchecked args into `c.schedule`. +- **Authenticate and scope keys**: Add connection [authentication](/docs/actors/authentication) and use per-user actor keys instead of one global key, so users cannot read or cancel each other's schedules. +- **Prune completed entries**: The example's `reminders` array grows without bound. Remove or archive completed entries so state stays small. +- **Use stable IDs**: Generate entry IDs with `crypto.randomUUID()` rather than timestamp-plus-random strings. + +_Source doc path: /cookbook/cron-jobs_ diff --git a/.agents/skills/ai-agent-workspace/reference/cookbook/live-cursors.md b/.agents/skills/ai-agent-workspace/reference/cookbook/live-cursors.md new file mode 100644 index 0000000..71c94ab --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/cookbook/live-cursors.md @@ -0,0 +1,152 @@ +# Live Cursors and Presence + +> Source: `src/content/cookbook/live-cursors.mdx` +> Canonical URL: https://rivet.dev/cookbook/live-cursors +> Description: Live cursors and multiplayer presence with Rivet Actors: per-connection cursor state, realtime updates over events or raw WebSockets, and throttling. + +--- +Patterns for building live cursors, multiplayer presence, and realtime cursor sharing with RivetKit. One room actor fans cursor positions out to every connected client, keyed per room with [actor keys](/docs/actors/keys). + +## Starter Code + +Start with one of the two working variants on GitHub. Both implement the same collaborative cursor canvas with persistent text labels; they differ only in transport. + +| Variant | Starter Code | Transport | Presence Storage | +| --- | --- | --- | --- | +| `cursors` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/cursors) | Typed [actions](/docs/actors/actions) and [events](/docs/actors/events) over the RivetKit connection | `connState` per connection | +| `cursors-raw-websocket` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/cursors-raw-websocket) | Raw [`onWebSocket` handler](/docs/actors/websocket-handler) with a custom JSON message protocol | Socket map in `createVars` | + +Use `cursors` by default: typed actions, typed events, and automatic connection tracking cover most apps with less code. Use `cursors-raw-websocket` when you need full control of the wire format, for example a custom JSON or binary protocol, or clients that do not use the RivetKit client library. + +## Connection State vs Persistent State + +Presence is ephemeral by definition. A cursor position is only meaningful while its connection is alive, so it belongs in per-connection storage, not in persistent actor state. Persistent state is reserved for data that must survive disconnects and actor restarts. + +| Data | Where It Lives | Why | +| --- | --- | --- | +| Cursor position | `connState` (`cursors`) or the `createVars` socket map (`cursors-raw-websocket`) | Scoped to one connection and discarded with it. Stale presence cannot accumulate in storage. | +| Text labels (`textLabels`) | Persistent actor `state` in both variants | Canvas content must survive disconnects and actor restarts. | + +In the `cursors` variant, `updateCursor` writes `c.conn.state.cursor` and `getRoomState` rebuilds the presence snapshot by iterating `c.conns.values()`, so the cursor map is always derived from live connections rather than stored. See [Connections](/docs/actors/connections) for `connState` and [State](/docs/actors/state) for persistence semantics. + +## Presence Lifecycle + +- **Join**: The `cursors-raw-websocket` variant pushes an `init` message with the current `{ cursors, textLabels }` snapshot as soon as a socket connects. The `cursors` variant has no explicit join broadcast; the client calls the `getRoomState` action once after connecting to seed its local maps, and peers first see a new user on that user's first `cursorMoved` broadcast. +- **Move**: Every `updateCursor` call writes the connection's presence entry, then broadcasts `cursorMoved` to all connections, including the sender. +- **Leave**: The `cursors` variant handles leave in `onDisconnect`, broadcasting `cursorRemoved` with the connection's last cursor. The raw variant does the same from the socket `close` listener, then deletes the session from the `vars.websockets` map. Clients delete that user from their local cursor map, so stale cursors disappear the moment a tab closes. + +See [Lifecycle](/docs/actors/lifecycle) for `onDisconnect` and `createVars`. + +## Update Throttling + +Neither example throttles. Both frontends send a cursor update on every raw `mousemove` event with no debounce or interval cap. That is fine for a demo, but a fast mouse on a high-refresh display can emit hundreds of events per second per user. The patterns below are recommended production hardening on top of the starter code, not something the examples implement. + +| Layer | Pattern | Guidance | +| --- | --- | --- | +| Client (smoothness) | Throttle to 20-30Hz | Sample the latest pointer position every 33-50ms and send only that. Drop intermediate moves, but always flush the final position so cursors settle at the true location. Interpolate between received positions on the rendering side. | +| Server (enforcement) | Per-connection rate limit | Track the last accepted update timestamp per connection and drop or coalesce updates arriving faster than your cap. Client throttles are cooperative; the actor is the enforcement boundary. | + +## Actors + +- **Key**: `cursorRoom[roomId]` (the frontend defaults `roomId` to `"general"`) +- **Responsibility**: Holds per-connection cursor presence in `connState`, persists shared text labels in actor state, and broadcasts cursor and text updates to all connections. +- **Actions** + - `updateCursor` + - `updateText` + - `removeText` + - `getRoomState` +- **Events** + - `cursorMoved` + - `cursorRemoved` + - `textUpdated` + - `textRemoved` +- **Queues** + - None +- **State** + - JSON + - `textLabels` (persistent) + - `connState.cursor` per connection (ephemeral) + +- **Key**: `cursorRoom[roomId]` (resolved via `client.cursorRoom.getOrCreate(roomId)`) +- **Responsibility**: Exposes a raw WebSocket endpoint, tracks live sockets and their cursors in a `createVars` map keyed by a `sessionId` query parameter, persists text labels, and manually fans JSON frames out to every socket. +- **Actions** + - `getOrCreate` (stub returning `{ status: "ok" }`; the frontend resolves the actor ID with the client handle's `getOrCreate(roomId).resolve()`, which creates the actor without dispatching this action) + - `getRoomState` +- **Queues** + - None +- **State** + - JSON + - `textLabels` (persistent) + - `vars.websockets` map of `sessionId` to socket and cursor (in-memory, lost on restart) + +The raw variant defines no RivetKit events. Its message names are `type` fields on raw JSON frames: + +| Direction | Message `type` | Payload | +| --- | --- | --- | +| Client to server | `updateCursor` | `{ userId, x, y }` | +| Client to server | `updateText` | `{ id, userId, text, x, y }` | +| Client to server | `removeText` | `{ id }` | +| Server to client | `init` | `{ cursors, textLabels }` snapshot on connect | +| Server to client | `cursorMoved`, `textUpdated`, `textRemoved`, `cursorRemoved` | The corresponding cursor, label, or ID payload | + +## Lifecycle + +### cursors (Actions + Events) + +```mermaid +sequenceDiagram + participant A as Client A + participant R as cursorRoom + participant B as Other Clients + + A->>R: connect via useActor (cursorRoom[roomId]) + A->>R: getRoomState() + R-->>A: {cursors, textLabels} + loop every mouse move + A->>R: updateCursor(userId, x, y) + Note over R: write c.conn.state.cursor + R-->>B: cursorMoved (broadcast) + end + A->>R: updateText(id, userId, text, x, y) + Note over R: upsert persistent state.textLabels + R-->>B: textUpdated (broadcast) + Note over A: tab closes + Note over R: onDisconnect reads conn.state.cursor + R-->>B: cursorRemoved (broadcast) +``` + +### cursors-raw-websocket + +```mermaid +sequenceDiagram + participant A as Client A + participant R as cursorRoom + participant B as Other Clients + + A->>R: getOrCreate(roomId).resolve() + R-->>A: actorId + A->>R: open WebSocket /gateway/{actorId}/websocket?sessionId=... + Note over R: close 1008 if sessionId is missing + Note over R: store socket in vars.websockets + R-->>A: init {cursors, textLabels} + loop every mouse move + A->>R: {type: "updateCursor"} frame + Note over R: update session cursor in vars + R-->>B: cursorMoved frame + end + Note over A: socket closes + R-->>B: cursorRemoved frame + Note over R: delete session from vars.websockets +``` + +## Security Checklist + +Both examples ship without authentication so the presence pattern stays readable. Everything below is recommended hardening for production, not behavior the examples implement. + +- **Identity**: Bind presence identity to the connection (`c.conn.id` in the actions variant, a server-generated session ID in the raw variant). Never trust a client-supplied `userId`; in the examples it is a random client-generated string, so any client can impersonate or remove any cursor. +- **Authorization**: Authorize label mutations by owner. In the examples, `updateText` accepts arbitrary `id` and `userId` arguments and `removeText` accepts an arbitrary `id`, so any client can edit or delete any label. +- **Input validation**: Clamp `x` and `y` to canvas bounds, cap text label length, and cap the total `textLabels` count so persistent state cannot grow unbounded. +- **Rate limiting**: Enforce a per-connection cap on `updateCursor` (for example 30Hz) and on label writes, as described in [Update Throttling](#update-throttling). +- **Protocol strictness (raw variant)**: Validate message shape before use and close the socket on malformed JSON instead of logging and continuing. Reject duplicate `sessionId` values rather than silently overwriting another session's socket entry. + +_Source doc path: /cookbook/live-cursors_ diff --git a/.agents/skills/ai-agent-workspace/reference/cookbook/multiplayer-game.md b/.agents/skills/ai-agent-workspace/reference/cookbook/multiplayer-game.md new file mode 100644 index 0000000..425b113 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/cookbook/multiplayer-game.md @@ -0,0 +1,713 @@ +# Multiplayer Game + +> Source: `src/content/cookbook/multiplayer-game.mdx` +> Canonical URL: https://rivet.dev/cookbook/multiplayer-game +> Description: Pragmatic patterns for building multiplayer games: matchmaking, tick loops, realtime state, interest management, and validation. + +--- +Patterns for building multiplayer games with RivetKit, intended as a practical checklist you can adapt per genre. + +## Starter Code + +Start with one of the working examples on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/) and adapt it to your game. Do not start from scratch for matchmaking and lifecycle flows. + +| Game Classification | Starter Code | Common Examples | +| --- | --- | --- | +| Battle Royale | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/battle-royale/) | Fortnite, Apex Legends, PUBG, Warzone | +| Arena | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/arena/) | Call of Duty TDM/FFA, Halo Slayer, Counter-Strike casual, VALORANT unrated, Overwatch Quick Play, Rocket League | +| IO Style | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/io-style/) | Agar.io, Slither.io, surviv.io | +| Open World | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/open-world/) | Minecraft survival servers, Rust-like worlds, MMO zone/chunk worlds | +| Party | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/party/) | Fall Guys private lobbies, custom game rooms, social party sessions | +| Physics 2D | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-2d/) | Top-down physics brawlers, 2D arena games, platform fighters | +| Physics 3D | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-3d/) | Physics sandbox sessions, 3D arena games, movement playgrounds | +| Ranked | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/ranked/) | Chess ladders, competitive card games, duel arena ranked queues | +| Turn-Based | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/turn-based/) | Chess correspondence, Words With Friends, async board games | +| Idle | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/idle/) | Cookie Clicker, Idle Miner Tycoon, Adventure Capitalist | + +## Server Simulation + +### Game Loop And Tick Rates + +| Pattern | Use When | Implementation Guidance | +| --- | --- | --- | +| Fixed realtime loop | Battle Royale, Arena, IO Style, Open World, Ranked | Run in `run` with `sleep(tickMs)` and exit on `c.aborted`. | +| Action-driven updates | Party, Turn-Based | Mutate and broadcast only on actions/events rather than scheduled ticks. | +| Coarse offline progression | Any mode with idle progression | Use `c.schedule.after(...)` with coarse windows (for example 5 to 15 minutes) and apply catch-up from elapsed wall clock time. | + +### Physics + +Start with custom kinematic logic for simple games. Switch to a full physics engine when you need joints, stacked bodies, high collision density, or complex shapes (rotated polygons, capsules, convex hulls, triangle meshes). + +Pick one engine per simulation. Keep frontend-only libs out of backend simulation paths and treat server state as authoritative. + +| Dimension | Primary Engine | Fallback Engines | Example Code | +| --- | --- | --- | --- | +| 2D | `@dimforge/rapier2d` | `planck-js`, `matter-js` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-2d/) | +| 3D | `@dimforge/rapier3d` | `cannon-es`, `ammo.js` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-3d/) | + +### Spatial Indexing + +For non-physics spatial queries, use a dedicated index instead of naive `O(n^2)` checks: + +| Index Type | Recommendation | +| --- | --- | +| AABB index | For AOI, visibility, and non-collider entities, use `rbush` for dynamic sets or `flatbush` for static-ish sets. | +| Point index | For nearest-neighbor or within-radius queries, use `d3-quadtree`. | + +## Networking & State Sync + +### Netcode + +| Model | When To Use | Implementation | +| --- | --- | --- | +| Hybrid (client movement, server combat) | Shooters, action sports, ranked duels | Client owns movement and sends capped-rate position updates. Server validates for anti-cheat. Combat (projectiles, hits, damage) is fully server-authoritative. | +| Server-authoritative with interpolation | IO Style, persistent worlds | Client sends input commands. Server simulates on fixed ticks and publishes authoritative snapshots. Client interpolates between snapshots. | +| Server-authoritative (basic logic) | Turn-based, event-driven | Server validates and applies discrete actions (turns, phase transitions, votes). Client displays confirmed state. | + +### Realtime Data Model + +- **Snapshots and diffs**: Publish state as events. Send a full snapshot on join/resync, then per-tick diffs for regular updates. +- **Batch per tick**: Keep events small and typed. Batch high-frequency updates per tick. +- **Avoid UI framework state for game updates**: Use `requestAnimationFrame` or a Canvas/Three.js loop for simulation, not React state. Reserve UI framework state for menus, HUD, and forms. +- **Broadcast vs per-connection**: Use `c.broadcast(...)` for shared updates and `conn.send(...)` for private/per-player data. + +### Shared Simulation Logic + +Shared simulation logic runs on both the client and the server. For example, an `applyInput(state, input, dt)` function that integrates velocity and clamps to world bounds can run on the client for prediction and on the server for validation. + +- **Hybrid modes**: Client runs shared movement as primary authority, server runs it for anti-cheat validation. +- **Server-authoritative modes**: Client uses shared logic for interpolation and prediction only. +- **Keep it pure**: Movement integration, input transforms, collision helpers, and constants only. +- **Put shared code in `src/shared/`**: Keep deterministic helpers in `src/shared/sim/*` with no side effects. + +### Interest Management + +Control what each client receives to reduce bandwidth and prevent information leaks. + +#### Per-Player Replication Filters + +- **Filter by relevance**: Send each client only state relevant to that player (proximity, line-of-sight, team, or game phase). +- **Shooters and action games**: Limit replication by proximity and optional field-of-view checks. +- **Server-side only**: Clients should never receive data they should not see. + +#### Sharded Worlds + +- **Partition large worlds**: Use chunk actors keyed by `worldId:chunkX:chunkY`. +- **Subscribe to nearby chunks**: Clients connect only to nearby partitions (for example a 3x3 chunk window). +- **Use sparingly**: Only when the world is large and state-heavy (sandbox builders, MMOs), not as a default for small matches. + +## Backend Infrastructure + +### Persistence + +- **In-memory state**: Best for realtime game state that changes every tick (player positions, inputs, match phase, scores). +- **SQLite (`rivetkit/db`)**: Better for large or table-like state that needs queries, indexes, or long-term persistence (tiles, inventory, matchmaking pools). Serialize DB work through a queue since multiple actions can hit the same actor concurrently. + +### Matchmaking Patterns + +Common building blocks used across the architecture patterns below. + +#### Actor Topology + +| Primitive | Use When | Typical Ownership | +| --- | --- | --- | +| `matchmaker["main"]` + `match[matchId]` | Session-based multiplayer (battle royale, arena, ranked, party, turn-based) | Matchmaker owns discovery/assignment. Match owns lifecycle and gameplay state. | +| `chunk[worldId,chunkX,chunkY]` | Large continuous worlds that need sharding | Each chunk owns local players, chunk state, and local simulation. | +| `world[playerId]` | Per-player progression loops (idle/solo world state) | Per-player resources, buildings, timers, and progression. | +| `player[username]` | Canonical profile/rating reused across matches | Durable player stats (for example rating and win/loss). | +| `leaderboard["main"]` | Shared rankings across many matches/players | Global ordered score rows and top lists. | + +#### Queueing Strategy + +- Multiple players can hit the matchmaker at the same time, so actions like find/create, queue/unqueue, and close need to be serialized through actor queues to avoid races. +- Match-local actions (gameplay, scoring) do not need queueing unless they write back to the matchmaker. + +## Security And Anti-Cheat + +Start with this baseline, then harden further for competitive or high-risk environments. + +### Baseline Checklist + +- **Identity**: Use `c.conn.id` as the authoritative transport identity. Treat `playerId`/`username` in params as untrusted input and bind through server-issued assignment/join tickets. +- **Authorization**: Validate the caller is allowed to mutate the target entity (room membership, turn ownership, host-only actions). +- **Input validation**: Clamp sizes/lengths, validate enums, and validate usernames (length, allowed chars, avoid unbounded Unicode). +- **Rate limiting**: Per-connection rate limits for spammy actions (chat, join/leave, fire, movement updates). +- **State integrity**: Server recomputes derived state (scores, win conditions, placements). Never allow client-authoritative changes to inventory/currency/leaderboard totals. + +### Movement Validation + +For any mode with client-authoritative movement (hybrid flows), clients may send position/rotation updates for smoothness, but the server must: + +- Enforce max delta per update (speed cap) based on elapsed time. +- Reject or clamp teleports. +- Enforce world bounds (and basic collision if applicable). +- Rate limit update frequency (for example 20Hz max). + +## Architecture Patterns + +Each game type below starts with a quick summary table, then details actors and lifecycle. + +### Battle Royale + +| Topic | Summary | +| --- | --- | +| Matchmaking | Immediate routing to the fullest non-started lobby (oldest tie-break); players wait in lobby until capacity, then the match starts. | +| Netcode | Hybrid. Client owns movement, camera, and local prediction. Server owns zone state, projectiles, hit resolution, eliminations, loot, and final placement. | +| Tick Rate | 10 ticks/sec (`100ms`) with a fixed loop for zone progression and lifecycle checks. | +| Physics | Client owns movement with server anti-cheat validation; projectiles, hits, and damage are server-authoritative. Use `@dimforge/rapier3d` for 3D or `@dimforge/rapier2d` for top-down 2D. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Finds or creates lobbies, tracks pending reservations, and maintains occupancy. +- **Actions** + - `findMatch` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **Queues** + - `findMatch` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **State** + - SQLite + - `matches` + - `pending_players` + - `player_count` includes connected and pending players + +- **Key**: `match[matchId]` +- **Responsibility**: Runs lobby/live/finished phases, owns player state, zone progression, and eliminations. +- **Actions** + - `connect` + - Movement and combat actions +- **Queues** + - None +- **State** + - JSON + - `phase` + - `players` + - `zone` + - `eliminations` + - `snapshot data` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant M as match + + C->>MM: findMatch() + alt no open lobby + MM->>M: create(matchId) + end + MM-->>C: {matchId, playerId} + C->>M: connect(playerId) + M->>MM: pendingPlayerConnected(matchId, playerId) + MM-->>M: accepted + Note over M: lobby countdown -> live + M-->>C: snapshot + shoot events + M->>MM: closeMatch(matchId) +``` + +### Arena + +| Topic | Summary | +| --- | --- | +| Matchmaking | Mode-based fixed-capacity queues (`duo`, `squad`, `ffa`) that build only full matches and pre-assign teams (except FFA). | +| Netcode | Hybrid. Client owns movement plus prediction and smoothing. Server owns team or FFA assignment, projectiles, hit resolution, phase transitions, and scoring. | +| Tick Rate | 20 ticks/sec (`50ms`) with a tighter loop for live team and FFA snapshots. | +| Physics | Medium to high intensity; client movement with server validation and server-authoritative combat/entities. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Runs mode queues, builds full matches, assigns teams, and publishes assignments. +- **Actions** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **Queues** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **State** + - SQLite + - `player_pool` + - `matches` + - `assignments` keyed by connection and player + +- **Key**: `match[matchId]` +- **Responsibility**: Runs match phases and in-match player/team state for score and win conditions. +- **Actions** + - `connect` + - Gameplay actions +- **Queues** + - None +- **State** + - JSON + - `phase` + - `players` + - `team assignments` + - `score and win state` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant M as match + + C->>MM: queueForMatch(mode) + Note over MM: enqueue in player_pool + Note over MM: fill when capacity reached + MM->>M: create(matchId, assignments) + Note over MM: persist assignments + MM-->>C: assignmentReady + C->>M: connect(playerId) + Note over M: waiting -> live when all players connect + M->>MM: matchCompleted(matchId) +``` + +### IO Style + +| Topic | Summary | +| --- | --- | +| Matchmaking | Open-lobby routing to the fullest room below capacity; room counts are heartbeated and new lobbies are auto-created when needed. | +| Netcode | Server-authoritative with interpolation. Client sends input intents and interpolates. Server owns movement, bounds, room membership, and canonical snapshots. | +| Tick Rate | 10 ticks/sec (`100ms`) with lightweight periodic room snapshots. | +| Physics | Low to medium intensity; server-authoritative kinematic movement, escalating to a physics engine only when collisions get complex. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Routes players into the fullest open lobby and tracks reservations and occupancy. +- **Actions** + - `findLobby` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **Queues** + - `findLobby` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **State** + - SQLite + - `matches` + - `pending_players` + - Occupancy includes pending reservations + +- **Key**: `match[matchId]` +- **Responsibility**: Runs per-match movement simulation and broadcasts snapshots. +- **Actions** + - `connect` + - `setInput` +- **Queues** + - None +- **State** + - JSON + - `players` + - `inputs` + - `movement state` + - `snapshot cache` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant M as match + + C->>MM: findLobby() + alt no open lobby + MM->>M: create(matchId) + end + MM-->>C: {matchId, playerId} + C->>M: connect(playerId) + M->>MM: pendingPlayerConnected(matchId, playerId) + MM-->>M: accepted + Note over M: fixed tick simulation + M-->>C: snapshot events + M->>MM: closeMatch(matchId) +``` + +### Open World + +| Topic | Summary | +| --- | --- | +| Matchmaking | Client-driven chunk routing from world coordinates, with nearby chunk windows preloaded via adjacent chunk connections. | +| Netcode | Hybrid for sandbox (client movement with validation) or server-authoritative for MMO-like flows. Server owns chunk routing, persistence, and canonical world state. | +| Tick Rate | 10 ticks/sec per chunk actor (`100ms`), so load scales with active chunks. | +| Physics | Medium to high at scale; chunk-local simulation can be server-authoritative (MMO-like) or client movement with server validation (sandbox-like). | + +**Actors** + +- **Key**: `chunk[worldId,chunkX,chunkY]` +- **Responsibility**: Owns chunk-local players, blocks, movement tick, and chunk membership. +- **Actions** + - `connect` + - `enterChunk` + - `addPlayer` + - `setInput` + - `leaveChunk` + - `removePlayer` +- **Queues** + - None +- **State** + - JSON + - `connections` + - `players` + - `blocks` scoped to one chunk key + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant CH as chunk + + Note over C: resolve chunk keys from world position + loop each visible chunk + C->>CH: connect(worldId, chunkX, chunkY, playerId) + Note over CH: store connection metadata + end + C->>CH: enterChunk/addPlayer + loop movement updates + C->>CH: setInput(...) + CH-->>C: snapshot + end + C->>CH: leaveChunk/removePlayer or disconnect + Note over CH: remove membership and metadata +``` + +### Party + +| Topic | Summary | +| --- | --- | +| Matchmaking | Host-created private party flow using party codes and explicit joins. | +| Netcode | Server-authoritative (basic logic). Server owns membership, host permissions, and phase transitions. | +| Tick Rate | No continuous tick; updates are event-driven (`join`, `start`, `finish`). | +| Physics | Low intensity for lobby-first flows; usually no dedicated physics or indexing unless you add realtime mini-games. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Handles party create/join flow, validates join tickets, and tracks party size. +- **Actions** + - `createParty` + - `joinParty` + - `verifyJoin` + - `updatePartySize` + - `closeParty` +- **Queues** + - `createParty` + - `joinParty` + - `verifyJoin` + - `updatePartySize` + - `closeParty` +- **State** + - SQLite + - `parties` + - `join_tickets` for party lookup and join validation + +- **Key**: `match[matchId]` +- **Responsibility**: Owns party members, host role, ready flags, and phase transitions. +- **Actions** + - `connect` + - `startGame` + - `finishGame` +- **Queues** + - None +- **State** + - JSON + - `members` + - `host` + - `ready state` + - `phase` + - `party events` + +**Lifecycle** + +### Host Flow + +```mermaid +sequenceDiagram + participant H as Host Client + participant MM as matchmaker + participant M as match + + H->>MM: createParty() + MM-->>H: {matchId, partyCode, playerId, joinToken} + H->>M: connect(playerId, joinToken) + M->>MM: verifyJoin(...) + MM-->>M: allowed + M->>MM: updatePartySize(playerCount) + H->>M: startGame() / finishGame() + M->>MM: closeParty(matchId) +``` + +### Joiner Flow + +```mermaid +sequenceDiagram + participant J as Joiner Client + participant MM as matchmaker + participant M as match + + J->>MM: joinParty(partyCode) + MM-->>J: {matchId, playerId, joinToken} + J->>M: connect(playerId, joinToken) + M->>MM: verifyJoin(...) + MM-->>M: allowed / denied + M->>MM: updatePartySize(playerCount) +``` + +### Ranked + +| Topic | Summary | +| --- | --- | +| Matchmaking | ELO-based queue pairing with a widening search window as wait time increases. | +| Netcode | Hybrid. Client owns movement with local prediction and interpolation. Server owns projectiles, hit resolution, match results, and rating updates. | +| Tick Rate | 20 ticks/sec (`50ms`) with fixed live ticks for deterministic pacing and broadcast cadence. | +| Physics | Medium to high intensity; client movement with server validation and server-authoritative combat/hit resolution. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Runs rating-based queueing, pairing, assignment persistence, and completion fanout. +- **Actions** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **Queues** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **State** + - SQLite + - `player_pool` + - `matches` + - `assignments` with rating window and connection scoping + +- **Key**: `match[matchId]` +- **Responsibility**: Runs ranked match phase, score, and winner reporting. +- **Actions** + - `connect` + - Gameplay actions +- **Queues** + - None +- **State** + - JSON + - `phase` + - `players` + - `score` + - `winner` + - `completion payload` + +- **Key**: `player[username]` +- **Responsibility**: Stores canonical player MMR and win/loss profile. +- **Actions** + - `initialize` + - `getRating` + - `applyMatchResult` +- **Queues** + - None +- **State** + - JSON + - `rating` + - `wins` + - `losses` + - `match counters` + +- **Key**: `leaderboard["main"]` +- **Responsibility**: Stores and serves top-ranked players. +- **Actions** + - `updatePlayer` +- **Queues** + - None +- **State** + - SQLite + - Leaderboard score rows + - Top-list ordering + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant P as player + participant M as match + participant LB as leaderboard + + C->>MM: queueForMatch(username) + MM->>P: initialize/getRating + P-->>MM: rating + Note over MM: store queue row + retry pairing + MM->>M: create(matchId, assigned players) + MM-->>C: assignmentReady + C->>M: connect(username) + M->>MM: matchCompleted(...) + MM->>P: applyMatchResult(...) + MM->>LB: updatePlayer(...) + Note over MM: remove matches + assignments rows +``` + +### Turn-Based + +| Topic | Summary | +| --- | --- | +| Matchmaking | Async private-invite and public-queue pairing in the same pattern. | +| Netcode | Server-authoritative (basic logic). Client can draft moves before submit. Server owns turn ownership, committed move log, turn order, and completion state. | +| Tick Rate | No continuous tick; move submission and turn transitions drive updates. | +| Physics | Very low intensity; no realtime physics loop, just discrete rules validation. Indexing is optional and mostly for board or query convenience at scale. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Handles private invite and public queue pairing for async matches. +- **Actions** + - `createGame` + - `joinByCode` + - `queueForMatch` + - `unqueueForMatch` + - `closeMatch` +- **Queues** + - `createGame` + - `joinByCode` + - `queueForMatch` + - `unqueueForMatch` + - `closeMatch` +- **State** + - SQLite + - `matches` + - `player_pool` + - `assignments` for invite and queue mapping + +- **Key**: `match[matchId]` +- **Responsibility**: Owns board state, turn order, move validation, and final result. +- **Actions** + - `connect` + - `makeMove` +- **Queues** + - None +- **State** + - JSON + - `board` + - `turns` + - `players` + - `connection presence` + - `result` + +**Lifecycle** + +### Public Queue + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant MM as matchmaker + participant M as match + + A->>MM: queueForMatch() + B->>MM: queueForMatch() + Note over MM: pair first two queued players + MM->>M: create(matchId) + seed X/O players + MM-->>A: assignment/match info + MM-->>B: assignment/match info + A->>M: connect(playerId) + B->>M: connect(playerId) + A->>M: makeMove() + B->>M: makeMove() + opt all players disconnected for timeout + Note over M: destroy after idle timeout + end + M->>MM: closeMatch(matchId) +``` + +### Private Invite + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant MM as matchmaker + participant M as match + + A->>MM: createGame() + MM-->>A: {matchId, playerId, inviteCode} + B->>MM: joinByCode(inviteCode) + MM->>M: create(matchId) + seed X/O players + MM-->>A: assignment/match info + MM-->>B: assignment/match info + A->>M: connect(playerId) + B->>M: connect(playerId) + A->>M: makeMove() + B->>M: makeMove() + M->>MM: closeMatch(matchId) +``` + +### Idle + +| Topic | Summary | +| --- | --- | +| Matchmaking | No matchmaker; each player uses a direct per-player actor and a shared leaderboard actor. | +| Netcode | Server-authoritative (basic logic). Client owns UI and build intent. Server owns resources, production rates, building validation, and leaderboard totals. | +| Tick Rate | No continuous tick; use `c.schedule.after(...)` for coarse intervals and compute offline catch-up from elapsed wall time. | +| Physics | None for standard idle loops; transitions are discrete (`build`, `collect`, `upgrade`) and do not need spatial indexing. | + +**Actors** + +- **Key**: `world[playerId]` +- **Responsibility**: Owns one player's progression, buildings, production scheduling, and state updates. +- **Actions** + - `initialize` + - `build` + - `collectProduction` +- **Queues** + - None +- **State** + - JSON + - Per-player buildings + - `resources` + - `timers` + - `progression state` + +- **Key**: `leaderboard["main"]` +- **Responsibility**: Stores global scores and serves leaderboard updates. +- **Actions** + - `updateScore` +- **Queues** + - `updateScore` +- **State** + - SQLite + - `scores` table keyed by player + - Current leaderboard totals + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant W as world + participant LB as leaderboard + + C->>W: getOrCreate(playerId) + initialize() + Note over W: seed state + schedule collection + W-->>C: stateUpdate + loop gameplay loop + C->>W: build() / collectProduction() + W->>LB: updateScore(...) + Note over LB: upsert scores + LB-->>C: leaderboardUpdate + W-->>C: stateUpdate + end +``` + +_Source doc path: /cookbook/multiplayer-game_ diff --git a/.agents/skills/ai-agent-workspace/reference/cookbook/per-tenant-database.md b/.agents/skills/ai-agent-workspace/reference/cookbook/per-tenant-database.md new file mode 100644 index 0000000..e3c5616 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/cookbook/per-tenant-database.md @@ -0,0 +1,119 @@ +# Database per Tenant + +> Source: `src/content/cookbook/per-tenant-database.mdx` +> Canonical URL: https://rivet.dev/cookbook/per-tenant-database +> Description: Multi-tenant data isolation with one Rivet Actor per tenant: the actor key is the tenant id, so each tenant gets its own isolated dataset and migrations. + +--- +Patterns for database-per-tenant architectures with RivetKit. Instead of one shared database with a `tenant_id` column on every table, each tenant gets its own Rivet Actor, and that actor owns the tenant's entire dataset. + +## Starter Code + +Start with the working example on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/per-tenant-database) and adapt it. The example stores each tenant's dataset in JSON actor state and serves a React dashboard with live event updates. + +| Topic | Summary | +| --- | --- | +| Isolation | One `companyDatabase` actor per tenant, keyed by company name. Switching tenants swaps the entire dataset. | +| State | JSON actor state holding `employees` and `projects` arrays plus timestamps. No SQLite, no queues, no scheduling. | +| Realtime | Every write action mutates state, then broadcasts a typed event (`employeeAdded`, `projectAdded`) to all connected clients of that tenant. | +| Auth | None. The sign-in screen is cosmetic. Production guidance is in the [security checklist](#security-checklist). | + +## The Isolation Model + +The actor key is the tenant id. The client connects with `useActor({ name: "companyDatabase", key: [companyName] })` and the actor reads `c.key[0]` in `createState` to seed that tenant's dataset. This gives you: + +- **One actor per tenant**: `companyDatabase[tenantId]` addresses exactly one actor instance. Two tenants can never share an actor. +- **One dataset per tenant**: All reads and writes go through that actor's [state](/docs/actors/state), so there is no shared table with a `tenant_id` column to filter incorrectly. Cross-tenant leaks require constructing the wrong key, not forgetting a `WHERE` clause. +- **No key injection**: Keys are arrays, not interpolated strings. `key: [tenantId]` cannot be escaped the way `"tenant:" + tenantId` string concatenation can. See [Keys](/docs/actors/keys). + +The example's test ([tests/per-tenant-database.test.ts](https://github.com/rivet-dev/rivet/tree/main/examples/per-tenant-database/tests/per-tenant-database.test.ts)) proves the isolation: data written to `companyDatabase["Alpha Co"]` never appears in `companyDatabase["Beta Co"]`. + +## Choosing a State Backend + +The example uses plain JSON actor state. The same key-equals-tenant model works with any actor state backend. + +| Backend | Use When | Docs | Working Code | +| --- | --- | --- | --- | +| JSON actor state | Small datasets, simple reads, whole dataset fits comfortably in memory. What the example uses. | [State](/docs/actors/state) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/per-tenant-database) | +| Actor SQLite (`rivetkit/db`) | Tables, indexes, SQL queries, larger-than-memory data, per-tenant relational schema. | [SQLite](/docs/actors/sqlite) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/kitchen-sink/src/actors/state/sqlite-raw.ts) | +| SQLite + Drizzle | Typed schema, query builder, and generated migration files on top of actor SQLite. | [SQLite + Drizzle](/docs/actors/sqlite-drizzle) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/kitchen-sink/src/actors/state/sqlite-drizzle/) | + +With either SQLite option, every tenant gets its own embedded SQLite database, since the database is scoped to the actor and the actor is scoped to the tenant. + +## Migrations + +The per-tenant example has no migrations because JSON state has no schema. When you adopt SQLite, migrations run per tenant database: + +- **Raw SQL**: `db({ onMigrate })` runs your migration SQL inside a SQLite savepoint before the actor serves traffic. If `onMigrate` throws, all migration SQL rolls back atomically and the actor does not start. See [SQLite](/docs/actors/sqlite). +- **Drizzle**: `drizzle-kit` generates migration files from your typed schema, and `db({ schema, migrations })` applies them when the actor wakes. See [SQLite + Drizzle](/docs/actors/sqlite-drizzle). + +Because each tenant has its own database, migrations roll out per actor as each tenant's actor wakes, rather than as one large migration against a shared database. + +## Tenant Id Must Come From Auth + +The example's sign-in is cosmetic: the client picks any company string and that string becomes the actor key, so any visitor can read and write any tenant's data. Do not ship this. As a required production extension (not implemented by the example): + +- Derive the tenant id from a verified credential, such as a JWT claim, never from user input. +- Validate the credential against `c.key` in `onBeforeConnect` (pass/fail) or `createConnState` (store the verified user on connection state). See [Authentication](/docs/actors/authentication) and [Connections](/docs/actors/connections). +- Add per-action permission checks on top of connection-level auth. See [Access Control](/docs/actors/access-control). + +## Actors + +- **Key**: `companyDatabase[companyName]` (single-element array key; `c.key[0]` is the company name) +- **Responsibility**: One actor per tenant. Holds that company's employees and projects in persistent state, serves reads and writes via actions, and broadcasts mutations to connected clients. +- **Actions** + - `addEmployee` + - `listEmployees` + - `addProject` + - `listProjects` + - `getStats` +- **Queues** + - None +- **Events** + - `employeeAdded` + - `projectAdded` +- **State** + - JSON + - `company_name` + - `employees` + - `projects` + - `created_at` + - `updated_at` + +Every write action follows the same mutate-then-broadcast shape: push the record into `c.state`, bump `updated_at`, broadcast the typed event, return the record. See [Actions](/docs/actors/actions) and [Events](/docs/actors/events). + +## Lifecycle + +```mermaid +sequenceDiagram + participant A as Tenant A client + participant DA as companyDatabase A + participant B as Tenant B client + participant DB as companyDatabase B + + Note over A: authenticate and derive tenant id + A->>DA: connect with key [tenantA] + Note over DA: createState seeds company_name, employees, projects + A->>DA: listEmployees() + listProjects() + getStats() + A->>DA: addEmployee(name, role) + DA-->>A: employeeAdded event + B->>DB: connect with key [tenantB] + Note over DB: separate actor, separate dataset + B->>DB: listEmployees() + DB-->>B: tenant B data only +``` + +In the example, the "authenticate" step is a free-text company picker. The rest of the flow matches the diagram: `createState` seeds the dataset on first creation, the dashboard loads with `listEmployees`, `listProjects`, and `getStats`, and every connected client of the same tenant receives `employeeAdded` and `projectAdded` events. + +## Security Checklist + +The example ships with none of these. Apply all of them before production. + +- **Tenant identity**: Derive the tenant id from a verified JWT claim, never from a client-supplied string. +- **Connection validation**: In `onBeforeConnect` or `createConnState`, verify the credential's tenant claim matches `c.key` and reject mismatches. +- **Per-action authorization**: Check the caller's role before mutating actions (`addEmployee`, `addProject`), not just at connect time. See [Access Control](/docs/actors/access-control). +- **Input validation**: Clamp name and role lengths and validate enums. The example only trims input and substitutes fallback defaults. +- **Key construction**: Always pass the tenant id as an array element (`key: [tenantId]`). Never interpolate tenant ids into key strings, and never build keys from one tenant's input to address another tenant's actor. +- **Growth limits**: As a recommended extension, cap or paginate the `employees` and `projects` arrays. The example lets them grow unboundedly in JSON state; move to [SQLite](/docs/actors/sqlite) when the dataset outgrows memory. + +_Source doc path: /cookbook/per-tenant-database_ diff --git a/.agents/skills/ai-agent-workspace/reference/cookbook/vpc-air-gapped.md b/.agents/skills/ai-agent-workspace/reference/cookbook/vpc-air-gapped.md new file mode 100644 index 0000000..f7d87a3 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/cookbook/vpc-air-gapped.md @@ -0,0 +1,136 @@ +# Deploying Rivet in a VPC or Air-Gapped Network + +> Source: `src/content/cookbook/vpc-air-gapped.mdx` +> Canonical URL: https://rivet.dev/cookbook/vpc-air-gapped +> Description: Run Rivet entirely inside your own perimeter: single-binary or Docker Compose install, file system storage with no database infrastructure, and no outbound telemetry by default. + +--- +Patterns for running self-hosted Rivet inside a private network: a VPC without internet egress, an on-premises rack, or a fully air-gapped environment. The engine is one service, the recommended single-node storage backend is the local file system, and the engine makes no outbound connections by default. Self-hosting is the only Rivet deployment model that supports air-gapped networks; see the [Self-Hosting Overview](/docs/self-hosting) for the full comparison with BYOC. + +## What Runs Inside the Perimeter + +A self-hosted deployment has three components, all of which live inside your network: + +| Component | Role | Inside the perimeter | +| --- | --- | --- | +| Your backend | Your application server, including the runner that executes actor code | Yes | +| Rivet Engine | Orchestration service that manages actor lifecycle, routes messages, and serves the dashboard and APIs | Yes | +| Storage | Persistence for actor state. Local file system for single-node, PostgreSQL or FoundationDB for multi-node | Yes | + +There is no license server, no Rivet Cloud account, and no callback to `rivet.dev`. Clients inside the perimeter reach actors through the engine's gateway over your private network. See [Architecture](/docs/self-hosting#architecture). + +## Single-Binary Install + +The engine compiles to a single `rivet-engine` binary. Build it from source outside the perimeter, then copy the binary across the boundary: + +```bash +git clone https://github.com/rivet-dev/rivet.git +cd rivet +cargo build --release -p rivet-engine +# Copy target/release/rivet-engine into the perimeter. +``` + +Prebuilt binaries are coming soon; see [Installing Rivet Engine](/docs/self-hosting/install) for current options. + +Run it with the file system backend, which stores everything on local disk and is the production-ready choice for single-node deployments. The [File System](/docs/self-hosting/filesystem) docs list air-gapped environments as a primary use case because it needs no database infrastructure: + +```bash +RIVET__database__file_system__path="/var/lib/rivet/data" ./rivet-engine +``` + +Configuration can also come from files. The engine discovers config at `/etc/rivet/config.json` on Linux (JSON, JSON5, JSONC, YAML, and YML are all supported), and `--config` overrides the path. Environment variables use the `RIVET__` prefix with `__` as the separator. See [Configuration](/docs/self-hosting/configuration). + +The engine serves its own dashboard on port `6420`, so inspection and namespace management work with nothing but a browser inside the perimeter. + +## Docker Compose Deployment + +For Docker hosts without registry access, move the engine image across the boundary the standard way: + +```bash +# Outside the perimeter. +docker pull rivetdev/engine:latest +docker save rivetdev/engine:latest -o rivet-engine.tar +# Inside the perimeter. +docker load -i rivet-engine.tar +``` + +Then run the engine and your app together in one Compose file: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - rivet-data:/data + environment: + RIVET__FILE_SYSTEM__PATH: "/data" + restart: unless-stopped + + my-app: + build: . + environment: + RIVET_ENDPOINT: "http://default:admin@rivet-engine:6420" + depends_on: + - rivet-engine + restart: unless-stopped + +volumes: + rivet-data: +``` + +`RIVET_ENDPOINT` uses the format `http://namespace:token@host:port` and tells your app to connect to the engine as a runner instead of running standalone. After both services start, register your runner with the engine through the dashboard or its API. The full walkthrough, including PostgreSQL setup for multi-node deployments, is in [Docker Compose](/docs/self-hosting/docker-compose). + +## No Outbound Telemetry + +The engine exports traces and metrics only when you opt in with OpenTelemetry. Export is disabled unless `RIVET_OTEL_ENABLED=1` is set, and the export target defaults to a local collector at `http://localhost:4317`. With no configuration, nothing crosses the perimeter. + +When you want observability, keep it inside the network: + +- Set `RIVET_OTEL_ENABLED=1` and point `RIVET_OTEL_GRPC_ENDPOINT` at a collector you run inside the perimeter. +- Adjust `RIVET_OTEL_SAMPLER_RATIO` to control trace sampling. +- Use the engine's health endpoint for liveness and readiness probes. + +See the [Production Checklist](/docs/self-hosting/production-checklist) for monitoring guidance. + +## Embedding Rivet in a Customer's Environment + +If you ship software that runs inside your customers' VPCs, the same setup turns Rivet into an internal component of your product rather than a service your customers must reach over the internet: + +- **Ship the engine next to your app.** Add `rivetdev/engine` to the Compose file or chart you already deliver. Your app finds it over the private network via `RIVET_ENDPOINT`, so one artifact deploys the whole stack. +- **One namespace per install.** The endpoint URL carries the namespace and token (`http://namespace:token@host:port`), so a single image works across customer deployments. See [Endpoints](/docs/general/endpoints). +- **Generate a strong admin token per install.** Replace the default token and keep it server-side. Never include the admin token in `RIVET_PUBLIC_ENDPOINT` or anywhere clients can read it. +- **Public endpoint only when needed.** `RIVET_PUBLIC_ENDPOINT` with a public (`pk_`) token is only required when browser clients connect to actors in [serverless runtime mode](/docs/general/runtime-modes). Backend-only deployments can skip it entirely. +- **TLS at the customer's edge.** Terminate TLS with the customer's reverse proxy or load balancer in front of the engine. + +## Scaling Past One Node + +| Backend | Use when | Status | +| --- | --- | --- | +| [File System](/docs/self-hosting/filesystem) (RocksDB-based) | Single-node deployments, including air-gapped installs | Production-ready, single node only | +| [PostgreSQL](/docs/self-hosting/postgres) | Multi-node deployments | Recommended for multi-node today, but experimental | +| FoundationDB | Largest production deployments | [Enterprise](/sales) | + +For multi-node deployments, run two or more engine nodes behind a load balancer and add NATS for pub/sub, which replaces the default PostgreSQL `LISTEN`/`NOTIFY` path at high throughput. Neither is needed for a single-node file system install. See the [Production Checklist](/docs/self-hosting/production-checklist). + +## Perimeter Checklist + +- **Admin token**: Generate a strong, random token for engine authentication and verify it is not exposed to clients. +- **TLS termination**: Encrypt connections to the engine via a reverse proxy or load balancer. +- **No public exposure**: Keep port `6420` reachable only from inside the perimeter unless clients outside it genuinely need access. +- **Health checks**: Configure liveness and readiness probes against the engine health endpoint. +- **Telemetry**: Leave OpenTelemetry export off, or point it at a collector inside the network. +- **Backups**: With the file system backend, back up the data directory. With PostgreSQL, configure automated backups and failover. + +## Full Configuration + +- [Self-Hosting Overview](/docs/self-hosting) for architecture and the self-host vs BYOC comparison +- [Installing Rivet Engine](/docs/self-hosting/install) for Docker, binary, and source installs +- [Docker Container](/docs/self-hosting/docker-container) and [Docker Compose](/docs/self-hosting/docker-compose) for container deployments +- [Kubernetes](/docs/self-hosting/kubernetes) for cluster deployments +- [Configuration](/docs/self-hosting/configuration) for every option and the full JSON schema +- [Endpoints](/docs/general/endpoints) for connecting your backend and clients +- [Production Checklist](/docs/self-hosting/production-checklist) before going live + +_Source doc path: /cookbook/vpc-air-gapped_ diff --git a/.agents/skills/ai-agent-workspace/reference/deploy/aws-ecs.md b/.agents/skills/ai-agent-workspace/reference/deploy/aws-ecs.md new file mode 100644 index 0000000..ab381ce --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/deploy/aws-ecs.md @@ -0,0 +1,13 @@ +# Deploying to AWS ECS + +> Source: `src/content/docs/deploy/aws-ecs.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/aws-ecs +> Description: Run your backend on Amazon ECS with Fargate. + +--- +See the [AWS ECS template](https://github.com/rivet-dev/template-aws-ecs) for deployment instructions: + +- [Deploy with Terraform](https://github.com/rivet-dev/template-aws-ecs#option-a-deploy-with-terraform) +- [Deploy with AWS CLI](https://github.com/rivet-dev/template-aws-ecs#option-b-deploy-with-aws-cli) + +_Source doc path: /docs/deploy/aws-ecs_ diff --git a/.agents/skills/ai-agent-workspace/reference/deploy/aws-lambda.md b/.agents/skills/ai-agent-workspace/reference/deploy/aws-lambda.md new file mode 100644 index 0000000..f1327cc --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/deploy/aws-lambda.md @@ -0,0 +1,10 @@ +# Deploy To Amazon Web Services Lambda + +> Source: `src/content/docs/deploy/aws-lambda.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/aws-lambda +> Description: _AWS Lambda is coming soon_ + +--- + + +_Source doc path: /docs/deploy/aws-lambda_ diff --git a/.agents/skills/ai-agent-workspace/reference/deploy/cloudflare.md b/.agents/skills/ai-agent-workspace/reference/deploy/cloudflare.md new file mode 100644 index 0000000..970078e --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/deploy/cloudflare.md @@ -0,0 +1,53 @@ +# Deploying to Cloudflare Workers + +> Source: `src/content/docs/deploy/cloudflare.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/cloudflare +> Description: Deploy an existing Rivet project to Cloudflare Workers. + +--- +This guide covers deploying an existing Rivet project to Cloudflare Workers. + +## Prerequisites + +- [Cloudflare account](https://dash.cloudflare.com/) +- [`wrangler`](https://developers.cloudflare.com/workers/wrangler/) configured for your account +- A Rivet namespace from the [Rivet Dashboard](https://dashboard.rivet.dev/) or a self-hosted Rivet Engine + +## Steps + +### Set up your project + +Follow the [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) to set up your project locally. + +### Configure Wrangler + +Set your Rivet connection values as Worker variables. Find `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` in the [Rivet Dashboard](https://dashboard.rivet.dev/) under **Settings → Namespace → Advanced → Backend Configuration** and copy them in. + +```toml wrangler.toml +name = "rivetkit-cloudflare" +main = "src/index.ts" +compatibility_date = "2025-04-01" +compatibility_flags = ["nodejs_compat"] + +[vars] +RIVET_ENDPOINT = "https://your-namespace:sk_...@api.rivet.dev" +RIVET_PUBLIC_ENDPOINT = "https://your-namespace@api.rivet.dev" +``` + +### Deploy + +```sh +npx wrangler deploy +``` + +### Register the Serverless Runner URL + +After deploy, set the Worker URL with the `/api/rivet` path as the serverless runner URL in Rivet. + +## Related + +- [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) +- [Deploying to Supabase Functions](/docs/deploy/supabase) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/deploy/cloudflare_ diff --git a/.agents/skills/ai-agent-workspace/reference/deploy/freestyle.md b/.agents/skills/ai-agent-workspace/reference/deploy/freestyle.md new file mode 100644 index 0000000..eb6ed57 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/deploy/freestyle.md @@ -0,0 +1,136 @@ +# Deploying to Freestyle + +> Source: `src/content/docs/deploy/freestyle.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/freestyle +> Description: Deploy RivetKit app to Freestyle.sh, a cloud platform for running AI-generated code with built-in security and scalability. + +--- +Freestyle provides built-in security for running untrusted AI-generated code, making it ideal for AI agent applications. Using Rivet, it is easy to deploy your vibe-coded or user-provided RivetKit backends straight to Freestyle. + +- [Freestyle + Rivet](https://github.com/rivet-dev/rivet/tree/main/examples/freestyle) — Complete example of deploying RivetKit app to Freestyle.sh. + +## Setup + +### Install packages + +Install RivetKit and Hono and create your registry: + +```bash +npm install rivetkit hono +``` + +### Configure serverless driver + +Update your server code to run the registry serverless with Deno. + +```typescript index.ts @hide +import { actor, setup } from "rivetkit"; + +export const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, x: number) => { + c.state.count += x; + return c.state.count; + }, + }, +}); + +export const registry = setup({ + use: { counter }, +}); +registry.start(); +``` + +```typescript server.ts @nocheck +import { registry } from "./index"; + +// Freestyle uses Deno under the hood for web deployments +// @ts-ignore Deno is a Freestyle runtime global +Deno.serve((request: Request) => registry.handler(request)); +``` + +The `Deno.serve` API is provided by Freestyle's runtime environment. The `@ts-ignore` comment suppresses TypeScript errors for this platform-specific API. + +### Deploy to Freestyle + +Deploy your application to Freestyle with the correct configuration. Create a deployment script or add this to your existing deployment process: + +```typescript @nocheck +const FREESTYLE_DOMAIN = "my-domain.style.dev"; // Change to your desired Freestyle domain + +declare const freestyle: any; +declare const buildDir: string; + +const res = await freestyle.deployWeb(buildDir, { + envVars: { + FREESTYLE_ENDPOINT: `https://${FREESTYLE_DOMAIN}`, + RIVET_RUNNER_KIND: "serverless", + // For self-hosted instances: + // RIVET_ENDPOINT: "http://127.0.0.1:6420", + RIVET_ENDPOINT: "api.rivet.dev", + }, + timeout: 60 * 5, // Increases max request lifetime on the runner + entrypoint: "server.ts", // File which starts serverless runner + domains: [FREESTYLE_DOMAIN], + build: false, +}); +``` + +Details on `buildDir` and other settings are available on [Freestyle docs](https://docs.freestyle.sh/web/web). + +Run this deployment script to push your application to Freestyle. + +**Deployment Configuration:** + +- `timeout: 60 * 5` - Set timeout to 5 minutes for actor operations - it's important to keep this high +- `entrypoint: "server.ts"` - Entry point file with your serverless setup +- `domains` - Your Freestyle domain(s) +- `build: false` - Disable build if you're pre-building your assets + +### Configure runner + +Update the runner configuration on the Rivet side to connect with your Freestyle deployment. Create a configuration script and run it after your Freestyle deployment is live: + +```typescript @nocheck +import { RivetClient } from "@rivetkit/engine-api-full"; + +const rivet = new RivetClient({ + environment: "https://api.rivet.dev", + token: process.env.RIVET_API_TOKEN, +}); + +const FREESTYLE_DOMAIN = "my-domain.style.dev"; // Change to your desired Freestyle domain +const RIVET_NAMESPACE = "my-rivet-namespace"; // Change to your Rivet namespace + +await rivet.runnerConfigsUpsert("freestyle-runner", { + namespace: RIVET_NAMESPACE, + datacenters: { + default: { + serverless: { + url: `https://${FREESTYLE_DOMAIN}/start`, + runnersMargin: 1, + minRunners: 1, + maxRunners: 1, + slotsPerRunner: 1, + // Must be shorter than Freestyle request `timeout` config + requestLifespan: 60 * 5 - 5, + }, + }, + }, +}); +``` + +Execute this configuration script to register your Freestyle deployment with Rivet. + +**Runner Configuration:** + +- `url` - Freestyle deployment URL with `/start` endpoint +- `runnersMargin` - Buffer of runners to maintain +- `minRunners/maxRunners` - Scaling limits +- `slotsPerRunner` - Concurrent actors per runner +- `requestLifespan` - Request timeout (slightly less than Freestyle timeout) + +Once executed, Rivet will be connected to your Freestyle serverless instance. + +_Source doc path: /docs/deploy/freestyle_ diff --git a/.agents/skills/ai-agent-workspace/reference/deploy/gcp-cloud-run.md b/.agents/skills/ai-agent-workspace/reference/deploy/gcp-cloud-run.md new file mode 100644 index 0000000..f140950 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/deploy/gcp-cloud-run.md @@ -0,0 +1,74 @@ +# Deploying to Google Cloud Run + +> Source: `src/content/docs/deploy/gcp-cloud-run.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/gcp-cloud-run +> Description: Deploy your RivetKit app to Google Cloud Run. + +--- +## Steps + +### Prerequisites + +- Google Cloud project with Cloud Run and Artifact Registry enabled +- `gcloud` CLI authenticated (`gcloud auth login`) and project set (`gcloud config set project YOUR_PROJECT`) +- Artifact Registry repository or Container Registry enabled +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Package Your App + +Create a `Dockerfile` in your project root: + +```dockerfile +FROM node:20-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev +COPY . . +ENV PORT=8080 +CMD ["node", "server.js"] +``` + +### Build and Push the Image + +Use Cloud Build to build and push the image. Replace the region and repository with your own. + +```bash +gcloud builds submit --tag us-central1-docker.pkg.dev/YOUR_PROJECT/rivetkit-app/rivetkit-app:latest +``` + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select Google Cloud Run as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables to use when deploying. + +### Deploy to Cloud Run + +Deploy the service to Cloud Run, passing the Rivet environment variables. Adjust the region and image as needed. + +```bash +gcloud run deploy rivetkit-app \ + --image us-central1-docker.pkg.dev/YOUR_PROJECT/rivetkit-app/rivetkit-app:latest \ + --region us-central1 \ + --allow-unauthenticated \ + --min-instances 1 \ + --set-env-vars RIVET_ENDPOINT=,RIVET_PUBLIC_ENDPOINT= +``` + +### Connect to Rivet + +1. After deployment, note the service URL (e.g. `https://rivetkit-app-xxxxx-uc.a.run.app`) +2. On the Rivet dashboard, paste your URL with the `/api/rivet` path into the connect form (e.g. `https://rivetkit-app-xxxxx-uc.a.run.app/api/rivet`) +3. Click "Done" + +### Verify + +Confirm the service is running: + +```bash +gcloud run services describe rivetkit-app --region us-central1 --format 'value(status.conditions[?type="Ready"].status)' +``` + +Your app should appear as connected on the Rivet dashboard once the service reports ready. + +_Source doc path: /docs/deploy/gcp-cloud-run_ diff --git a/.agents/skills/ai-agent-workspace/reference/deploy/hetzner.md b/.agents/skills/ai-agent-workspace/reference/deploy/hetzner.md new file mode 100644 index 0000000..5b61024 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/deploy/hetzner.md @@ -0,0 +1,10 @@ +# Deploying to Hetzner + +> Source: `src/content/docs/deploy/hetzner.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/hetzner +> Description: Please see the VM & Bare Metal guide. + +--- + + +_Source doc path: /docs/deploy/hetzner_ diff --git a/.agents/skills/ai-agent-workspace/reference/deploy/kubernetes.md b/.agents/skills/ai-agent-workspace/reference/deploy/kubernetes.md new file mode 100644 index 0000000..43496a9 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/deploy/kubernetes.md @@ -0,0 +1,121 @@ +# Deploying to Kubernetes + +> Source: `src/content/docs/deploy/kubernetes.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/kubernetes +> Description: Deploy your RivetKit app to any Kubernetes cluster. + +--- +## Steps + +### Prerequisites + +- A Kubernetes cluster with `kubectl` access (EKS, GKE, k3s, etc.) +- Container registry credentials (Docker Hub, GHCR, GCR, etc.) +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Package Your App + +Create a `Dockerfile` in your project root: + +```dockerfile +FROM node:20-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev +COPY . . +ENV PORT=8080 +CMD ["node", "server.js"] +``` + +### Build and Push the Image + +```bash +docker build -t registry.example.com/your-team/rivetkit-app:latest . +docker push registry.example.com/your-team/rivetkit-app:latest +``` + +Replace `registry.example.com/your-team` with your registry path. Auth with `docker login` first if needed. + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select Kubernetes as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables. + +Create a `rivetkit-secrets.yaml` for your environment variables: + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: rivetkit-secrets +type: Opaque +stringData: + RIVET_ENDPOINT: + RIVET_PUBLIC_ENDPOINT: +``` + +### Deploy to Kubernetes + +Create a `deployment.yaml`: + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: rivetkit-app +spec: + replicas: 1 + selector: + matchLabels: + app: rivetkit-app + template: + metadata: + labels: + app: rivetkit-app + spec: + # Allow enough time for actors to gracefully stop on SIGTERM. + # The runner waits up to 30m for actors to finish. + # Add buffer for runner shutdown overhead after actors stop. + # See: /docs/actors/versions#graceful-shutdown-sigterm + terminationGracePeriodSeconds: 2100 + containers: + - name: rivetkit-app + image: registry.example.com/your-team/rivetkit-app:latest + envFrom: + - secretRef: + name: rivetkit-secrets +``` + +Apply both manifests: + +```bash +kubectl apply -f rivetkit-secrets.yaml +kubectl apply -f deployment.yaml +``` + +### Connect to Rivet + +1. Add a `Service` and Ingress to expose your app externally (e.g. `my-app.example.com`) +2. On the Rivet dashboard, paste your domain with the `/api/rivet` path into the connect form (e.g. `https://my-app.example.com/api/rivet`) +3. Click "Done" + +Rivet envoys connect to your app over long-lived WebSockets, and your app's clients (browsers, SDKs) do the same. Default Ingress and cloud load balancer idle timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +Raise the idle / read / send timeout on every Ingress and load balancer in front of your app to at least 1 hour (`3600` seconds). Examples: + +- **NGINX Ingress**: `nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"` and `nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"` +- **AWS Load Balancer Controller (ALB)**: `alb.ingress.kubernetes.io/load-balancer-attributes: idle_timeout.timeout_seconds=3600` +- **GCE Ingress (GKE)**: set `timeoutSec: 3600` on the `BackendConfig` referenced by the Service. + +### Verify + +Check that the pod is running: + +```bash +kubectl get pods -l app=rivetkit-app +``` + +Your app should appear as connected on the Rivet dashboard once the pod is ready. + +_Source doc path: /docs/deploy/kubernetes_ diff --git a/.agents/skills/ai-agent-workspace/reference/deploy/railway.md b/.agents/skills/ai-agent-workspace/reference/deploy/railway.md new file mode 100644 index 0000000..640ac37 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/deploy/railway.md @@ -0,0 +1,45 @@ +# Deploying to Railway + +> Source: `src/content/docs/deploy/railway.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/railway +> Description: Deploy your RivetKit app to Railway. + +--- +## Steps + +### Prerequisites + +- [Railway account](https://railway.app) +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Deploy to Railway + +1. Connect your GitHub account to Railway +2. Select your repository containing your RivetKit app +3. Railway will automatically detect and deploy your app + +See [Railway's deployment docs](https://docs.railway.com/quick-start) for more details. + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select Railway as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables to add to your Railway service. + +See [Railway's environment variables docs](https://docs.railway.com/guides/variables#service-variables) for more details. + +### Connect to Rivet + +1. In your Railway project, go to **Settings > Networking** +2. Click **Create Custom Domain** then **Create Domain** to generate a Railway domain (e.g. `my-app.railway.app`) +3. On the Rivet dashboard, paste your domain with the `/api/rivet` path into the connect form (e.g. `https://my-app.railway.app/api/rivet`) +4. Click "Done" + +Rivet envoys connect to your app over long-lived WebSockets, and your app's clients (browsers, SDKs) do the same. Railway's HTTP proxy supports WebSockets, but if you front your app with your own reverse proxy (NGINX, Caddy, etc.) inside the Railway service, raise its idle / read timeout to at least 1 hour (`3600` seconds). Default proxy timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +### Configure Sleeping & Multi-Region (Optional) + +- [Enable App Sleeping](https://docs.railway.com/reference/app-sleeping) to reduce costs when idle +- [Configure Multi-Region](https://docs.railway.com/reference/deployment-regions) to deploy closer to your users + +_Source doc path: /docs/deploy/railway_ diff --git a/.agents/skills/ai-agent-workspace/reference/deploy/rivet-compute.md b/.agents/skills/ai-agent-workspace/reference/deploy/rivet-compute.md new file mode 100644 index 0000000..75884d7 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/deploy/rivet-compute.md @@ -0,0 +1,106 @@ +# Deploying to Rivet Compute + +> Source: `src/content/docs/deploy/rivet-compute.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/rivet-compute +> Description: Run your backend on Rivet Compute. + +--- +Rivet Compute is currently in beta. + +Using an AI coding agent? Open **Connect** on the [Rivet dashboard](https://dashboard.rivet.dev), select **Rivet Cloud**, and paste the one-shot prompt into your agent and have it connect with Rivet Compute for you. + +## Steps + +### Prerequisites + +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- A [Rivet Cloud](https://dashboard.rivet.dev) account and project +- Docker running locally + +### Create a Dockerfile + +Add a `Dockerfile` to your project root that builds and runs your RivetKit server: + +```dockerfile @nocheck +FROM node:24-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev +COPY . . +CMD ["node", "src/server.js"] +``` + +### Get Your Cloud Token + +1. Open the [Rivet dashboard](https://dashboard.rivet.dev) and navigate to your project +2. Click **Connect** and select **Rivet Cloud** +3. Copy the **`RIVET_CLOUD_TOKEN`** value shown + +### Deploy + +Run the deploy command from your project root. The token is saved to `~/.rivet/credentials`, so later deploys can omit it. + +```bash +npx @rivetkit/cli deploy --token cloud_api_xxxxx +``` + +The CLI resolves your project from the token, builds and pushes your Docker image to Rivet's built-in registry, upserts the managed pool, and prints the deployment URL on stdout when the pool is ready. + +### Optionally Add CI + +After local deploys work, install the GitHub Actions workflow that deploys on every push and pull request: + +```bash +npx @rivetkit/cli setup-ci +``` + +This writes `.github/workflows/rivet-deploy.yml`. Add your token as a repository secret to enable it: + +```bash +gh secret set RIVET_CLOUD_TOKEN +``` + +The workflow creates production and pull-request namespaces, posts preview links, and cleans up PR namespaces when pull requests close. See the [CLI reference](/docs/cli) for all commands. + +### Monitor Deployment + +The dashboard shows live status as Rivet Compute provisions your backend: + +| Status | Description | +| --- | --- | +| Provisioning | Allocating compute resources | +| Initializing | Starting the runtime environment | +| Allocating | Assigning the runner to your pool | +| Deploying | Pulling and launching your container | +| Binding | Connecting the runner to the network | +| Ready | Deployment complete | + +Once the status reaches **Ready**, your backend is live and actors are available for connections. + +If you are an agent monitoring the deployment via API rather than the dashboard, poll the managed-pool endpoint on the Cloud API. + +The `RIVET_CLOUD_TOKEN` secret is a `cloud_api_*` management token scoped to the Cloud API at `cloud-api.rivet.dev`. Use it for `Authorization: Bearer ...` against the Cloud API. Do not confuse it with a `pk_*` publishable key, which is scoped to the Rivet Engine API at `api.rivet.dev` and will 401 against this endpoint. + +Substitute `$CLOUD_API_URL` (typically `https://cloud-api.rivet.dev`), `$PROJECT`, `$ORG`, `$CLOUD_NAMESPACE`, and `$CLOUD_TOKEN`. + +Poll every 5 seconds until `status` is `ready`. Stop and investigate if `status` is `error`. + +```bash +curl -s "$CLOUD_API_URL/projects/$PROJECT/namespaces/$CLOUD_NAMESPACE/managed-pools/default?org=$ORG" -H "Authorization: Bearer $CLOUD_TOKEN" +``` + +## Troubleshooting + +If the status stays in **Provisioning** for more than a few minutes, verify that: + +- The `RIVET_CLOUD_TOKEN` secret is correctly set in your GitHub repository +- The GitHub Actions workflow completed without errors — check the run logs + +If the status shows **Error**, check that your container starts successfully and does not exit immediately. Common causes: + +- The server file is not calling `registry.startRunner()` +- A runtime crash on startup — test the image locally with `docker run` +- The Dockerfile is not listening on the `PORT` environmental variable + +_Source doc path: /docs/deploy/rivet-compute_ diff --git a/.agents/skills/ai-agent-workspace/reference/deploy/supabase.md b/.agents/skills/ai-agent-workspace/reference/deploy/supabase.md new file mode 100644 index 0000000..93f1b4d --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/deploy/supabase.md @@ -0,0 +1,48 @@ +# Deploying to Supabase Functions + +> Source: `src/content/docs/deploy/supabase.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/supabase +> Description: Deploy an existing Rivet project to Supabase Edge Functions. + +--- +This guide covers deploying an existing Rivet project to Supabase Edge Functions. + +## Prerequisites + +- [Supabase project](https://supabase.com/) +- [Supabase CLI](https://supabase.com/docs/guides/cli) configured for your project +- A Rivet namespace from the [Rivet Dashboard](https://dashboard.rivet.dev/) or a self-hosted Rivet Engine + +## Steps + +### Set up your project + +Follow the [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) to set up your project locally. + +### Set Secrets + +Set your Rivet connection values as Supabase secrets. Find `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` in the [Rivet Dashboard](https://dashboard.rivet.dev/) under **Settings → Namespace → Advanced → Backend Configuration** and copy them in. + +```sh +npx supabase secrets set \ + RIVET_ENDPOINT=https://your-namespace:sk_...@api.rivet.dev \ + RIVET_PUBLIC_ENDPOINT=https://your-namespace@api.rivet.dev +``` + +### Deploy + +```sh +npx supabase functions deploy rivet +``` + +### Register the Serverless Runner URL + +After deploy, set the function URL with the `/api/rivet` path as the serverless runner URL in Rivet. For a function named `rivet`, this is usually `https://your-project.functions.supabase.co/functions/v1/rivet/api/rivet`. + +## Related + +- [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) +- [Deploying to Cloudflare Workers](/docs/deploy/cloudflare) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/deploy/supabase_ diff --git a/.agents/skills/ai-agent-workspace/reference/deploy/vercel.md b/.agents/skills/ai-agent-workspace/reference/deploy/vercel.md new file mode 100644 index 0000000..e8b5ba3 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/deploy/vercel.md @@ -0,0 +1,138 @@ +# Deploying to Vercel + +> Source: `src/content/docs/deploy/vercel.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/vercel +> Description: Deploy your Next.js Rivet app to Vercel. + +--- +This guide assumes a Next.js app. + +## Prerequisites + +- [Vercel account](https://vercel.com/) +- A Next.js Rivet app +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +## Steps + +### Set up your project + +Follow the [Next.js Quickstart](/docs/actors/quickstart/next-js) to set up your project. + +### Verify Your Project Structure + +Your Next.js project should have the following structure: + +- `src/app/api/rivet/[...all]/route.ts`: RivetKit route handler +- `src/rivet/registry.ts`: Actor definitions and registry + +The route handler sets `maxDuration` to extend the serverless function timeout so long-lived actor requests are not cut short: + +```ts src/app/api/rivet/[...all]/route.ts @nocheck +import { toNextHandler } from "@rivetkit/next-js"; +import { registry } from "@/rivet/registry"; + +export const maxDuration = 300; + +export const { GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS } = toNextHandler(registry); +``` + +### Set Environment Variables + +Set `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` in your Vercel project settings using the URL auth format: + +``` +RIVET_ENDPOINT=https://my-namespace:sk_****@api.rivet.dev +RIVET_PUBLIC_ENDPOINT=https://my-namespace:pk_****@api.rivet.dev +``` + +`RIVET_ENDPOINT` uses the secret token for server-side access. `RIVET_PUBLIC_ENDPOINT` uses the publishable token and tells the metadata endpoint what connection info to provide to clients. + +### Deploy to Vercel + +1. Connect your GitHub repository to Vercel +2. Vercel will deploy your app + +### Configure Preview Deployments (Recommended) + +Add a GitHub action to automatically create isolated Rivet namespaces for each PR: + +1. Add these secrets to your GitHub repository: + - `RIVET_CLOUD_TOKEN`: Get from [Rivet Dashboard](https://dashboard.rivet.dev) → Settings → Advanced → Cloud API Tokens + - `VERCEL_TOKEN`: Get from [Vercel Account Settings](https://vercel.com/account/tokens) + +2. Create `.github/workflows/rivet-preview.yml`: + +```yaml +name: Rivet Preview + +on: + pull_request: + types: [opened, synchronize, reopened] + push: + branches: [main] + +concurrency: + group: rivet-preview-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + rivet-preview: + runs-on: ubuntu-latest + permissions: + pull-requests: write + steps: + - uses: rivet-dev/preview-namespace-action@v1 + with: + platform: vercel + rivet-token: ${{ secrets.RIVET_CLOUD_TOKEN }} + vercel-token: ${{ secrets.VERCEL_TOKEN }} +``` + +## Troubleshooting + +``` +Error: ENOENT: no such file or directory, mkdir '.../rivetkit/.../state' +``` + +**Cause:** The `RIVET_ENDPOINT` environment variable is not configured. RivetKit falls back to the file system driver, which fails in Vercel's read-only serverless environment. + +**Solution:** Ensure `RIVET_ENDPOINT` is set with your Rivet endpoint using the URL auth format: + +``` +RIVET_ENDPOINT=https://my-namespace:sk_****@api.rivet.dev +``` + +If using the [preview-namespace-action](https://github.com/rivet-dev/preview-namespace-action), this is configured automatically. + +The `/api/rivet/metadata` endpoint returns data but `clientEndpoint`, `clientNamespace`, and `clientToken` are missing. + +**Cause:** The `RIVET_PUBLIC_ENDPOINT` environment variable is not configured. This tells the metadata endpoint what connection info to provide to clients. + +**Solution:** Set `RIVET_PUBLIC_ENDPOINT` with the publishable token (for client access): + +``` +RIVET_PUBLIC_ENDPOINT=https://my-namespace:pk_****@api.rivet.dev +``` + +If using the [preview-namespace-action](https://github.com/rivet-dev/preview-namespace-action), this is configured automatically. + +Rivet fails to connect to your Vercel deployment with a 401 error mentioning "Authentication Required". + +**Cause:** [Vercel Deployment Protection](https://vercel.com/docs/security/deployment-protection) is blocking requests from Rivet. + +**Solution:** + +1. Create a bypass secret in your Vercel project settings +2. In Rivet, go to **Settings > Providers** +3. Click the three dots on your provider and select **Edit** +4. Click **Add Header** and add `x-vercel-protection-bypass` with your bypass secret + +If using the [preview-namespace-action](https://github.com/rivet-dev/preview-namespace-action), this is configured automatically. + +## Related + +- [Next.js Quickstart](/docs/actors/quickstart/next-js) +- [Self-Hosting](/docs/general/self-hosting) + +_Source doc path: /docs/deploy/vercel_ diff --git a/.agents/skills/ai-agent-workspace/reference/deploy/vm-and-bare-metal.md b/.agents/skills/ai-agent-workspace/reference/deploy/vm-and-bare-metal.md new file mode 100644 index 0000000..6a123f9 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/deploy/vm-and-bare-metal.md @@ -0,0 +1,96 @@ +# Deploying to VMs & Bare Metal + +> Source: `src/content/docs/deploy/vm-and-bare-metal.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/vm-and-bare-metal +> Description: Deploy your RivetKit app to any Linux VM or bare metal host. + +--- +## Steps + +### Prerequisites + +- A Linux VM or bare metal server with SSH access +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Upload Your App + +- Build your RivetKit app locally +- Copy the build output to your server (example): + +```bash +scp -r ./dist user@server:/opt/rivetkit-app +``` + +Place the files somewhere readable by the service user, such as `/opt/rivetkit-app`. + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select VM & Bare Metal as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables to use in the next step. + +### Create the systemd Service + +Create `/etc/systemd/system/rivetkit-app.service`: + +```ini +[Unit] +Description=RivetKit App +After=network.target + +[Service] +Type=simple +WorkingDirectory=/opt/rivetkit-app +ExecStart=/usr/bin/node server.js +Restart=on-failure +Environment=RIVET_ENDPOINT= +Environment=RIVET_PUBLIC_ENDPOINT= + +[Install] +WantedBy=multi-user.target +``` + +Replace the environment values with those from the Rivet dashboard and adjust paths to match your deployment. + +### Start the Service + +Reload systemd units and start the service: + +```bash +sudo systemctl daemon-reload +sudo systemctl enable --now rivetkit-app.service +``` + +### Connect to Rivet + +1. Ensure your server is accessible via a public URL (e.g. `https://my-app.example.com`) +2. On the Rivet dashboard, paste your URL with the `/api/rivet` path into the connect form (e.g. `https://my-app.example.com/api/rivet`) +3. Click "Done" + +If you front your app with a reverse proxy or load balancer (NGINX, HAProxy, Caddy, AWS ALB/NLB, etc.), raise its idle / read timeout to at least 1 hour (`3600` seconds). Rivet envoys connect to your app over long-lived WebSockets, and clients (browsers, SDKs) do the same. Default proxy timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +Examples: + +- **NGINX**: `proxy_read_timeout 3600s;` and `proxy_send_timeout 3600s;` in the relevant `location` block. +- **HAProxy**: `timeout client 1h` and `timeout server 1h` in the matching frontend / backend. +- **AWS ALB / NLB**: set the load balancer attribute `idle_timeout.timeout_seconds = 3600`. + +## Operating + +### Restart + +Restart the service after deploying new builds or environment changes: + +```bash +sudo systemctl restart rivetkit-app.service +``` + +### Logs + +Follow realtime logs when debugging: + +```bash +sudo journalctl -u rivetkit-app.service -f +``` + +_Source doc path: /docs/deploy/vm-and-bare-metal_ diff --git a/.agents/skills/ai-agent-workspace/reference/general/actor-configuration.md b/.agents/skills/ai-agent-workspace/reference/general/actor-configuration.md new file mode 100644 index 0000000..37339a2 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/general/actor-configuration.md @@ -0,0 +1,41 @@ +# Actor Configuration + +> Source: `src/content/docs/general/actor-configuration.mdx` +> Canonical URL: https://rivet.dev/docs/general/actor-configuration +> Description: This page documents the configuration options available when defining a RivetKit actor. The actor configuration is passed to the `actor()` function. + +--- +## Basic Example + +```typescript +import { actor, setup } from "rivetkit"; + +const myActor = actor({ + state: { count: 0 }, + + actions: { + increment: (c) => { + c.state.count++; + return c.state.count; + }, + }, + options: { + actionTimeout: 15_000, + } +}); + +const registry = setup({ + use: { myActor }, +}); +``` + +## Configuration Reference + +## Related + +- [Registry Configuration](/docs/general/registry-configuration): Configure the RivetKit registry +- [State](/docs/actors/state): Managing actor state +- [Actions](/docs/actors/actions): Defining actor actions +- [Lifecycle](/docs/actors/lifecycle): Actor lifecycle hooks + +_Source doc path: /docs/general/actor-configuration_ diff --git a/.agents/skills/ai-agent-workspace/reference/general/architecture.md b/.agents/skills/ai-agent-workspace/reference/general/architecture.md new file mode 100644 index 0000000..a4c731a --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/general/architecture.md @@ -0,0 +1,452 @@ +# Architecture + +> Source: `src/content/docs/general/architecture.mdx` +> Canonical URL: https://rivet.dev/docs/general/architecture +> Description: - rivetkit is the typescript library used for both local development & to connect your application to rivet - a rivetkit instance is called a "runner." you can run multiple runners to scale rivetkit horiziotnally. read omre about runners below. + +--- +## 3 ways of running + +### rivetkit + +- rivetkit is the typescript library used for both local development & to connect your application to rivet +- a rivetkit instance is called a "runner." you can run multiple runners to scale rivetkit horiziotnally. read omre about runners below. + +#### local development + +- in local development, rivetkit provides a full actor environment for single-node deployments + +#### drivers + +- rivetkit supports multiple drivers. currently supports: file system (default in local dev), memory, rivet engine (used for rivet cloud & self-hosting), cloudflare durable objects (does not rely on rivet engine) +- drivers are very flexible to enable you to write your actors once and plug in to any system that fits your architecture adequately +- see the driver interface + - actordriver https://github.com/rivet-dev/rivet/blob/eeb01fc4d9ca0e06f2e740d267bd53280ca7330e/rivetkit-typescript/packages/rivetkit/src/actor/driver.ts + - managerdriver https://github.com/rivet-dev/rivet/blob/eeb01fc4d9ca0e06f2e740d267bd53280ca7330e/rivetkit-typescript/packages/rivetkit/src/manager/driver.ts + +### rivet cloud + +- provides multi-region and highest performance out of the box +- accessible at dashboard.rivet.dev and the api is avialble at api.rivet.dev + +### rivet self-hosted + +- available as a standalone rust binary or a docker contianer +- can be configured ot persist to postgres or rocksdb +- can scale horiziontally across multipe nodes and can scale across multiple regions +- see [self-hosting docs](/docs/self-hosting/) + +## actors + +- Actors for long-lived processes with durable state, realtime, and hibernate when not in use. read more about actors at a high level at (link to actors/index) + +### actor-per-entity + +- actors are designed to have an actor-per-entity +- you can think about actors a bit like objects in object-oriented programming where ach is responsible for their own state and expose methods (ie actions in our case) +- examples incldue + - actor per user + - actor per user session + - actor per document + - actor per game room + - actor per tenant + - actor per rate limit topic + +### architecting for scale + +- actors scale by: + - having isolated state to each acotr that combines compute and storage for in-memory reads and writes + - communication is stndardized based on actions & events + - scale horizontally +- read more about scalign at (link to scaling doc) + +### horizontal scaling + +- actors can run across multiple rivetkit runners. this is orchestrated by rivetkit itself. + +### lifecycle + +actors have create, destroy, wake, and sleep lifecycle hooks that you can implement to modify behavior. see the lifecycle docs for reference on actor lifecycel hook sequences + +### actor sleeping + +- actors sleep when not in use +- an actor is considered not in use when there are no active network connections to the actor (or the network connections are hibernatable websockets, see below) and there are no actions in flight +- actors have a sleep timeout (configured in `options.sleepTimeout`) that decides how long to keep the actor in memory with no recent activity +- sleep can be held off for the lifetime of a promise with `c.keepAwake(promise)` +- see the [sleeping docs](/docs/actors/lifecycle#sleeping) for full details + +### wake events + +- actors can wake to any of the follwoing events: + - network requests + - websocket messages + - alarms (see scheduling docs) + +### live actor migration + +- live actor migrations lets your application ugprade, crash, or hot reload cahnges without interruption to your user or application (including websockets) +- this is powered by hibernating websockets for live websocket migraiton & our fault tolerance mechanism (read more below) + +### coldstart performance + +- actors have negligible coldstart performance. the code to run the actor is already started (ie the runner), so creating/starting an actor is incredibly cheap. +- creating new actors with a key requires some overhead to communicate with other regions in order to reserve the actor's key (see below). actors can be created without keys with near-0 latency. + +### multi-region, globally unique actor keys + +- acotrs can optionally have a globally unique "key" +- when creating an actor with a key +- this system is highly optimized to reduce wan round trips using per-key Paxos with a custom database called Epoxy (https://github.com/rivet-dev/rivet/tree/main/engine/packages/epoxy) +- limitation: when creating an actor with a given key, that key will always be pinned to that region even if the actor is destroyed. creating a new actor with the same key will always live in the same region. +- see the acotr keys document + +### input + +- actors have input data that can be passed to them when constructed +- this is similar to apssing data to a constructor in an object + +### generic parameters + +actor definitions include the following generic parameters that you'll see frequently in the code: + +- state +- conn state +- conn params +- ephemeral variables +- input data +- (experimental) database connector + +### persistence + +- state automatically flushes to storage intelligently +- to force a state flush and wait for it to finish, call (TODO: look this up in state document) +- read more about state persistence in the state document (link to document) +- state is stored in the same place as where the actor lives. loading an actor in to memory has comparable performance to network attached storage, and once in memory, has performance of any standard in-memory read/write like a variable. + +### scheduling & alarms + +- actors have a scheduling api to be able to wake up at any time in the indefinite future +- think of this like setTimeout but without a max timeout +- rivet is responsible for waking the actor when this timeout wakes + +### ephemeral variables + +- actors have the ability to create ephemrla variables for things that you do not want to be persisted with the actor's state +- this is useful for non-serializable data like a utility class like a pubsubs erver or something (TODO extra info) +- link to ephemeral variables docs + +### actions + +- for stateless clients, actions are sent as http requests via `POST /gateway/{actor id}/actions/{action name}` +- for stateful clients, actions are sent as websocket messages + +### events & subscriptions + +- events are sent as websocket messages + +### error handling + +- this is different than fault tolerance: + - error handling is a user error + - fault tolerance is something goes wrong that your applciation was not built to handle (ie hard crash, oom, network error) +- rivet provdies a special UserError class to throw custom errors that will be returned to the client +- all other errors are returned as a generic "internal error" +- this is becuase leaking error deatils is a common security hole, so we default to expose-nothing errors + +### logging + +- rivet uses pino for logging +- we expose a scoped child logger for each actor at `c.log` that automatically logs the actor id + key +- this allows you to search lgos easily by actor id without having to log the actor id frequently +- logs can be configured via the `RIVET_LOG_LEVEL` env var + +### fault tolerance + +- actors are fault tolerant, meaning that the host machine can crash and the actors will proceed to operate as if nothing happened +- runners maintain a socket with rivet engine. when this socket closes or takes to long to ping, actors will reschedule +- hibernating websockets (enabled by default) will live-migrate to the new actor as if nothing happened + +### crash policy + +- there are 3 crash policies: sleep, restart, and destroyed + - sleep (default, usually the option you want): + - when to use: actors that need high-performance in-memory logic. + - when not to use: you need this actor running at all times no matter what, even if idle + - examples: (list commone xamples) + - destroy: + - when to use: actors that need to run once until completion. on crash, do not try to reschedule. + - when not to use: if you want your actor to have fault tolerance and be able to run transaprenlty to the underlying runner + - examples: batch jobs, image conversions, ephemeral jobs, (TODO come up with better eaxmples) + - restart: + - when to use: actors that should be running at all times + - when not to use: if you don't absolutely need something running at all times, since this consumes needless compute resources. considure using the scheduling api instead. + - examples: maintain outbound sockets, daemons, always-running jobs, (TODO come up with better examples) + +the behavior for each is described below: + +| Event | Restart | Sleep | Destroy | +|------------------------------|--------------|--------------|--------------| +| Graceful exit (StopCode::Ok) | Destroy | Destroy | Destroy | +| Crash (non-Ok exit) | Reschedule | Sleep | Destroy | +| Lost (runner disappeared) | Reschedule | Sleep | Destroy | +| Lost + force_reschedule | Reschedule | Reschedule | Reschedule | +| GoingAway (runner draining) | Reschedule | Sleep | Destroy | +| No capacity (allocation) | Queue (wait) | Sleep | Queue (wait) | +| No capacity + serverless | Queue (wait) | Queue (wait) | Queue (wait) | +| Wake signal (while sleeping) | Reschedule | Reschedule | Reschedule | + +### inspector + +- actors provide an inspector api to implement the: + - repl + - state read/write + - network inspector + - event log +- this is impelmented over a websocket over bare + +### http api + +- see the http api document on actors + +### multi-region + +- actors can be scheduled across multiple regions +- each actor has an actor id which embeds which region it lives in +- networking is automatically routed to the region that an actor lives in +- limitation: actors curretnly cannot migrate across regions + +### backpressure + +#### no runner capacity + +- this is how actors with different crash policies behave when when there's backpressure: + - sleep = sleeps (sheds load by not rescheduling) + - restart = queues + - destroy = queues +- see the above matrix for more details on actor crash policy on how it handles no capacity. + +- the actor queue is built to withstand high amounts of backpressure on rivet, so queueing actors is fine here +- a large queue means it'll take more time for your application to process the queue to catch up with demand when it comes online. + +#### per-actor cpu & networking exhaustion + +- actors are isolated, so they each have their own individual bottleneck. you can think of this like a process thread where each thread can only do so much. +- there is no durable message queue/"mailbox" for actors. if the actor cannot respond in time, then the request is dropped. +- if an actor exhauses its cpu or networking, then the runner +- returns service unavailble (503) if the actor fails to respond to a request in time +- there is no hard cap on the networking or cpu usage for each actor at the moment +- if your actor is resource intensive, it's common to use a separate mailbox actor to act as a queue + +## runners + +### regular vs serverless runners + +there are 2 types of runners: + +- regular: these are standard nodejs processes connected to rivet that rivet can orchestrate actors to and send network requests to at any time +- serverless: rivet works with serverless platforms. when an actor is created, it has a request-per-actor model where it opens a long-running request on the serverless platofrm to run a given actor. + +### runner pool + +- runners are pooled together by sharing a common name (ie "default") +- when an acotr is created, it chooses the pool by selecting the runner name to run on +- rivet will automatically load balance actors across these runners + +### runner key + +- not relevnat for serverless runners +- each runner has a unique key that it provides when connecting. keys are unique to the instace the runner is running on and should be the same if the runner is restarted. +- this can be the: machine's ip, k8s pod name, etc +- if there is an existing runner connected with a given key, the runner will disconnect the old runner and replace it +- rivet is designed to handle network partitions by waiting for runners to miss a ping, indicating it's no longer alive. however, often times runners restart immediately after a hard crash and reconnect. in this case, the runner will reconnect on restart and terminate the old runner in order to prevent further actors from scheduling to the crashed runner. + +### capacity + +- not relevnat for serverless runners +- each runner can be assigned a capacity of how many actors it can run +- rivet will schedule with spread (not binpacking) in order to spread load over actors + +#### usefulness of capacity = 1 + +- setting a capacity of 1 is helpful for situations where you have cpu-intensive apps that should not run with any other actors +- examples include game servers, ffmpeg jobs, etc + +### versions & upgrading code + +- each runner has a version index +- actors are always scheduled to the highest verison index (see runner priority below) +- this means that when a new runner is deployed: + 1. runners with higher index come online + 2. actors schedule to the highest index, stop scheduling to the older index + 3. old index runners start draining and migrating actors to new index + 4. all old runners are now shut down +- websocekts are live migrated to the new version when upgrading using hibernating websockets to users see no hiccup in their applications +- this is important because actors should never downgrade their runner. they should always move to a newer version of code in order to prevent corruption. + +### runner scheduling prioroty + +- actors are scheduled to runners sorted by priority of (version DESC, remaining capacity ASC) + +### multi-region + +TODO + +### shutdown sequence + +- runner shutdown is important to ensure that actors do not get unexpectedly terminated when either: + - upgrading your applciation and taking down old pods + - scaling down your runners horizontally (ie from an hpa) + - pressing ctrl-c when in development +- on shutdown: + 1. tell rivet the runner is stopping + 2. rivet tells all the actors on this runner to migrate + 3. runner waits for all actors to finish migrating + 4. runner exits process + +### reconnection + +- runners can handle temporary network partitions +- they'll automatically reconnect and replay missed commands/events between rivet and the runner +- this happens transparenlty to the user +- if disconnected for too long (indicating a network partition), the runner will shut itself down and exit + +### autoscaling + +- not relevant to serverless +- runners currently autoscale on cpu. more intelligent scaling is coming soon. +- tune your runner total slots capacity accordingly +- it's up to you to configure your hpa/etc to work like this. see the Connect guides (link to index page) for reference on hwo to configure this. + +### serverless timeouts + +- serverless runners take in to account the maximum run duration of the serverless platform +- the runners will mgirate actors to a new request before the request times out +- this is completely transparent to you and the user because of the fault tolerance and websocket migraiton characteristics +- it's common for actors to go sleep before hitting the serverless timeout + +## networking + +### web standards + +- everything in rivet is built on webstandards by default +- nothing in rivet requires you to use our sdk, our sdks are meant to be a convenience. it's built to be as easy to use raw http/websocket endpoints from scratch. +- actions, events, etc are all built on simple, well-documented http/websocket under the hood (link to openapi & asyncapi docs). +- you can use low-level request handlers (lnk to dock) and low-level weboscket handlers (link to doc) to handle low-level primtivies yourself + +### encoding + +- rivetkit's action/events api supports communicating via [VBARE](link to github repo, see the blog post for the link), CBOR, or JSON + - VBARE: high-perofrmance & compact, optimal use case + - CBOR: descent encoding/decoding perf + portable libraries, good for implemnting high-ish performance on other platforms + - JSON: good for fast implementations & debugging (easy to read) + +### tunneling + +- when a runner connects it opens a tunnel to rivet to allow incoming traffic + - this is simila to systems like tailscale, ngrok, or other vpns + - we do this for security & configuraiton simplicity since it means that you don't have to manage exposing your rivetkit applications' networkig to rivet. instead, anything that can open a socket to rivet can accept inbound traffic to actors. + +### gateway + +- incoming traffic to actors come to the Rivet gateway and are routed to the appropriate runner +- the rivet gateway automatically handles: + - multi-region routing to route traffic to the correct reigon for an actor + - automatically waking the actor if needed + - sending traffic over the runner + +### hibernating websockets + +- hibernating web sockets are a core component of live actor migration & fault tolerance. it allows us to maintain an open websocket while the actor crashes, upgrades, or moves to another runner. +TODO: copy the rest of this from low-level webosckets document and rephrase + +### actor health endpoin + +- actors provide a simple, utility health endpoint at `/health` that lets you check if your actor is reachable (e.g. `curl https://api.rivet.dev/gateway/{actor id}/health`) + +## multi-region + +### networking + +- actors may live in different regions than inbound requests +- Rivet uses the Epoxy (link again) system to handle global routing to route traffic to the correct region with high performance +- this is completely transparent to you. your app sends traffic to https://api.rivet.dev/gateway/* and it automatically routes to the correct actor in the appropriate region + +### globally unique actor keys + +- acotr keys are globally unique to be able to benefit from multi-region capabilities without any extra work +- see more about globally uniuqe actor keys above +- see the actor keys document + +### regional endpoints + +- each reigon has a regional endpoint +- this endpoint is used specifically for connecting runners (for example https://api-us-east-1.rivet.dev), opt to use api.rivet.dev for all other traffic +- runners are required to connect to the regional endpoints + - this is because runners are sensitive to latency to the rivet regional datacenter + - we add datacenters regularly so each runner needs to be pinned to a single datacenter in order to ensure your availble datacneter list doesn't change sporadically without your consent + +### persistence + +- data is always persisted in the same region that is written +- this is important for minimal coldstarts & data locality laws + +## namespaces + +- rivet provides namespaces to run multiple actor systems in isolation +- this makes it really easy to have prod/staging environments or completely different applications running on the same rivet instance +- when you connect to rivet, you can specify which namespace you're connecting to +- self-hotsed rivet defaults to namespace "default" +- rivet cloud provdies isolated tokens for each namespace + +## manager api + +- rivet provides a standard rest api for managing actors + - useful endoints include: + - get /actors + - delete /actors/{} + - get /actors/names -> get all actor types available + +## comparison to prior art for actors + +### runtime + +- there are very few serious actor implementation targeted at the javascirpt eocsystem. rivet is arguably the most serious open-source actor implementation for typescript out there. + +### library vs orchestrator + +- some actor systems opt to be purely a library while rivet opts to have an orchestrator (i.e. the single rust binary) +- this lets us to a lot of things other actor systems can't: + - separating orchestration, persistence, and proxy lets us isoalte the core to be incredibly reliable while the fast-changing applications that ocnnect to rivet can be more error-prone safely. with a library, the blast radius of your application also affects the entire actor system. + - support for serverless platforms to benefit from cost, multi-region, blitz scaling, and relibaiblity benefits + - optimize fault tolerance since we can make more assumtions about application state when the rivet core does not crash and your app does + +### scheduling + +actors is a loose term, but there are generally 2 types of schedulign in practice: + +- ephemeral actors + - examples: erlang/otp, akka, swift + - provides no persistence or sleeping mechanism by defualt + - relies on supervisors for managing persistence +- [virtual actors](https://www.microsoft.com/en-us/research/project/orleans-virtual-actors/) + - an extension of the actor pattern that provides actors that can hibernate ("sleep") when not in use + - examples: orleans, dapr, durable objects + +rivet has similarities with both to provide more flexibility: + +- crash policies provdie for 3 types of actors: + - sleep -> most similar to virutal actors + - restart -> most similar to ephemeral actors but with a supervisor to auto-restart, however still has a durable queue ot handle backpressure + - crash -> most similar to traditional actors but with no supervisor to restart, however still has a durable queue to handle backpressure + +### communication + +- many actor frameworks use inbox patterns (think: queue-per-actor) to handle sending messages between actors +- there is no callback mechanims, instead you need to send messages back to the actual actor +- rivet opts to behave like web standards instead of using the message pattern + - actors can impelment the inbox pattern optionally + - but we provide lower-level networking to be able to be compatible with more techniologies + - rivet assumes the same serial concurerntly that other actors do (by the nature of javascript being single-threaded) but we allow you to run promises in parallel or handl eyour own concurrency control (which some other actor frameworks might require a spawning new actor to do) + +_Source doc path: /docs/general/architecture_ diff --git a/.agents/skills/ai-agent-workspace/reference/general/cors.md b/.agents/skills/ai-agent-workspace/reference/general/cors.md new file mode 100644 index 0000000..c138478 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/general/cors.md @@ -0,0 +1,74 @@ +# Cross-Origin Resource Sharing + +> Source: `src/content/docs/general/cors.mdx` +> Canonical URL: https://rivet.dev/docs/general/cors +> Description: Cross-Origin Resource Sharing (CORS) controls which origins (domains) can access your actors. When actors are exposed to the public internet, proper origin validation is critical to prevent security breaches and denial of service attacks. + +--- +Unlike stateless HTTP APIs that use CORS headers, Rivet Actors are stateful and support persistent WebSocket connections. Since WebSockets don't natively support CORS, we validate origins manually in the `onBeforeConnect` hook before connections may open. + +## Implementing Origin Restrictions + +To implement origin restrictions on Rivet Actors, use the `onBeforeConnect` hook to verify the request. + +```typescript server.ts +import { actor, UserError } from "rivetkit"; + +const ALLOWED_ORIGINS = [ + "http://localhost:3000", + "https://myapp.com", + "https://www.myapp.com" +]; + +const myActor = actor({ + state: { count: 0 }, + + onBeforeConnect: (c, params) => { + // Check if origin is allowed + // + // This works for both HTTP & WebSocket requests + const origin = c.request?.headers.get("origin") ?? ""; + if (!ALLOWED_ORIGINS.includes(origin)) { + throw new UserError("Origin not allowed", { code: "origin_not_allowed" }); + } + }, + + actions: { + increment: (c) => { + c.state.count++; + return c.state.count; + } + } +}); +``` + +To catch the error on the client, use the following code: + +```typescript client.ts +import { createClient, ActorError } from "rivetkit/client"; +import { actor, setup } from "rivetkit"; + +const myActor = actor({ + state: { count: 0 }, + actions: { increment: (c) => c.state.count++ } +}); +const registry = setup({ use: { myActor } }); + +const client = createClient("http://localhost:6420"); + +try { + const actorHandle = client.myActor.getOrCreate(["my-actor"]); + const conn = actorHandle.connect(); + + // Connection will be established or error will be thrown + await conn.increment(); +} catch (error) { + if (error instanceof ActorError && error.code === "origin_not_allowed") { + console.error("Connection rejected: Origin not allowed"); + } +} +``` + + See tracking issue for [configuring CORS per-actor on the gateway](https://github.com/rivet-dev/rivet/issues/3539) that will remove the need to implement origin restrictions in `onBforeRequest`. + +_Source doc path: /docs/general/cors_ diff --git a/.agents/skills/ai-agent-workspace/reference/general/docs-for-llms.md b/.agents/skills/ai-agent-workspace/reference/general/docs-for-llms.md new file mode 100644 index 0000000..db0c216 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/general/docs-for-llms.md @@ -0,0 +1,51 @@ +# Documentation for LLMs & AI + +> Source: `src/content/docs/general/docs-for-llms.mdx` +> Canonical URL: https://rivet.dev/docs/general/docs-for-llms +> Description: Rivet provides optimized documentation formats specifically designed for Large Language Models (LLMs) and AI integration tools. + +--- +## Skills (Recommended) + +For AI coding assistants like Claude Code, Cursor, or Windsurf, install Rivet skills for the best development experience: + +```sh +npx skills add rivet-dev/skills +``` + +Skills provide your AI assistant with Rivet-specific knowledge, best practices, and code patterns directly in your project context. + +## Available Formats + +### `llms.txt` (Condensed) +A condensed version of the documentation perfect for quick reference and context-aware AI assistance. + +**Access:** /llms.txt + +This format includes: +- Key concepts and features +- Essential getting started information +- Summaries of main functionality +- Optimized for token efficiency + +### `llms-full.txt` (Complete) +The complete documentation in a single file, ideal for comprehensive AI assistance and in-depth analysis. + +**Access:** /llms-full.txt + +This format includes: +- Complete documentation content +- All examples and detailed explanations +- Full API references and guides +- Suitable for complex queries and comprehensive understanding + +## Access Pages As Markdown + +Each documentation page is also available as clean markdown by appending `.md` to any documentation URL path. + +For example: + +- Original URL: `https://rivet.dev/docs/actors` +- Markdown URL: `https://rivet.dev/docs/actors.md` + +_Source doc path: /docs/general/docs-for-llms_ diff --git a/.agents/skills/ai-agent-workspace/reference/general/edge.md b/.agents/skills/ai-agent-workspace/reference/general/edge.md new file mode 100644 index 0000000..711dddd --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/general/edge.md @@ -0,0 +1,39 @@ +# Edge Networking + +> Source: `src/content/docs/general/edge.mdx` +> Canonical URL: https://rivet.dev/docs/general/edge +> Description: Actors automatically run near your users on your provider's global network. + +--- +At the moment, edge networking is only supported on Rivet Cloud & Cloudflare Workers. More self-hosted platforms are on the roadmap. + +## Region selection + +### Automatic region selection + +By default, actors will choose the nearest region based on the client's location. + +Under the hood, Rivet and Cloudflare use [Anycast routing](https://en.wikipedia.org/wiki/Anycast) to automatically find the best location for the client to connect to without relying on a slow manual pinging process. + +### Manual region selection + +The region an actor is created in can be overridden using region options: + +```typescript client.ts +import { createClient } from "rivetkit/client"; +import { actor, setup } from "rivetkit"; + +const example = actor({ state: {}, actions: {} }); +const registry = setup({ use: { example } }); + +const client = createClient("http://localhost:6420"); + +// Create actor in a specific region using getOrCreate +const actorHandle = client.example.getOrCreate(["my-actor"], { + createInRegion: "atl" +}); +``` + +See [Create Manage Actors](/docs/actors/communicating-between-actors) for more information. + +_Source doc path: /docs/general/edge_ diff --git a/.agents/skills/ai-agent-workspace/reference/general/endpoints.md b/.agents/skills/ai-agent-workspace/reference/general/endpoints.md new file mode 100644 index 0000000..b68de0e --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/general/endpoints.md @@ -0,0 +1,128 @@ +# Endpoints + +> Source: `src/content/docs/general/endpoints.mdx` +> Canonical URL: https://rivet.dev/docs/general/endpoints +> Description: Configure how your backend connects to Rivet and how clients reach your actors. + +--- +## Local Development + +No configuration is needed for local development. RivetKit runs entirely on your local machine without any extra configuration to run Rivet Actors. + +## Production Deployment + +When deploying to production, you need to configure endpoints so your backend can communicate with Rivet Engine and clients can reach your actors. + +Diagram showing Client connecting to Rivet, which connects to Your Backend + +### Private Endpoint + +The private endpoint tells your backend where to find the Rivet Engine. + +### Environment Variable + +```bash +RIVET_ENDPOINT=https://my-namespace:sk_xxxxx@api.rivet.dev +``` + +### Config + +```typescript +import { actor, setup } from "rivetkit"; + +const myActor = actor({ + state: {}, + actions: {} +}); + +const registry = setup({ + use: { myActor }, + endpoint: "https://my-namespace:sk_xxxxx@api.rivet.dev", +}); +``` + +### Public Endpoint + +The public endpoint tells clients where to connect to reach your actors. + +This endpoint and token will be exposed to the internet. Use a public token (`pk_`), not your secret token (`sk_`). + +The public endpoint is only required if using the [serverless runtime mode](/docs/general/runtime-modes#runners) and if you have a frontend using RivetKit. + +### Environment Variable + +```bash +RIVET_PUBLIC_ENDPOINT=https://my-namespace:pk_xxxxx@api.rivet.dev +``` + +### Config + +```typescript +import { actor, setup } from "rivetkit"; + +const myActor = actor({ + state: {}, + actions: {} +}); + +const registry = setup({ + use: { myActor }, + serverless: { + publicEndpoint: "https://my-namespace:pk_xxxxx@api.rivet.dev", + }, +}); +``` + +## Advanced + +### URL Auth Syntax + +Endpoint URLs support embedding namespace and token directly in the URL: + +``` +https://namespace:token@host/path +``` + +This is the recommended approach for simplicity. Alternatively, you can use separate environment variables: + +```bash +RIVET_ENDPOINT=https://api.rivet.dev +RIVET_NAMESPACE=my-namespace +RIVET_TOKEN=sk_xxxxx +``` + +### Security + +In serverless mode, the private endpoint is used to validate that requests to `GET /api/rivet/start` are coming from your trusted Rivet endpoint. If the private endpoint is not configured, anyone can run a self-hosted instance of Rivet and connect to your backend from any endpoint. + +### How Clients Connect + +This flow applies to [serverless runtime mode](/docs/general/runtime-modes#serverless). For [runner runtime mode](/docs/general/runtime-modes#runners) or [clients configured to connect directly to Rivet](/docs/clients/javascript), clients connect directly to Rivet and this metadata flow is not needed. + +When a client connects to your serverless application, it follows this flow: + +1. Client makes a request to `https://my-app.example.com/api/rivet/metadata` +2. Your app returns the public endpoint configuration: + ```json + { + "clientEndpoint": "https://api.rivet.dev", + "clientNamespace": "my-namespace", + "clientToken": "pk_xxxxx" + } + ``` +3. Client caches these values and uses them for subsequent requests +4. Client connects to `https://api.rivet.dev/gateway/{actor}`, which routes requests to your actors + +This indirection exists because Rivet acts as a gateway between clients and your actors. This is because Rivet handles routing, load balancing, and actor lifecycle management of actors. + +## Reference + +| Environment Variable | Config Option | Description | +|---------------------|---------------|-------------| +| `RIVET_ENDPOINT` | `endpoint` | Rivet Engine URL for your backend | +| `RIVET_NAMESPACE` | `namespace` | Namespace for actor isolation | +| `RIVET_TOKEN` | `token` | Authentication token for engine connection | +| `RIVET_PUBLIC_ENDPOINT` | `serverless.publicEndpoint` | Client-facing endpoint | +| `RIVET_PUBLIC_TOKEN` | `serverless.publicToken` | Client-facing token | + +_Source doc path: /docs/general/endpoints_ diff --git a/.agents/skills/ai-agent-workspace/reference/general/environment-variables.md b/.agents/skills/ai-agent-workspace/reference/general/environment-variables.md new file mode 100644 index 0000000..2a86e98 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/general/environment-variables.md @@ -0,0 +1,87 @@ +# Environment Variables + +> Source: `src/content/docs/general/environment-variables.mdx` +> Canonical URL: https://rivet.dev/docs/general/environment-variables +> Description: This page documents all environment variables that configure RivetKit behavior. + +--- +## Connection + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_ENDPOINT` | Endpoint URL to connect to Rivet Engine. Supports [URL auth syntax](/docs/general/endpoints#url-auth-syntax). | +| `RIVET_TOKEN` | Authentication token for Rivet Engine | +| `RIVET_NAMESPACE` | Namespace to use (default: "default") | + +## Public Endpoint + +These variables configure how clients connect to your actors. + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_PUBLIC_ENDPOINT` | Public endpoint for client connections. Supports [URL auth syntax](/docs/general/endpoints#url-auth-syntax). | +| `RIVET_PUBLIC_TOKEN` | Public token for client authentication | + +## Runner Configuration + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_RUNNER` | Runner name (default: "default") | +| `RIVET_RUNNER_VERSION` | Version number for the runner. See [Versions & Upgrades](/docs/actors/versions). | +| `RIVET_RUNNER_KIND` | Type of runner | +| `RIVET_TOTAL_SLOTS` | Total actor slots available (default: 100000) | + +## Engine + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_RUN_ENGINE` | Set to `1` to spawn the engine process | +| `RIVET_RUN_ENGINE_HOST` | Host to bind the spawned local engine process to. Defaults to `127.0.0.1`. | +| `RIVET_RUN_ENGINE_PORT` | Port to bind the spawned local engine process to. Defaults to `6420`. | +| `RIVET_RUN_ENGINE_VERSION` | Version of engine to download | + +## Inspector + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_INSPECTOR_DISABLE` | Set to `1` to disable the inspector | + +## Metrics + +| Environment Variable | Description | +|---------------------|-------------| +| `_RIVET_METRICS_TOKEN` | Bearer token that gates the per-actor Prometheus `/metrics` endpoint. When unset, `/metrics` is disabled. | + +## Experimental + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_EXPERIMENTAL_OTEL` | Set to `1` to enable experimental OTel tracing in Rivet Actors | + +## Storage + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVETKIT_RUNTIME` | Runtime binding to use for RivetKit core: `auto`, `native`, or `wasm`. Defaults to `auto`. | +| `RIVETKIT_STORAGE_PATH` | Overrides the default file-system storage path used by RivetKit when using the default driver. | + +## Lifecycle + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVETKIT_RUNTIME_MODE` | Controls how `registry.start()` runs. Accepted values are `envoy` and `serverless`; any other explicit value errors. Defaults to `envoy`: opens a long-lived WebSocket to the engine (Mode A). Set to `serverless` to bind an HTTP listener via `registry.listen()` (Mode B). | +| `RIVETKIT_PUBLIC_DIR` | Directory of static assets to serve alongside the framework routes when calling `registry.listen()`. Used as a fallback when `opts.publicDir` is not passed. On auto-listen via `registry.start()`, defaults to `/public` when this env var is unset. | +| `RIVET_PORT` | Port the listener binds when calling `registry.listen()` without an explicit `opts.port`. Must be an integer between 1 and 65535. Defaults to `3000`. | + +## Logging + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_LOG_LEVEL` | Log level: `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `silent` | +| `RIVET_LOG_TARGET` | Set to `1` to include log target | +| `RIVET_LOG_TIMESTAMP` | Set to `1` to include timestamps | +| `RIVET_LOG_MESSAGE` | Set to `1` to include message formatting | +| `RIVET_LOG_ERROR_STACK` | Set to `1` to include error stack traces | +| `RIVET_LOG_HEADERS` | Set to `1` to log request headers | + +_Source doc path: /docs/general/environment-variables_ diff --git a/.agents/skills/ai-agent-workspace/reference/general/http-server.md b/.agents/skills/ai-agent-workspace/reference/general/http-server.md new file mode 100644 index 0000000..7b2118a --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/general/http-server.md @@ -0,0 +1,156 @@ +# HTTP Server + +> Source: `src/content/docs/general/http-server.mdx` +> Canonical URL: https://rivet.dev/docs/general/http-server +> Description: Different ways to run your RivetKit HTTP server. + +--- +## Methods of Running Your Server + +### registry.start() + +The simplest way to run your server. Starts a local RivetKit server, serves static files from a `public` directory, and starts the actor runner: + +```ts index.ts +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +registry.start(); +``` + +Run with `npx tsx --watch index.ts` (Node.js), `bun --watch index.ts` (Bun), or `deno run --allow-net --allow-read --allow-env --watch index.ts` (Deno). Clients connect to the Rivet Engine on `http://localhost:6420`. + +### With Fetch Handlers + +A [fetch handler](https://wintercg.org/) is a function that takes a `Request` and returns a `Response`. This is the standard pattern used by Cloudflare Workers, Deno Deploy, Bun, and other modern runtimes. + +Use `registry.serve()` to get a fetch handler: + +```ts server.ts +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +export default registry.serve(); +``` + +To integrate with a router like [Hono](https://hono.dev/) or [Elysia](https://elysiajs.com/), use `registry.handler()`: + +### Hono + +```ts server.ts +import { Hono } from "hono"; +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +const app = new Hono(); +app.get("/health", (c) => c.text("OK")); +app.all("/api/rivet/*", (c) => registry.handler(c.req.raw)); + +export default app; +``` + +### Elysia + +```ts server.ts +import { Elysia } from "elysia"; +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +const app = new Elysia() + .get("/health", () => "OK") + .all("/api/rivet/*", ({ request }) => registry.handler(request)); + +export default app; +``` + +Then run your server: + +```bash Node.js +npx tsx --watch server.ts +``` + +```bash Bun +bun --watch server.ts +``` + +```bash Deno +deno run --allow-net --allow-read --allow-env --watch server.ts +``` + +### Explicit HTTP Server + +If you need to explicitly start the HTTP server instead of using the fetch handler pattern: + +### Node.js (Hono) + +Using Hono with `@hono/node-server`: + +```ts server.ts +import { Hono } from "hono"; +import { serve } from "@hono/node-server"; +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +const app = new Hono(); +app.all("/api/rivet/*", (c) => registry.handler(c.req.raw)); + +serve({ fetch: app.fetch, port: 3000 }); +``` + +### Node.js (Adapter) + +Using `@whatwg-node/server` to adapt the fetch handler to Node's HTTP server: + +```ts server.ts @nocheck +import { actor, setup } from "rivetkit"; +import { createServer } from "node:http"; +import { createServerAdapter } from "@whatwg-node/server"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +const handler = createServerAdapter(registry.serve().fetch); +const server = createServer(handler); +server.listen(3000); +``` + +### Bun + +Using Bun's native server: + +```ts server.ts @nocheck +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +Bun.serve({ + port: 3000, + fetch: (request: Request) => registry.handler(request), +}); +``` + +### Deno + +Using Deno's native server: + +```ts server.ts @nocheck +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +Deno.serve({ port: 3000 }, (request: Request) => registry.handler(request)); +``` + +_Source doc path: /docs/general/http-server_ diff --git a/.agents/skills/ai-agent-workspace/reference/general/logging.md b/.agents/skills/ai-agent-workspace/reference/general/logging.md new file mode 100644 index 0000000..c12a370 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/general/logging.md @@ -0,0 +1,151 @@ +# Logging + +> Source: `src/content/docs/general/logging.mdx` +> Canonical URL: https://rivet.dev/docs/general/logging +> Description: Actors provide a built-in way to log complex data to the console. + +--- +Using the context's log object (`c.log`) allows you to log complex data using structured logging. + +Using the actor logging API is completely optional. + +## Log levels + +There are 7 log levels: + +| Level | Call | Description | +| ------ | ------------------------------- | ---------------------------------------------------------------- | +| Fatal | `c.log.fatal(message, ...args);` | Critical errors that prevent core functionality | +| Error | `c.log.error(message, ...args);` | Errors that affect functionality but allow continued operation | +| Warn | `c.log.warn(message, ...args);` | Potentially harmful situations that should be addressed | +| Info | `c.log.info(message, ...args);` | General information about significant events & state changes | +| Debug | `c.log.debug(message, ...args);` | Detailed debugging information, usually used in development | +| Trace | `c.log.trace(message, ...args);` | Very detailed debugging information, usually for tracing flow | +| Silent | N/A | Disables all logging output | + +## Structured logging + +The built-in logging API (using `c.log`) provides structured logging to let you log key-value +pairs instead of raw strings. Structured logs are readable by both machines & +humans to make them easier to parse & search. + +When using `c.log`, the actor's name, key, and actor ID are automatically included in every log output. This makes it easy to filter and trace logs by specific actors in production environments. + +### Examples + +```typescript +import { actor } from "rivetkit"; + +const myActor = actor({ + state: {}, + actions: { + logExamples: (c) => { + // Just a message + c.log.info('server started'); + // Prints: level=INFO actor=myActor key=foo actorId=44096d46632fd087 msg="server started" + + // Object with message and additional fields + c.log.info({ msg: 'user connected', userId: 123, ip: '192.168.1.1' }); + // Prints: level=INFO actor=myActor key=foo actorId=44096d46632fd087 msg="user connected" userId=123 ip="192.168.1.1" + + // Just an object (no message) + c.log.info({ action: 'purchase', amount: 99.99, currency: 'USD' }); + // Prints: level=INFO actor=myActor key=foo actorId=44096d46632fd087 action="purchase" amount=99.99 currency="USD" + } + } +}); +``` + +The logging system is built on [Pino](https://getpino.io/#/docs/api?id=logger), a high-performance structured logger for Node.js. + +## Configuration + +### Environment Variables + +You can configure logging behavior using environment variables: + +| Variable | Description | Values | Default | +| -------- | ----------- | ------ | ------- | +| `RIVET_LOG_LEVEL` | Sets the minimum log level to display | `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `silent` | `warn` | +| `RIVET_LOG_TARGET` | Include the module name that logged the message | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_TIMESTAMP` | Include timestamp in log output | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_MESSAGE` | Enable detailed message logging for debugging | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_ERROR_STACK` | Include stack traces in error output | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_HEADERS` | Log HTTP headers in requests | `1` to enable, `0` to disable | `0` | + +Example: +```bash +RIVET_LOG_LEVEL=debug RIVET_LOG_TARGET=1 RIVET_LOG_TIMESTAMP=1 node server.js +``` + +### Log Level + +You can configure the log level programmatically when setting up your registry: + +```typescript +import { actor, setup } from "rivetkit"; + +const counter = actor({ + state: { count: 0 }, + actions: { increment: (c) => c.state.count++ } +}); + +const registry = setup({ + use: { counter }, + logging: { + level: "debug" + } +}); +``` + +### Custom Pino Logger + +You can also provide a custom Pino base logger for more advanced logging configurations: + +```typescript +import { actor, setup } from "rivetkit"; +import { pino } from "pino"; + +const counter = actor({ + state: { count: 0 }, + actions: { increment: (c) => c.state.count++ } +}); + +const customLogger = pino({ + level: "info", + transport: { + target: "pino-pretty" + } +}); + +const registry = setup({ + use: { counter }, + logging: { + baseLogger: customLogger, // Use your custom Pino logger + } +}); +``` + +If using a custom base logger, you must manually configure your own log level in the Pino logger. + +For more advanced Pino configuration options, see the [Pino API documentation](https://getpino.io/#/docs/api?id=export). + +### Disable Welcome Message + +You can disable the default RivetKit welcome message with: + +```typescript +import { actor, setup } from "rivetkit"; + +const counter = actor({ + state: { count: 0 }, + actions: { increment: (c) => c.state.count++ } +}); + +const registry = setup({ + use: { counter }, + noWelcome: true +}); +``` + +_Source doc path: /docs/general/logging_ diff --git a/.agents/skills/ai-agent-workspace/reference/general/pool-configuration.md b/.agents/skills/ai-agent-workspace/reference/general/pool-configuration.md new file mode 100644 index 0000000..21b00f1 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/general/pool-configuration.md @@ -0,0 +1,119 @@ +# Pool Configuration + +> Source: `src/content/docs/general/pool-configuration.mdx` +> Canonical URL: https://rivet.dev/docs/general/pool-configuration +> Description: Reference for runner pool configuration, including drain behavior, actor eviction rate limiting, and serverless-specific options. + +--- +A **runner pool** is the set of runners Rivet manages for a given runner name within a namespace. The pool configuration controls how runners are scaled, drained on version upgrades, and how quickly actors are evicted from drained runners. + +There are two pool kinds: + +- **`normal`** — runners connect to the engine themselves (for example a long-running process started by you, Docker, or Kubernetes). The engine does not start or stop runners. +- **`serverless`** — the engine calls an HTTP endpoint to wake runners on demand. Used by serverless platforms (Vercel, Cloudflare Workers, Freestyle, etc.). See [Runtime Modes](/docs/general/runtime-modes). + +## Setting the Configuration + +Configure a pool from the [Rivet dashboard](https://dashboard.rivet.dev) under your namespace's runner settings. The dashboard is the recommended way to manage pool configuration. + +You can also set pool configuration directly through the API or the TypeScript SDK: + +```typescript SDK @nocheck +import { RivetClient } from "@rivetkit/engine-api-full"; + +const rivet = new RivetClient({ + environment: "https://api.rivet.dev", + token: process.env.RIVET_TOKEN!, +}); + +await rivet.runnerConfigsUpsert("default", { + namespace: "default", + datacenters: { + default: { + serverless: { + url: "https://my-app.example.com/api/rivet", + requestLifespan: 60 * 15, + actorEvictionDelay: 5, + actorEvictionPeriod: 60, + actorEvictionRate: 1, + }, + }, + }, +}); +``` + +```bash curl +curl -X PUT "https://api.rivet.dev/runner-configs/default?namespace=default" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "datacenters": { + "default": { + "serverless": { + "url": "https://my-app.example.com/api/rivet", + "request_lifespan": 900, + "actor_eviction_delay": 5, + "actor_eviction_period": 60, + "actor_eviction_rate": 1 + } + } + } + }' +``` + +The HTTP API uses `snake_case`. The TypeScript SDK uses `camelCase`. The field names below use `camelCase`. + +## Common Options + +These options apply to both `normal` and `serverless` pools. + +| Option | Type | Default | Description | +|---|---|---|---| +| `drainOnVersionUpgrade` | `bool` | `true` | When a new runner version is deployed, stop old runners and migrate their actors. See [Versions & Upgrades](/docs/actors/versions#drain-on-version-upgrade). | +| `actorEvictionDelay` | `u32` (seconds) | `0` | Delay before actor eviction begins after a drain is triggered. Gives clients time to receive the drain signal before migrations start. | +| `actorEvictionPeriod` | `u32` (seconds) | `0` | Window over which evictions are batched. Used together with `actorEvictionRate` to smooth eviction load on the rest of the pool. | +| `actorEvictionRate` | `f32` (actors/sec) | `1.0` | Maximum number of actors evicted per second once eviction is underway. Set higher for fast cutovers, lower to spread reschedule load. | +| `metadata` | `object` | — | Arbitrary JSON metadata attached to the pool. Useful for tagging and dashboards. | + +### Tuning eviction rate limiting + +Eviction kicks in whenever a runner is drained — most commonly during a version upgrade with `drainOnVersionUpgrade: true`, but also when a runner disconnects ungracefully or is replaced. + +A typical tuning starts from: + +- `actorEvictionDelay: 5` — five-second head start so clients see the drain notification before migrations begin. +- `actorEvictionPeriod: 60` — batch over a one-minute window. +- `actorEvictionRate: 1` — evict one actor per second. + +Increase `actorEvictionRate` for small pools where a full cutover finishes in seconds. Decrease it for large pools to avoid bursts of reschedule traffic. + +## Serverless-Only Options + +These options only apply when `kind: "serverless"`. + +| Option | Type | Default | Description | +|---|---|---|---| +| `url` | `string` | — | HTTP endpoint the engine calls to wake a runner. | +| `headers` | `map` | `{}` | Additional headers sent with the wake request (for example an auth token). | +| `requestLifespan` | `u32` (seconds) | — | Total lifespan of a serverless request before drain begins. Must be shorter than your platform's request timeout. | +| `maxConcurrentActors` | `u64` | `1000` | Soft cap on concurrent actors hosted across the pool. | +| `drainGracePeriod` | `u32` (seconds) | `1800` (30 min) | Time a serverless runner reserves at the end of its lifespan for actors to stop gracefully. | +| `metadataPollInterval` | `u64` (ms) | engine default | How often each runner re-fetches pool metadata to detect new versions. | + +### Deprecated options + +The following options still parse for backwards compatibility but should not be used in new configurations: + +- `slotsPerRunner` +- `minRunners` +- `maxRunners` +- `runnersMargin` + +## Related + +- [Runtime Modes](/docs/general/runtime-modes) — runner vs serverless behavior. +- [Versions & Upgrades](/docs/actors/versions) — how `drainOnVersionUpgrade` interacts with version detection. +- [Limits](/docs/actors/limits) — request lifespan and drain grace period limits. +- [Debugging](/docs/actors/debugging) — inspect a pool configuration via the API. + +_Source doc path: /docs/general/pool-configuration_ diff --git a/.agents/skills/ai-agent-workspace/reference/general/production-checklist.md b/.agents/skills/ai-agent-workspace/reference/general/production-checklist.md new file mode 100644 index 0000000..1ebe257 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/general/production-checklist.md @@ -0,0 +1,98 @@ +# Production Checklist + +> Source: `src/content/docs/general/production-checklist.mdx` +> Canonical URL: https://rivet.dev/docs/general/production-checklist +> Description: Checklist for deploying Rivet Actors to production. + +--- +We recommend passing this page to your coding agent to verify your configuration before deploying. + +## Environment + +- **Set `NODE_ENV=production`.** Ensures optimized performance and disables development-only behavior. +- **Ensure log level is not set to debug.** Leave `RIVET_LOG_LEVEL` at its default or explicitly set it to `warn` to avoid excessive logging. See [Logging](/docs/general/logging). +- **Do not set `RIVET_EXPOSE_ERRORS=1` in production.** This exposes internal error details to clients. It is automatically enabled when `NODE_ENV=development`. See [Errors](/docs/actors/errors). + +## Runtime Mode + +- **Configure a runner version.** Required for graceful upgrades and draining of old actors. Applies to both serverless and runner modes. See [Versions & Upgrades](/docs/actors/versions). + +### Serverless + +- **Check platform timeouts.** Rivet handles migration between invocations automatically, but shorter timeouts increase migration frequency. See [Timeouts](/docs/general/runtime-modes#timeouts). +- **Verify `/api/rivet/start` body size limits.** Serverless actor starts carry actor config and preloaded KV or SQLite startup data in the request body. Keep `serverless.maxStartPayloadBytes` and your platform or proxy body limit at **16 MiB or higher**, or lower the preload budget if your platform cannot accept that size. See [Limits](/docs/actors/limits#kv-preloading). +- **Configure max runners.** Go to Settings > Providers > Edit Provider > Max Runners to set the limit. The default is 100,000 runners. This is effectively your max actor count. +- **Verify your platform rate limit accommodates your actor create and wake frequency.** Actor start requests are sent from Rivet's servers, so they all originate from the same IP. Per-IP rate limits will throttle the engine well before they would throttle real end-user traffic. Size your platform's rate limit to your peak actor create and wake rate, not your end-user request rate. +- **Set the per-instance max concurrent actor limit.** Each serverless instance hosts one actor per in-flight `/api/rivet/start` request, so your platform's per-instance concurrency (e.g. GCP Cloud Run `--concurrency`, AWS Lambda reserved concurrency, Vercel `maxDuration` + concurrency) directly caps actors per instance. Pick a value based on per-actor memory and CPU; the platform autoscales out additional instances once existing ones hit the cap. +- **Tune `requestLifespan` to your platform's hard request timeout.** `requestLifespan` (default `3600`, 60 minutes) is the total lifespan of each serverless request before actors migrate to a fresh instance. Set it just below your platform's hard timeout (e.g. `295` for Vercel Hobby, `3595` for Vercel Pro, `840` for Cloud Run's 15-min cap). Configure via [`configurePool`](/docs/general/registry-configuration). See [Timeouts](/docs/general/runtime-modes#timeouts). +- **Tune `drainGracePeriod` to cover graceful actor shutdown.** Time reserved at the end of `requestLifespan` for actors to stop gracefully before the request is forcibly closed. Default is 30 minutes from the engine; lower it for short-lived stateless actors, raise it if your actors do non-trivial cleanup or final SQLite writes. Configure via [`configurePool`](/docs/general/registry-configuration). See [Limits](/docs/actors/limits). + +### Runner + +- **Set a graceful shutdown period of at least 35 minutes.** Runners need up to 30 minutes to drain actors during upgrades, plus buffer for shutdown overhead. In Kubernetes, set `terminationGracePeriodSeconds: 2100` on the pod spec. + +## Actors + +### Design Patterns + +- **Do not use god actors.** Avoid putting all logic into a single actor type. See [Design Patterns](/docs/actors/design-patterns). +- **Do not use actor-per-request patterns.** Avoid creating a new actor for each request. See [Design Patterns](/docs/actors/design-patterns). + +### Lifecycle + +- **Do not rely on `onSleep` for critical cleanup.** `onSleep` is not called during crashes or forced terminations. See [Lifecycle](/docs/actors/lifecycle). + +### State + +- **Verify `c.state` does not grow unbounded.** Avoid using arrays or objects that grow over time in state. Use [SQLite](/docs/actors/sqlite) for unbounded or append-heavy data instead. +- **Verify actor data does not exceed 10 GB.** Contact [enterprise support](https://rivet.dev/sales) if you need more storage. +- **Use input parameters and `createState` for actor initialization.** See [Input Parameters](/docs/actors/input). + +### Events + +- **Use `conn.send()` instead of `c.broadcast()` for private events.** `c.broadcast()` sends to all connected clients. Use `conn.send()` to send events to a specific connection. See [Realtime](/docs/actors/events). + +### Actions + +- **Review action timeout configuration.** The default `actionTimeout` is 60 seconds. Increase it if you have long-running actions like API calls or file processing. See [Actor Configuration](/docs/general/actor-configuration). +- **Review message size limits.** The default `maxIncomingMessageSize` is 64 KiB and `maxOutgoingMessageSize` is 1 MiB. Increase if your actors send or receive large JSON payloads. See [Registry Configuration](/docs/general/registry-configuration). + +### Queues + +- **Review queue limits.** The default `maxQueueSize` is 1,000 messages and `maxQueueMessageSize` is 64 KiB. Increase if you expect burst traffic or large queue payloads. See [Actor Configuration](/docs/general/actor-configuration). +- **Ensure queue handlers are idempotent.** If processing fails before `message.complete()`, the message will be retried. See [Queues](/docs/actors/queues). + +### Workflows + +- **Verify workflows do not generate infinite steps.** Use `ctx.loop` to avoid creating unbounded step histories. See [Workflows](/docs/actors/workflows). + +## Security + +### Authentication + +- **Validate connections in `createConnState` or `onBeforeConnect`.** Do not trust client input without validation. See [Authentication](/docs/actors/authentication). + +### CORS + +- **Configure CORS for production.** Restrict allowed origins instead of allowing all. See [CORS](/docs/general/cors). + +### Tokens (Rivet Cloud) + +- **Use `pk_*` tokens for `RIVET_PUBLIC_ENDPOINT`.** Public tokens are safe to expose to clients. +- **Use `sk_*` tokens for `RIVET_ENDPOINT`.** Secret tokens should only be used server-side. +- **Do not leak your secret token.** Never expose `sk_*` tokens in client-side code, public repositories, or browser environments. See [Endpoints](/docs/general/endpoints). +- **Verify you're connecting to the correct region.** Use the nearest datacenter endpoint (e.g. `api-us-west-1.rivet.dev`) for lowest latency. + +### Access Control + +Access control is only needed if you want granular permissions for different clients. For most use cases, basic authentication in `onBeforeConnect` or `createConnState` is sufficient. + +- **Use deny-by-default rules.** Reject unknown roles in `onBeforeConnect`, action handlers, `canPublish`, and `canSubscribe`. See [Access Control](/docs/actors/access-control). +- **Authorize actions explicitly.** Check the caller's role in each action handler and throw `forbidden` for unauthorized access. +- **Gate event subscriptions and queue publishes.** Use `canSubscribe` and `canPublish` hooks to restrict which clients can subscribe to events or publish to queues. + +## Clients + +- **Dispose connections and/or client when not in use (JavaScript client).** Call `conn.dispose()` or `client.dispose()` when no longer needed to free resources. React and SwiftUI clients handle this automatically. See [Connection Lifecycle](/docs/clients/javascript#connection-lifecycle). + +_Source doc path: /docs/general/production-checklist_ diff --git a/.agents/skills/ai-agent-workspace/reference/general/registry-configuration.md b/.agents/skills/ai-agent-workspace/reference/general/registry-configuration.md new file mode 100644 index 0000000..90b48b4 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/general/registry-configuration.md @@ -0,0 +1,106 @@ +# Registry Configuration + +> Source: `src/content/docs/general/registry-configuration.mdx` +> Canonical URL: https://rivet.dev/docs/general/registry-configuration +> Description: This page documents the configuration options available when setting up a RivetKit registry. The registry configuration is passed to the `setup()` function. + +--- +## Example Configurations + +### Basic Setup + +```typescript +import { setup, actor } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); + +const registry = setup({ + use: { myActor }, +}); +``` + +### Connecting to Rivet Engine + +```typescript Environment-Variables +import { setup, actor } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); + +// Reads from RIVET_ENDPOINT, RIVET_TOKEN, and RIVET_NAMESPACE +const registry = setup({ + use: { myActor }, +}); +``` + +```typescript Config +import { setup, actor } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); + +const registry = setup({ + use: { myActor }, + endpoint: "https://api.rivet.dev", + token: process.env.RIVET_TOKEN, + namespace: "production", +}); +``` + +## Starting Your App + +After configuring your registry, start it: + +```typescript registry.start() +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +registry.start(); +``` + +```typescript Serverless +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +export default registry.serve(); +``` + +```typescript Serverless-with-Router +import { Hono } from "hono"; +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +const app = new Hono(); +app.all("/api/rivet/*", (c) => registry.handler(c.req.raw)); + +export default app; +``` + +```typescript Envoy +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +registry.startEnvoy(); +``` + +See [Runtime Modes](/docs/general/runtime-modes) for details on when to use each mode. + +## Environment Variables + +Many configuration options can be set via environment variables. See [Environment Variables](/docs/general/environment-variables) for a complete reference. + +## Configuration Reference + +## Related + +- [Actor Configuration](/docs/general/actor-configuration): Configure individual actors +- [HTTP Server Setup](/docs/general/http-server): Set up HTTP routing and middleware +- [Architecture](/docs/general/architecture): Understand how RivetKit works + +_Source doc path: /docs/general/registry-configuration_ diff --git a/.agents/skills/ai-agent-workspace/reference/general/runtime-modes.md b/.agents/skills/ai-agent-workspace/reference/general/runtime-modes.md new file mode 100644 index 0000000..9255278 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/general/runtime-modes.md @@ -0,0 +1,143 @@ +# Runtime Modes + +> Source: `src/content/docs/general/runtime-modes.mdx` +> Canonical URL: https://rivet.dev/docs/general/runtime-modes +> Description: RivetKit supports two runtime modes for running your actors: + +--- +- **Serverless**: Default mode. Responds to HTTP requests and scales automatically. +- **Runners**: Background processes without HTTP endpoints. Only needed for advanced scenarios. + +## Serverless + +Serverless is the default and recommended mode. Rivet sends HTTP requests to your backend to run actor logic, allowing your infrastructure to scale automatically. + +### Benefits + +- **Platform support**: Works with serverless platforms (Vercel, Cloudflare Workers, etc.) +- **Scale to zero**: No cost when idle +- **Edge deployments**: Easier to deploy to edge locations +- **Preview deployments**: Integrates with preview deployments on platforms like Vercel and Railway +- **Efficient autoscaling**: Request-based autoscaling can be faster and more efficient than CPU-based autoscaling depending on the platform + +### Example + +```typescript Direct +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +export default registry.serve(); +``` + +```typescript With-Router +import { Hono } from "hono"; +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +const app = new Hono(); +app.all("/api/rivet/*", (c) => registry.handler(c.req.raw)); + +export default app; +``` + +See [Server Setup](/docs/general/http-server/) for more configuration options. + +### Architecture + +When a client creates an actor, it sends a request to the Rivet Engine. The engine then calls `GET /api/rivet/start` on your serverless backend to run the actor. + +Serverless architecture diagram + +### Advanced + +#### Endpoints + +Rivet exposes the following endpoints: + +- `GET /api/rivet/metadata`: Validates configuration +- `GET /api/rivet/start`: Runs an actor + +You should never call these endpoints yourself, this is included purely for comprehension of how Rivet works under the hood. + +#### Timeouts + +Serverless platforms like Vercel have function timeouts. Rivet handles this automatically by migrating actors between function invocations, preserving state through `ctx.state`. Write your code as if it runs forever, Rivet handles the rest. + +Read more about [how we handle timeouts](/blog/2025-10-20-how-we-built-websocket-servers-for-vercel-functions/#timeouts-and-failover). + +#### Shutdown Sequence + +Each serverless request has a configurable lifespan (`requestLifespan`, default: 60 minutes). Set this to match your platform's function timeout (e.g. `requestLifespan: 3600` for Vercel Pro). + +When the request nears its lifespan, the engine reserves a grace period (`serverless_drain_grace_period`, default: 10 seconds) at the end to gracefully stop actors. For example, with a 3600-second lifespan, actors begin stopping at 3590 seconds. After the full lifespan elapses, the connection is forcibly closed and any remaining actors are rescheduled. + +See [Limits](/docs/actors/limits#serverless-shutdown) for configuration details. + +## Runners + +Runners run actors as long-running background processes without exposing an HTTP endpoint. + +### When to Use Runners + +- **No HTTP server**: Your app does not or cannot expose an HTTP server +- **No load balancer**: You don't have a load balancer to distribute HTTP requests across your servers +- **Custom scaling**: You have custom scaling requirements + +### Example + +```typescript runner.ts +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +registry.startEnvoy(); +``` + +The runner runs in the background, ready to run actors. + +### Architecture + +On startup, your backend calls `registry.startEnvoy()` which opens a persistent connection to the Rivet Engine. When a client creates an actor, the engine sends a command through this connection to start the actor on your backend. + +Runners architecture diagram + +### Configuration + +#### Runner Pool + +Use `RIVET_RUNNER` to assign runners to a pool. This lets you control which runners handle specific actors. + +```bash +RIVET_RUNNER=gpu-workers +``` + +```typescript +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); + +const registry = setup({ + use: { myActor }, + envoy: { + poolName: "gpu-workers", + }, +}); +``` + +See [Pool Configuration](/docs/general/pool-configuration) for how pools are scaled, drained on version upgrades, and rate-limited during actor eviction. + +## Comparison + +| Mode | Method | Use Case | +|------|--------|----------| +| Auto | `registry.start()` | Simplest setup. Starts server, serves static files, and runs actors. | +| Serverless | `registry.serve()` | Fetch handler for serverless platforms | +| Serverless | `registry.handler()` | Integrating with existing routers (Hono, Elysia, etc.) | +| Runner | `registry.startEnvoy()` | Long-running processes without HTTP endpoints | + +_Source doc path: /docs/general/runtime-modes_ diff --git a/.agents/skills/ai-agent-workspace/reference/general/wasm-vs-native-sdk.md b/.agents/skills/ai-agent-workspace/reference/general/wasm-vs-native-sdk.md new file mode 100644 index 0000000..79fe29d --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/general/wasm-vs-native-sdk.md @@ -0,0 +1,87 @@ +# WASM vs Native SDK + +> Source: `src/content/docs/general/wasm-vs-native-sdk.mdx` +> Canonical URL: https://rivet.dev/docs/general/wasm-vs-native-sdk +> Description: RivetKit runs your actors on a native or a WebAssembly runtime depending on your platform. + +--- +RivetKit ships two runtimes for executing actor logic. Most projects use the +native runtime automatically. Edge and serverless platforms that cannot run +native binaries use the WebAssembly runtime. + +- **Native**: Default. Runs on Node.js and Bun via native bindings. Best performance. +- **WebAssembly (wasm)**: Runs anywhere a `WebAssembly.Module` can be instantiated, including Cloudflare Workers, Supabase Edge Functions, and Deno Deploy. + +## Native runtime + +The native runtime is the default and requires no configuration. It loads +platform-specific native bindings for the best performance and full feature +support on Node.js and Bun. + +```typescript +import { actor, setup } from "rivetkit"; + +const counter = actor({ state: { count: 0 }, actions: {} }); + +const registry = setup({ use: { counter } }); +``` + +## WebAssembly runtime + +Edge platforms run on isolates (V8, Deno) that cannot load native binaries, so +RivetKit provides a WebAssembly build of its core runtime in the +`@rivetkit/rivetkit-wasm` package. You select it with `runtime: "wasm"` and pass +the wasm bindings and binary through the `wasm` option. + +### Recommended: use a platform package + +For supported platforms, use the dedicated package instead of wiring the wasm +runtime by hand. They install the wasm runtime, load the binary, and (on +Cloudflare) provide the outbound WebSocket the engine tunnel needs. + +- **Cloudflare Workers**: [`@rivetkit/cloudflare-workers`](/docs/actors/quickstart/cloudflare) +- **Supabase Edge Functions**: [`@rivetkit/supabase`](/docs/actors/quickstart/supabase) + +```typescript @nocheck +// Cloudflare Workers +import { actor } from "rivetkit"; +import { createHandler } from "@rivetkit/cloudflare-workers"; + +const counter = actor({ state: { count: 0 }, actions: {} }); + +export default createHandler({ use: { counter } }); +``` + +### Manual configuration + +For platforms without a dedicated package, configure the wasm runtime directly. +Pass the bindings from `@rivetkit/rivetkit-wasm` and the wasm binary as +`initInput`. `initInput` accepts a `Uint8Array`, `URL`, `Response`, or a +`WebAssembly.Module`. + +```typescript @nocheck +import { actor, setup } from "rivetkit"; +import * as wasmBindings from "@rivetkit/rivetkit-wasm"; +import wasmModule from "@rivetkit/rivetkit-wasm/rivetkit_wasm_bg.wasm"; + +const counter = actor({ state: { count: 0 }, actions: {} }); + +const registry = setup({ + runtime: "wasm", + wasm: { bindings: wasmBindings, initInput: wasmModule }, + use: { counter }, +}); +``` + +On platforms without an outbound `new WebSocket(url)` constructor (such as +Cloudflare Workers), you must also install a fetch-based `globalThis.WebSocket` +shim so the actor can open its tunnel to the engine. The platform packages handle +this for you, which is why they are recommended. + +## Related + +- [Runtime Modes](/docs/general/runtime-modes) +- [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) +- [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) + +_Source doc path: /docs/general/wasm-vs-native-sdk_ diff --git a/.agents/skills/ai-agent-workspace/reference/self-hosting/configuration.md b/.agents/skills/ai-agent-workspace/reference/self-hosting/configuration.md new file mode 100644 index 0000000..85a1d30 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/self-hosting/configuration.md @@ -0,0 +1,74 @@ +# Configuration + +> Source: `src/content/docs/self-hosting/configuration.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/configuration +> Description: Rivet Engine can be configured through environment variables or configuration files. + +--- +The full JSON Schema for the configuration is available at [/docs/engine-config-schema.json](/docs/engine-config-schema.json). + +## Configuration Sources + +Rivet supports JSON, JSON5, JSONC, YAML, YML, and environment variable configurations. + +**Environment Variables** + +Use the `RIVET__` prefix with `__` as separator to configure properties in the config. For example: set the `RIVET__database__postgres__url` environment variable for `database.postgres.url`. + +**Configuration Paths** + +Configuration files are automatically discovered in platform-specific directories: + +- Linux: `/etc/rivet/config.json` +- macOS: `/Library/Application Support/rivet/config.json` +- Windows: `C:\ProgramData\rivet\config.json` + +**Multiple Files** + +Multiple configuration files in the same directory are loaded and merged together. For example: `/etc/rivet/config.json` and `/etc/rivet/database.json` will be merged together. + +**Override Configuration Path** + +You can override the default configuration path using the `--config` flag: + +```bash +# Load from a specific file +rivet-engine --config /path/to/config.json + +# Load from a directory +rivet-engine --config /etc/rivet + +# Load multiple paths (merged in order) +rivet-engine --config /etc/rivet/base.json --config /etc/rivet/override.json +``` + +## Configuration Reference + +### Pegboard Envoy Load Balancing + +`pegboard.envoy_load_balancer` supports the `hash` strategy for hash-ring-based envoy selection: + +```json +{ + "pegboard": { + "envoy_load_balancer": { + "hash": { + "virtual_nodes": 8, + "samples": 2, + "max_scan": 16, + "use_snapshot_read": true + } + } + } +} +``` + +Use `samples: 1` for a uniform random pick that skips slot reads. Use `samples >= 2` for power-of-K choices over envoy slot counts. Treat `virtual_nodes` as an operational invariant once envoys have registered. + +## Related + +- SQLite actor startup picks the storage schema by probing the actor KV subspace for legacy v1 data. Existing v1 data stays on v1, and actors without v1 data start on v2. +- [PostgreSQL](/docs/self-hosting/postgres): Configure the experimental PostgreSQL backend +- [File System](/docs/self-hosting/filesystem): Configure file system storage for development + +_Source doc path: /docs/self-hosting/configuration_ diff --git a/.agents/skills/ai-agent-workspace/reference/self-hosting/docker-compose.md b/.agents/skills/ai-agent-workspace/reference/self-hosting/docker-compose.md new file mode 100644 index 0000000..8f2cea1 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/self-hosting/docker-compose.md @@ -0,0 +1,188 @@ +# Docker Compose + +> Source: `src/content/docs/self-hosting/docker-compose.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/docker-compose +> Description: Deploy Rivet Engine with docker-compose for multi-container setups. + +--- +## Quick Start + +### Create docker-compose.yaml + +Create a `docker-compose.yaml` in your project root: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - rivet-data:/data + environment: + RIVET__FILE_SYSTEM__PATH: "/data" + restart: unless-stopped + +volumes: + rivet-data: +``` + +### Start the engine + +```bash +docker-compose up -d +``` + +## Connecting Your Project + +Once the engine is running, add your app as a service in the same Compose file. + +### Create your server + +Follow the [quickstart](/docs/actors/quickstart/backend) to create a working server with actors. + +### Create a Dockerfile + +Create a `Dockerfile` in your project root: + +```dockerfile @nocheck +FROM node:22-slim +WORKDIR /app +COPY package.json pnpm-lock.yaml ./ +RUN corepack enable && pnpm install --frozen-lockfile +COPY . . +RUN pnpm build +CMD ["node", "dist/index.js"] +``` + +### Add your app to docker-compose.yaml + +Update your `docker-compose.yaml` to include your app alongside the engine: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - rivet-data:/data + environment: + RIVET__FILE_SYSTEM__PATH: "/data" + restart: unless-stopped + + my-app: + build: . + environment: + RIVET_ENDPOINT: "http://default:admin@rivet-engine:6420" + depends_on: + - rivet-engine + restart: unless-stopped + +volumes: + rivet-data: +``` + +`RIVET_ENDPOINT` tells your app to connect to the engine as a runner instead of running standalone. The URL uses the format `http://namespace:token@host:port`. Inside the Docker network, your app reaches the engine at `rivet-engine:6420`. See [Endpoints](/docs/general/endpoints) for all options. + +### Start the services + +```bash +docker-compose up -d +``` + +### Register your runner with the engine + +### Dashboard + +1. Open the Rivet Engine dashboard at `http://localhost:6420`. +2. Enter your admin token when prompted. +3. In the namespace sidebar, click **Settings**. +4. Click **Add Provider**, then choose **Custom**. +5. Click **Next** (these settings can be changed later). +6. Click **Next** (you can safely skip the env ar step for Docker Compose). +5. Go to **Confirm Connection**, enter your app endpoint (`http://my-app:6420/api/rivet`), then click **Add**. + +### CLI (curl) + +Register your runner programmatically via the engine API: + +```bash @nocheck +curl -X PUT "http://localhost:6420/runner-configs/default?namespace=default" \ + -H "Content-Type: application/json" \ + -d '{ + "datacenters": { + "default": { + "normal": {} + } + } + }' +``` + +## Configuration + +### Config File + +Mount a JSON configuration file in your `docker-compose.yaml`: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - ./rivet-config.json:/etc/rivet/config.json:ro + - rivet-data:/data + restart: unless-stopped + +volumes: + rivet-data: +``` + +Create `rivet-config.json` in the same directory as your `docker-compose.yaml`. See the [Configuration](/docs/self-hosting/configuration) docs for all available options and the full [JSON Schema](/docs/engine-config-schema.json). + +```json +{ + "postgres": { + "url": "postgresql://rivet:password@postgres:5432/rivet" + } +} +``` + +### Postgres Setup + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +```yaml +services: + postgres: + image: postgres:15 + environment: + POSTGRES_DB: rivet + POSTGRES_USER: rivet + POSTGRES_PASSWORD: rivet_password + volumes: + - postgres-data:/var/lib/postgresql/data + restart: unless-stopped + + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + environment: + RIVET__POSTGRES__URL: postgresql://rivet:rivet_password@postgres:5432/rivet + depends_on: + - postgres + restart: unless-stopped + +volumes: + postgres-data: +``` + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/docker-compose_ diff --git a/.agents/skills/ai-agent-workspace/reference/self-hosting/docker-container.md b/.agents/skills/ai-agent-workspace/reference/self-hosting/docker-container.md new file mode 100644 index 0000000..e6983ae --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/self-hosting/docker-container.md @@ -0,0 +1,150 @@ +# Docker Container + +> Source: `src/content/docs/self-hosting/docker-container.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/docker-container +> Description: Run Rivet Engine in a single Docker container. + +--- +## Quick Start + +### Start the engine + +```bash +docker run -d \ + --name rivet-engine \ + -p 6420:6420 \ + -v rivet-data:/data \ + -e RIVET__FILE_SYSTEM__PATH="/data" \ + rivetdev/engine:latest +``` + +### Verify the engine is running + +```bash +curl http://localhost:6420/health +``` + +## Connecting Your Project + +Once the engine is running, connect your app to it. + +### Create your server + +Follow the [quickstart](/docs/actors/quickstart/backend) to create a working server with actors. + +### Start your app with RIVET_ENDPOINT + +Set `RIVET_ENDPOINT` to tell your app to connect to the engine as a runner instead of running standalone: + +```bash @nocheck +RIVET_ENDPOINT="http://default:admin@host.docker.internal:6420" npm start +``` + +If running your app outside of Docker, use `localhost` instead of `host.docker.internal`: + +```bash @nocheck +RIVET_ENDPOINT="http://default:admin@localhost:6420" npm start +``` + +See [Endpoints](/docs/general/endpoints) for all options. + +### Register your runner with the engine + +### Dashboard + +1. Open the Rivet Engine dashboard at `http://localhost:6420`. +2. Enter your admin token when prompted. +3. In the namespace sidebar, click **Settings**. +4. Click **Add Provider**, then choose **Custom**. +5. Click **Next**. +6. Go to **Confirm Connection**, enter your app endpoint, then click **Add**. + +### CLI (curl) + +Register your runner programmatically via the engine API: + +```bash @nocheck +curl -X PUT "http://localhost:6420/runner-configs/default?namespace=default" \ + -H "Content-Type: application/json" \ + -d '{ + "datacenters": { + "default": { + "normal": {} + } + } + }' +``` + +## Configuration + +### Environment Variables + +Configure Rivet using environment variables: + +```bash +docker run -d \ + --name rivet-engine \ + -p 6420:6420 \ + -v rivet-data:/data \ + -e RIVET__FILE_SYSTEM__PATH="/data" \ + -e RIVET__POSTGRES__URL="postgresql://postgres:password@localhost:5432/db" \ + rivetdev/engine:latest +``` + +### Config File + +Mount a JSON configuration file: + +```bash +docker run -d \ + --name rivet-engine \ + -p 6420:6420 \ + -v rivet-data:/data \ + -v $(pwd)/rivet-config.json:/etc/rivet/config.json:ro \ + rivetdev/engine:latest +``` + +Create `rivet-config.json` in your working directory. See the [Configuration](/docs/self-hosting/configuration) docs for all available options and the full [JSON Schema](/docs/engine-config-schema.json). + +```json +{ + "postgres": { + "url": "postgresql://postgres:password@localhost:5432/db" + } +} +``` + +### Postgres Setup + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +```bash +# Create network +docker network create rivet-net + +# Run PostgreSQL +docker run -d \ + --name postgres \ + --network rivet-net \ + -e POSTGRES_DB=rivet \ + -e POSTGRES_USER=rivet \ + -e POSTGRES_PASSWORD=rivet_password \ + -v postgres-data:/var/lib/postgresql/data \ + postgres:15 + +# Run Rivet Engine +docker run -d \ + --name rivet-engine \ + --network rivet-net \ + -p 6420:6420 \ + -e RIVET__POSTGRES__URL="postgresql://rivet:rivet_password@postgres:5432/rivet" \ + rivetdev/engine +``` + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- Use [Docker Compose](/docs/self-hosting/docker-compose) for multi-container setups +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/docker-container_ diff --git a/.agents/skills/ai-agent-workspace/reference/self-hosting/filesystem.md b/.agents/skills/ai-agent-workspace/reference/self-hosting/filesystem.md new file mode 100644 index 0000000..30f7bdb --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/self-hosting/filesystem.md @@ -0,0 +1,47 @@ +# File System + +> Source: `src/content/docs/self-hosting/filesystem.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/filesystem +> Description: The file system backend stores all data on the local disk. This is suitable for single-node deployments, development, and testing. + +--- +For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based); for multi-node deployments, PostgreSQL is the recommended backend today but remains experimental as we evaluate the best fit for scalability and performance, and Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB. + +## Configuration + +```json Configuration-file +{ + "database": { + "file_system": { + "path": "/var/lib/rivet/data" + } + } +} +``` + +```bash Environment-variables +RIVET__database__file_system__path="/var/lib/rivet/data" +``` + +## Default Paths + +If no path is specified, Rivet uses platform-specific default locations: + +- Linux: `~/.local/share/rivet-engine/db` +- macOS: `~/Library/Application Support/rivet-engine/db` +- Windows: `%APPDATA%\rivet-engine\db` + +When running in a container or as a service, the path defaults to `./data/db` relative to the working directory. + +## When to Use File System + +The file system backend is ideal for: + +- Local development +- Single-node deployments +- Testing and prototyping +- Air-gapped environments without database infrastructure + +If you need a production-ready Rivet deployment today, use this backend for smaller single-node setups; for multi-node deployments, PostgreSQL is the recommended backend today though still experimental, and Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +_Source doc path: /docs/self-hosting/filesystem_ diff --git a/.agents/skills/ai-agent-workspace/reference/self-hosting/foundationdb.md b/.agents/skills/ai-agent-workspace/reference/self-hosting/foundationdb.md new file mode 100644 index 0000000..b8331bb --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/self-hosting/foundationdb.md @@ -0,0 +1,35 @@ +# FoundationDB (Enterprise) + +> Source: `src/content/docs/self-hosting/foundationdb.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/foundationdb +> Description: FoundationDB is the recommended storage backend for scalable production Rivet deployments. + +--- +FoundationDB requires an enterprise license. Contact [enterprise support](https://rivet.dev/sales) for setup guidance and access. + +## Overview + +FoundationDB is the recommended storage backend for scalable, production-ready Rivet deployments. It is a distributed, ordered key-value store originally built by Apple. + +FoundationDB powers some of the largest infrastructure in the world: + +- **Apple**: iCloud and other Apple services +- **Snowflake**: Cloud data platform metadata layer +- **Datadog**: Observability and monitoring platform +- **Tigris Data**: Globally distributed object storage + +Its strict serializability guarantees, fault tolerance, and ability to scale linearly across nodes make it the ideal backend for Rivet's actor state and orchestration layer. + +## Why FoundationDB + +| | RocksDB (File System) | PostgreSQL | FoundationDB | +|---|---|---|---| +| **Scalability** | Single node | Primary/replica failover | Linear horizontal scaling | +| **Fault tolerance** | None | Primary/replica failover | Automatic recovery with no data loss | +| **Production readiness** | Development and small deployments | Experimental for multi-node | Battle-tested at global scale | + +## Getting Started + +FoundationDB configuration and cluster setup are handled as part of enterprise onboarding. Contact [enterprise support](https://rivet.dev/sales) to get started. + +_Source doc path: /docs/self-hosting/foundationdb_ diff --git a/.agents/skills/ai-agent-workspace/reference/self-hosting/install.md b/.agents/skills/ai-agent-workspace/reference/self-hosting/install.md new file mode 100644 index 0000000..344be8e --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/self-hosting/install.md @@ -0,0 +1,32 @@ +# Installing Rivet Engine + +> Source: `src/content/docs/self-hosting/install.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/install +> Description: Install Rivet Engine using Docker, binaries, or a source build. + +--- +For more options: + +- [Docker Container](/docs/self-hosting/docker-container) for persistent storage, configuration, and production setups +- [Docker Compose](/docs/self-hosting/docker-compose) for multi-container deployments with PostgreSQL + +## Docker + +```bash +docker run -p 6420:6420 rivetdev/engine +``` + +## Prebuilt Binaries + + Prebuilt binaries coming soon + +## Build From Source + +```bash +git clone https://github.com/rivet-dev/rivet.git +cd rivet +cargo build --release -p rivet-engine +./target/release/rivet-engine +``` + +_Source doc path: /docs/self-hosting/install_ diff --git a/.agents/skills/ai-agent-workspace/reference/self-hosting/kubernetes.md b/.agents/skills/ai-agent-workspace/reference/self-hosting/kubernetes.md new file mode 100644 index 0000000..a2c619c --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/self-hosting/kubernetes.md @@ -0,0 +1,236 @@ +# Kubernetes + +> Source: `src/content/docs/self-hosting/kubernetes.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/kubernetes +> Description: Deploy production-ready Rivet Engine to Kubernetes with PostgreSQL storage. + +--- +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Prerequisites + +- Kubernetes cluster +- `kubectl` configured +- [Metrics server](https://github.com/kubernetes-sigs/metrics-server) (required for HPA) — included by default in most distributions (k3d, GKE, EKS, AKS) + +## Deploy Rivet Engine + + +### Download Manifests + + Download the `self-host/k8s/engine` directory from the Rivet repository: + + ```bash + npx giget@latest gh:rivet-dev/rivet/self-host/k8s/engine rivet-k8s + cd rivet-k8s + ``` + + + +### Configure Engine + + In `02-engine-configmap.yaml`, set `public_url` to your engine's external URL. + + + +### Configure PostgreSQL + + In `11-postgres-secret.yaml`, update the PostgreSQL password. See [Using a Managed PostgreSQL Service](#using-a-managed-postgresql-service) for external databases. + + + +### Configure Admin Token + + Generate a secure admin token and save it somewhere safe: + + ```bash + openssl rand -hex 32 + ``` + + Create the namespace and store the token as a Kubernetes secret: + + ```bash + kubectl create namespace rivet-engine + kubectl -n rivet-engine create secret generic rivet-secrets --from-literal=admin-token=YOUR_TOKEN_HERE + ``` + + + +### Deploy + + ```bash + # Apply all manifests + kubectl apply -f . + + # Wait for all pods to be ready + kubectl -n rivet-engine wait --for=condition=ready pod -l app=nats --timeout=300s + kubectl -n rivet-engine wait --for=condition=ready pod -l app=postgres --timeout=300s + kubectl -n rivet-engine wait --for=condition=ready pod -l app=rivet-engine --timeout=300s + + # Verify all pods are running + kubectl -n rivet-engine get pods + ``` + + + +### Access the Engine + + Visit `/ui` on your `public_url` to access the dashboard. + + +## Connecting Your Project + +### Create your server + +Follow the [quickstart](/docs/actors/quickstart/backend) to create a working server with actors. + +### Create Kubernetes manifests + +Create these manifest files for your app: + +```yaml deployment.yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: rivetkit-app + namespace: your-namespace +spec: + replicas: 1 + selector: + matchLabels: + app: rivetkit-app + template: + metadata: + labels: + app: rivetkit-app + spec: + # Allow enough time for actors to gracefully stop on SIGTERM. + # The runner waits up to 30m for actors to finish. + # Add buffer for runner shutdown overhead after actors stop. + # See: /docs/actors/versions#graceful-shutdown-sigterm + terminationGracePeriodSeconds: 2100 + containers: + - name: rivetkit-app + image: registry.example.com/your-team/rivetkit-app:latest + envFrom: + - secretRef: + name: rivetkit-secrets +``` + +```yaml service.yaml +apiVersion: v1 +kind: Service +metadata: + name: rivetkit-app + namespace: your-namespace +spec: + selector: + app: rivetkit-app + ports: + - name: http + port: 8080 + targetPort: 8080 +``` + +### Configure the endpoint + +Create `rivetkit-secrets.yaml` with `RIVET_ENDPOINT` pointing to the engine. This tells your app to connect as a runner instead of running standalone. See [Endpoints](/docs/general/endpoints) for all options. + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: rivetkit-secrets + namespace: your-namespace +type: Opaque +stringData: + RIVET_ENDPOINT: http://my-app:your-admin-token@your-engine.example.com +``` + +### Deploy your app + +```bash +kubectl apply -f rivetkit-secrets.yaml +kubectl apply -f deployment.yaml +kubectl apply -f service.yaml +``` + +### Register your runner with the engine + +### Dashboard + +1. Open the Rivet Engine dashboard in your browser. +2. Enter your admin token when prompted. +3. In the namespace sidebar, click **Settings**. +4. Click **Add Provider**, then choose **Custom**. +5. Click **Next**. +6. Go to **Confirm Connection**, enter your app endpoint (e.g. `http://rivetkit-app.your-namespace:8080/api/rivet`), then click **Add**. + +### CLI (curl) + +Register your runner programmatically via the engine API: + +```bash @nocheck +curl -X PUT "https://your-engine.example.com/runner-configs/default?namespace=default" \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer your-admin-token" \ + -d '{ + "datacenters": { + "default": { + "normal": {} + } + } + }' +``` + +## Advanced + +### Using a Managed PostgreSQL Service + +If you prefer to use a managed PostgreSQL service (e.g. Amazon RDS, Cloud SQL, Azure Database) instead of the bundled Postgres deployment: + +- Update the `postgres.url` connection string in `02-engine-configmap.yaml` to point to your managed instance +- Delete the bundled PostgreSQL manifests: + - `10-postgres-configmap.yaml` + - `11-postgres-secret.yaml` + - `12-postgres-statefulset.yaml` + - `13-postgres-service.yaml` + +### Applying Configuration Updates + +When making subsequent changes to `02-engine-configmap.yaml`, restart the engine pods to pick up the new configuration: + +```bash +kubectl apply -f 02-engine-configmap.yaml +kubectl -n rivet-engine rollout restart deployment/rivet-engine +``` + +### Ingress and Load Balancer Timeouts + +Rivet uses long-lived WebSocket connections for both client traffic (browsers, SDKs) and envoy traffic (actor hosts connecting back to the engine). Default Ingress and cloud load balancer idle timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +Raise the idle / read / send timeout on every Ingress and load balancer in front of the engine to at least 1 hour (`3600` seconds). Examples: + +- **NGINX Ingress** (annotations on the Ingress): + + ```yaml + nginx.ingress.kubernetes.io/proxy-read-timeout: "3600" + nginx.ingress.kubernetes.io/proxy-send-timeout: "3600" + ``` + +- **AWS Load Balancer Controller (ALB)**: + + ```yaml + alb.ingress.kubernetes.io/load-balancer-attributes: idle_timeout.timeout_seconds=3600 + ``` + +- **GCE Ingress (GKE)**: set `timeoutSec: 3600` on the `BackendConfig` referenced by the Service. + +The same guidance applies to the load balancer fronting your RivetKit app, since envoys connect to it over WebSocket. + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all engine config options + +_Source doc path: /docs/self-hosting/kubernetes_ diff --git a/.agents/skills/ai-agent-workspace/reference/self-hosting/multi-region.md b/.agents/skills/ai-agent-workspace/reference/self-hosting/multi-region.md new file mode 100644 index 0000000..2ecca85 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/self-hosting/multi-region.md @@ -0,0 +1,10 @@ +# Multi-Region + +> Source: `src/content/docs/self-hosting/multi-region.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/multi-region +> Description: Rivet Engine supports scaling transparently across multiple regions. + +--- +Documentation coming soon + +_Source doc path: /docs/self-hosting/multi-region_ diff --git a/.agents/skills/ai-agent-workspace/reference/self-hosting/postgres.md b/.agents/skills/ai-agent-workspace/reference/self-hosting/postgres.md new file mode 100644 index 0000000..e935246 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/self-hosting/postgres.md @@ -0,0 +1,192 @@ +# PostgreSQL + +> Source: `src/content/docs/self-hosting/postgres.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/postgres +> Description: Configure PostgreSQL for self-hosted Rivet deployments. + +--- +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Basic Configuration + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://user:password@host:5432/database" + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://user:password@host:5432/database" +``` + +## Managed Postgres Compatibility + +Some hosted PostgreSQL platforms require additional configuration due to platform-specific restrictions. + +### PlanetScale + +Use direct connection (not connection pooler). + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://pscale_api_.:@.pg.psdb.cloud:5432/postgres?sslmode=require", + "unstable_disable_lock_customization": true + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://pscale_api_.:@.pg.psdb.cloud:5432/postgres?sslmode=require" +RIVET__database__postgres__unstable_disable_lock_customization=true +``` + +### Supabase + +Use direct connection on port `5432` (not connection pooler). + +#### Without SSL + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=disable", + "unstable_disable_lock_customization": true + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=disable" +RIVET__database__postgres__unstable_disable_lock_customization=true +``` + +#### With SSL + +Download the root certificate from your Supabase dashboard and specify its path. See [Supabase SSL Enforcement](https://supabase.com/docs/guides/platform/ssl-enforcement) for details. + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=require", + "unstable_disable_lock_customization": true, + "ssl": { + "root_cert_path": "/path/to/supabase-ca.crt" + } + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=require" +RIVET__database__postgres__unstable_disable_lock_customization=true +RIVET__database__postgres__ssl__root_cert_path="/path/to/supabase-ca.crt" +``` + +## SSL/TLS Support + +To enable SSL for Postgres, add `sslmode=require` to your PostgreSQL connection URL: + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://user:password@host.example.com:5432/database?sslmode=require" + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://user:password@host.example.com:5432/database?sslmode=require" +``` + +The `sslmode` parameter controls TLS usage: + +- `disable`: Do not use TLS +- `prefer`: Use TLS if available, otherwise connect without TLS (default) +- `require`: Require TLS connection (fails if TLS is not available) + +To verify the server certificate against a CA or verify the hostname, use custom SSL certificates (see below). + +### Custom SSL Certificates + +For databases using custom certificate authorities (e.g., Supabase) or requiring client certificate authentication, you can specify certificate paths in the configuration: + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://user:password@host:5432/database?sslmode=require", + "ssl": { + "root_cert_path": "/path/to/root-ca.crt", + "client_cert_path": "/path/to/client.crt", + "client_key_path": "/path/to/client.key" + } + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://user:password@host:5432/database?sslmode=require" +RIVET__database__postgres__ssl__root_cert_path="/path/to/root-ca.crt" +RIVET__database__postgres__ssl__client_cert_path="/path/to/client.crt" +RIVET__database__postgres__ssl__client_key_path="/path/to/client.key" +``` + +| Parameter | Description | PostgreSQL Equivalent | +|-----------|-------------|----------------------| +| `root_cert_path` | Path to the root certificate file for verifying the server's certificate | `sslrootcert` | +| `client_cert_path` | Path to the client certificate file for client certificate authentication | `sslcert` | +| `client_key_path` | Path to the client private key file for client certificate authentication | `sslkey` | + +All SSL paths are optional. If not specified, Rivet uses the default system root certificates from Mozilla's root certificate store. + +## Do Not Use Connection Poolers + +Rivet requires direct PostgreSQL connections for session-level features and does not support connection poolers. + +Do not use: + +- PgBouncer +- Supavisor +- AWS RDS Proxy + +## Troubleshooting + +### Permission Denied Errors + +If you see errors like: + +``` +ERROR: permission denied to set parameter "deadlock_timeout" +ERROR: current transaction is aborted, commands ignored until end of transaction block +``` + +Add `unstable_disable_lock_customization: true` to your configuration: + +```json +{ + "database": { + "postgres": { + "url": "postgresql://...", + "unstable_disable_lock_customization": true + } + } +} +``` + +This disables Rivet's attempt to set `lock_timeout = 0` and `deadlock_timeout = 10ms`. Since `lock_timeout` defaults to `0` in PostgreSQL, skipping these settings is safe. Deadlock detection will use the default `1s` timeout instead of `10ms`. + +_Source doc path: /docs/self-hosting/postgres_ diff --git a/.agents/skills/ai-agent-workspace/reference/self-hosting/production-checklist.md b/.agents/skills/ai-agent-workspace/reference/self-hosting/production-checklist.md new file mode 100644 index 0000000..3cefa5a --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/self-hosting/production-checklist.md @@ -0,0 +1,53 @@ +# Production Checklist + +> Source: `src/content/docs/self-hosting/production-checklist.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/production-checklist +> Description: Checklist for deploying a self-hosted Rivet Engine to production. + +--- +We recommend passing this page to your coding agent to verify your configuration before deploying. + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +Also review the [general production checklist](/docs/general/production-checklist). + +## Security + +- **Validate that you have an admin token configured.** Generate a strong, random token for engine authentication. See [Configuration](/docs/self-hosting/configuration). +- **Verify your admin token is not exposed publicly.** Do not include the admin token in `RIVET_PUBLIC_ENDPOINT` or anywhere accessible to clients. See [Endpoints](/docs/general/endpoints#public-endpoint). +- **Configure TLS termination.** Ensure connections to the engine are encrypted via a reverse proxy or load balancer. + +## Resources + +- **Set container resource limits.** Recommended at least 1 CPU and 2 GB of RAM per Rivet Engine instance. +- **Configure health checks.** Set up liveness and readiness probes on port `6421` at `/health`. Recommended timeout of 5 seconds. + +## Scaling + +- **Configure autoscaling for the Rivet Engine.** Set target CPU utilization to 70% and memory to 80% to ensure headroom for traffic spikes. In Kubernetes, this is configured via a Horizontal Pod Autoscaler (HPA). +- **Use 2+ engine nodes for redundancy.** Running a single engine node is a single point of failure. Deploy at least two engine instances behind a load balancer. +- **RocksDB only supports a single node.** Do not run multiple RocksDB nodes. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). For multi-node deployments, PostgreSQL is the recommended backend today, though it remains experimental as we evaluate the best fit for scalability and performance. +- **Validate the rate limit on your serverless actor host.** Actor start requests are sent from your engine instances, so they all originate from a small set of IPs. Per-IP rate limits on the actor host will throttle the engine before they would throttle end-user traffic. Size the limit to your peak actor create and wake rate, and configure platform max concurrency (e.g. on GCP Cloud Run) to match your expected concurrent actor count. + +## PostgreSQL + +- **PostgreSQL is recommended for multi-node deployments, but remains experimental.** Validate the deployment carefully before rollout. +- **Configure automated backups.** Set up regular backups for your PostgreSQL database to prevent data loss. +- **Configure failover.** Set up a standby replica with automatic failover to ensure high availability. +- **Use FoundationDB for the most scalable production-ready deployments.** FoundationDB provides the best performance, scalability, and uptime for Rivet. Contact [enterprise support](https://rivet.dev/sales) for FoundationDB guidance. + +## NATS + +- **Use NATS for pub/sub (recommended).** By default, Rivet uses PostgreSQL `LISTEN`/`NOTIFY` for pub/sub which has limited throughput. NATS significantly improves performance for high-traffic deployments. This is not needed if using RocksDB. See [Configuration](/docs/self-hosting/configuration). +- **Deploy 2+ NATS replicas.** Run at least two NATS replicas for high availability. + +## Monitoring + +- **Configure OpenTelemetry.** The Rivet Engine supports exporting traces and metrics via OpenTelemetry. Set `RIVET_OTEL_ENABLED=1` and `RIVET_OTEL_GRPC_ENDPOINT` to your collector endpoint (defaults to `http://localhost:4317`). Adjust `RIVET_OTEL_SAMPLER_RATIO` to control trace sampling (defaults to `0.001`). See [Configuration](/docs/self-hosting/configuration). +- **Set up alerts for critical metrics.** Monitor engine CPU, memory, request latency, and error rates. Configure alerts to notify your team before issues become outages. + +## Enterprise + +- **Contact [enterprise support](https://rivet.dev/sales) for production-ready deployments.** We can help with architecture review, scaling guidance, and FoundationDB support. + +_Source doc path: /docs/self-hosting/production-checklist_ diff --git a/.agents/skills/ai-agent-workspace/reference/self-hosting/railway.md b/.agents/skills/ai-agent-workspace/reference/self-hosting/railway.md new file mode 100644 index 0000000..c4bb922 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/self-hosting/railway.md @@ -0,0 +1,99 @@ +# Railway Deployment + +> Source: `src/content/docs/self-hosting/railway.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/railway +> Description: Railway provides a simple platform for deploying Rivet Engine with automatic scaling and managed infrastructure. + +--- +## Video Tutorial + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Quick Deploy + +Choose the template that best fits your needs: + +| **Rivet Template** | **Rivet Starter** | +|-------------------|-------------------| +| [![Deploy on Railway](https://railway.com/button.svg)](https://railway.com/deploy/rivet?referralCode=RC7bza&utm_medium=integration&utm_source=template&utm_campaign=generic) | [![Deploy Rivet Starter](https://railway.com/button.svg)](https://railway.com/deploy/rivet-starter) | +| **Blank template** to start fresh | **Complete example** with chat app | +| - Rivet Engine | - Pre-configured Rivet Engine | +| - PostgreSQL database | - Example chat application with Actors | +| - Basic configuration | - PostgreSQL database | +| - Manual setup required | - Rivet Inspector for debugging | +| | - Ready to run immediately | + +You can also use the [Rivet Railway template](https://github.com/rivet-dev/template-railway) as a starting point for your application. + +After deploying either template, you can find the `RIVET__AUTH__ADMIN_TOKEN` under the **Variables** tab in the Railway dashboard. This token is required to access the Rivet Inspector. + +## Manual Deployment + +### Prerequisites + +1. [Railway account](https://railway.app) +2. [Railway CLI](https://docs.railway.app/develop/cli) (optional) + +### Step 1: Create New Project + +```bash +# Using Railway CLI +railway init + +# Or create via dashboard +# https://railway.app/new +``` + +### Step 2: Add Services + +#### Deploy PostgreSQL Database + +1. Click "New Service" → "Database" → "PostgreSQL" +2. Railway automatically provisions and configures PostgreSQL +3. Note the connection string from the service variables + +#### Deploy Rivet Engine + +1. Click "New Service" → "Docker Image" +2. Set image: `rivetdev/engine:latest` +3. Configure environment variables: + - `RIVET__POSTGRES__URL=${{Postgres.DATABASE_URL}}` +4. Configure graceful shutdown (see [Graceful Shutdown](#graceful-shutdown) below) + +### Step 3: Deploy Your Application + +Follow the [Railway Quick Start guide](https://docs.railway.com/quick-start) to deploy your repository: + +1. Connect your GitHub account to Railway +2. Select your repository containing your Rivet application +3. Railway will automatically detect and deploy your application +4. Configure environment variables for your application: + - `RIVET_ENDPOINT=${{Rivet.RAILWAY_PRIVATE_DOMAIN}}` - Points to the Rivet Engine service's private domain + +## WebSocket Timeouts + +Rivet uses long-lived WebSocket connections for both client traffic (browsers, SDKs) and envoy traffic (actor hosts connecting back to the engine). Railway's HTTP proxy supports WebSockets, but you must make sure no app-side timeout cuts them off. + +If you front the engine with your own reverse proxy (NGINX, Caddy, etc.) inside the Railway service, raise its idle / read timeout to at least 1 hour (`3600` seconds). The same guidance applies to the Railway service hosting your RivetKit app, since envoys connect to it over WebSocket. + +## Graceful Shutdown + +By default, Railway kills the old deploy 0 seconds after sending `SIGTERM` (see [Railway's docs](https://docs.railway.com/deployments/reference#singleton-deploys)), so in-flight requests are dropped and state flushes can be interrupted on every deploy. Rivet ships with a `SIGTERM` handler that drains cleanly, but it only gets to run if Railway is configured to give it time. + +Configure the following under **Settings → Deploy** on your service: + +- **Draining seconds** — the grace window between `SIGTERM` and `SIGKILL`. This is how long Rivet has to finish in-flight work and flush state. See [Railway's deployment teardown docs](https://docs.railway.com/deployments/deployment-teardown). + +Set draining seconds in the dashboard, via `drainingSeconds` in config-as-code, or via the `RAILWAY_DEPLOYMENT_DRAINING_SECONDS` service variable. A reasonable value is **60 seconds**. + +If your start command is a wrapper process (for example `npm start`, `yarn start`, `pnpm start`, or a shell script), the wrapper becomes PID 1 and swallows the signal — your app never drains and Railway force-kills it at the end of the window. + +- Invoke your binary directly as the start command (for example `node dist/index.js`, not `npm start`). +- Or run `dumb-init` / `tini` as PID 1 in your Dockerfile so signals forward to your process. + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/railway_ diff --git a/.agents/skills/ai-agent-workspace/reference/self-hosting/render.md b/.agents/skills/ai-agent-workspace/reference/self-hosting/render.md new file mode 100644 index 0000000..0bc6d6c --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/self-hosting/render.md @@ -0,0 +1,131 @@ +# Render Deployment + +> Source: `src/content/docs/self-hosting/render.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/render +> Description: Deploy Rivet Engine to Render with managed PostgreSQL and automatic HTTPS, using the experimental PostgreSQL backend. + +--- +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Prerequisites + +1. A [Render account](https://render.com) +2. A GitHub repository + +## Deploy Rivet Engine + + +### Create the Blueprint Files + + Add these three files to the root of your GitHub repository: + + **render.yaml** + + ```yaml + databases: + - name: rivet-db + plan: basic-256mb + databaseName: rivet + user: rivet + + services: + - type: web + name: rivet-engine + runtime: docker + dockerfilePath: ./Dockerfile.render + plan: starter + healthCheckPath: /health + envVars: + - key: DATABASE_URL + fromDatabase: + name: rivet-db + property: connectionString + - key: RIVET__AUTH__ADMIN_TOKEN + generateValue: true + ``` + + **Dockerfile.render** + + ```dockerfile + FROM rivetdev/engine:latest + + COPY entrypoint.render.sh /entrypoint.render.sh + RUN chmod +x /entrypoint.render.sh + + ENTRYPOINT ["/entrypoint.render.sh"] + ``` + + **entrypoint.render.sh** + + ```bash + #!/bin/sh + + if [ -n "$DATABASE_URL" ]; then + export RIVET__POSTGRES__URL="${DATABASE_URL}?sslmode=disable" + fi + + exec /usr/bin/rivet-engine start + ``` + + Commit and push these files to your repository. + + + +### Deploy to Render + + 1. Go to the [Render Dashboard](https://dashboard.render.com/) + 2. Click **Blueprints** in the left sidebar + 3. Click **New Blueprint Instance** + 4. Connect your GitHub account if you haven't already + 5. Select the repository containing the files from the previous step + 6. Click **Apply** + + Render will automatically create the PostgreSQL database and deploy the Rivet Engine. + + + +### Get Your Admin Token + + 1. Once deployed, go to your **rivet-engine** service in the Render Dashboard + 2. Click the **Environment** tab + 3. Find `RIVET__AUTH__ADMIN_TOKEN` and click the eye icon to reveal the value + 4. Copy this token — you'll need it to access the dashboard + + + +### Access the Rivet Dashboard + + Open your service URL in a browser: + + ``` + https://rivet-engine-xxxx.onrender.com/ui/ + ``` + + Replace `rivet-engine-xxxx` with your actual service name from the Render Dashboard. + + Enter the admin token from the previous step to log in. + + +## WebSocket Timeouts + +Rivet uses long-lived WebSocket connections for both client traffic (browsers, SDKs) and envoy traffic (actor hosts connecting back to the engine). Render's HTTP proxy supports WebSockets, but its default idle timeout will close connections that have no traffic for too long. + +If you front the engine with your own reverse proxy (NGINX, Caddy, etc.) on Render, raise its idle / read timeout to at least 1 hour (`3600` seconds). The same guidance applies to the Render service hosting your RivetKit app, since envoys connect to it over WebSocket. + +## Connecting Your Application + +To connect a RivetKit application to your self-hosted engine, set these environment variables in your app: + +```bash +RIVET_ENDPOINT=https://:@rivet-engine-xxxx.onrender.com +RIVET_PUBLIC_ENDPOINT=https://@rivet-engine-xxxx.onrender.com +``` + +See the [Connect guide](/docs/deploy/custom) for more details on connecting your application. + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/render_ diff --git a/.agents/skills/ai-agent-workspace/reference/self-hosting/tls.md b/.agents/skills/ai-agent-workspace/reference/self-hosting/tls.md new file mode 100644 index 0000000..63573d2 --- /dev/null +++ b/.agents/skills/ai-agent-workspace/reference/self-hosting/tls.md @@ -0,0 +1,22 @@ +# TLS & Certificates + +> Source: `src/content/docs/self-hosting/tls.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/tls +> Description: How Rivet validates TLS root certificates. + +--- +Public CAs (Let's Encrypt, AWS ACM, and so on) work out of the box. You only need to read this page if you're running behind a corporate or private CA. + +Rivet reads the operating system trust store (`/etc/ssl/certs` on Linux, Keychain on macOS, Schannel on Windows) for all outbound HTTPS. Operator-installed corporate CAs live there and are honored automatically. + +To trust a private CA inside the official `rivetdev/engine` image, extend it the standard Debian way: + +```dockerfile +FROM rivetdev/engine:latest +COPY my-corp-ca.crt /usr/local/share/ca-certificates/ +RUN update-ca-certificates +``` + +Rebuild and redeploy. The same approach works for any machine running a Rivet client: install the CA into the OS trust store and Rivet picks it up. + +_Source doc path: /docs/self-hosting/tls_ diff --git a/.agents/skills/ai-agent/BASE_SKILL.md b/.agents/skills/ai-agent/BASE_SKILL.md new file mode 100644 index 0000000..ca710ba --- /dev/null +++ b/.agents/skills/ai-agent/BASE_SKILL.md @@ -0,0 +1,537 @@ +--- +name: "rivetkit" +description: "RivetKit backend and Rivet Actor runtime guidance. Use for building, modifying, debugging, or testing Rivet Actors, registries, serverless/runner modes, deployment, or actor-based workflows." +--- + +# Rivet Actors + +Build high-performance, long-lived, in-memory processes on Rivet's actor runtime. Use this skill whenever HTTP endpoints, databases, or queues no longer meet the requirements for AI agents, realtime collaboration, workflow orchestration, or geo-distributed data. + +## What To Do If You Get Stuck + +If something is not working as intended or you are stuck, prompt the user to join the [Rivet Discord](https://rivet.dev/discord) or file an issue on the [Rivet GitHub](https://github.com/rivet-dev/rivet) to report an issue and get help. + +Provide the user with a pre-generated report with: + +- Symptoms + - If this is happening in local dev, deployed, or both + - The error you're seeing + - Relevant source code related to this +- What you've tried to solve it +- Environment + - RivetKit version + - Runtime (Node, Bun, etc) including version + - If applicable, provider in use (e.g. Vercel, Railway, etc) + - If applicable, HTTP router in use (e.g. Hono, Express, Elysia) + +## Debugging Actors + +Use the inspector HTTP API to examine running actors. These endpoints are accessible through the gateway at `/gateway/{actor_id}/inspector/*`. Key endpoints: + +- `GET /inspector/summary` - full actor snapshot (state, connections, RPCs, queue) +- `GET /inspector/state` / `PATCH /inspector/state` - read/write actor state +- `GET /inspector/connections` - active connections +- `GET /inspector/rpcs` - available actions +- `POST /inspector/action/{name}` - execute an action with `{"args": [...]}` +- `POST /inspector/database/execute` - run SQL with `{"sql": "...", "args": [...]}` or `{"sql": "...", "properties": {...}}` for reads or mutations +- `GET /inspector/queue?limit=50` - queue status +- `GET /inspector/traces?startMs=0&endMs=...&limit=1000` - trace spans (OTLP JSON) +- `GET /inspector/workflow-history` - workflow history and status as JSON (`nameRegistry`, `entries`, `entryMetadata`) +- `POST /inspector/workflow/replay` - replay a workflow from a specific step or from the beginning; returns `409 actor/workflow_in_flight` if the workflow is still running +- `GET /inspector/database/schema` - SQLite tables and views exposed by `c.db` +- `GET /inspector/database/rows?table=...&limit=100&offset=0` - paged SQLite rows for a table or view + +In local dev, no auth token is needed. In production, pass `Authorization: Bearer `, where the inspector token is the actor-specific token auto-generated on first start and persisted in the actor's internal KV at key `0x03`. The Rivet dashboard retrieves this token automatically; for direct API access, fetch it through the management KV endpoint. See the [debugging docs](https://rivet.dev/docs/actors/debugging) for details. + +## Citing Sources + +When providing information from Rivet documentation, cite the canonical URL so users can learn more. Each reference file includes its canonical URL in the header metadata. + +**How to cite:** + +- Use inline links for key concepts: "Use [actor keys](https://rivet.dev/docs/actors/keys) to uniquely identify instances." +- Add a "Learn more" link after explanations for complex topics + +**Finding canonical URLs:** + +The Reference Map below links to reference files. Each file's header contains: + +``` +> Canonical URL: https://rivet.dev/docs/actors/actions +``` + +Use that canonical URL when citing, not the reference file path. + +**Examples:** + +- Actions → `https://rivet.dev/docs/actors/actions` +- React client → `https://rivet.dev/docs/clients/react` +- Self-hosting on Kubernetes → `https://rivet.dev/docs/self-hosting/kubernetes` + +## Version Check + +Before starting any work, check if the user's project is on the latest version of RivetKit (latest: 2.3.4). Look at the `rivetkit` version in the user's `package.json` (check both `dependencies` and `devDependencies`). If the installed version is older than 2.3.4, inform the user and suggest upgrading: + +```bash +npm install rivetkit@2.3.4 +``` + +If the user also uses `@rivetkit/react`, `@rivetkit/next-js`, or other `@rivetkit/*` client packages, suggest upgrading those too. Outdated versions may have known bugs or missing features that cause issues. + +## First Steps + +1. Install RivetKit (latest: 2.3.4) + ```bash + npm install rivetkit@2.3.4 + ``` +2. Define a registry with `setup({ use: { /* actors */ } })`. +3. Call `registry.start()` to start the server. For custom HTTP server integration, use `registry.handler()` with a router like Hono. For serverless deployments, use `registry.serve()`. For runner-only mode, use `registry.startEnvoy()`. +4. Verify `/api/rivet/metadata` returns 200 before deploying. +5. Configure Rivet Cloud or self-hosted engine + - You must configure versioning for production builds. This is not needed for local development. See [Versions & Upgrades](https://rivet.dev/docs/actors/versions). +6. Integrate clients (see client guides below for JavaScript, React, or Swift) +7. Prompt the user if they want to deploy. If so, go to Deploying Rivet Backends. + +For more information, read the quickstart guide relevant to the user's project. + +## Project Setup + +### .gitignore + +Every RivetKit project should have a `.gitignore`. Include at minimum: + +``` +node_modules/ +dist/ +.env +``` + +### .dockerignore + +Every project with a Dockerfile should have a `.dockerignore` to keep the image small and avoid leaking secrets: + +``` +node_modules/ +dist/ +.env +.git/ +``` + +### Dockerfile + +Use this as a base Dockerfile for deploying a RivetKit project. The `RIVET_RUNNER_VERSION` build arg is only needed when self-hosting or using a custom runner (not needed for Rivet Compute). It lets Rivet track which version of the actor is running and drain old actors on deploy. See https://rivet.dev/docs/actors/versions for details. + +```dockerfile +FROM node:24-alpine + +ARG RIVET_RUNNER_VERSION +ENV RIVET_RUNNER_VERSION=$RIVET_RUNNER_VERSION + +WORKDIR /app + +COPY package.json package-lock.json ./ +RUN npm ci + +COPY . . +RUN npm run build --if-present + +CMD ["node", "dist/index.js"] +``` + +Build with: + +```bash +docker build --build-arg RIVET_RUNNER_VERSION=$(date +%s) . +``` + +Adjust the `CMD` to match the project's entry point. If the project uses a different output directory or start command, update accordingly. + +## Error Handling Policy + +- Prefer fail-fast behavior by default. +- Avoid `try/catch` unless it is required for a real recovery path, cleanup boundary, or to add actionable context. +- Never swallow errors. If you add a `catch`, you must handle the error explicitly, at minimum by logging it. +- When you cannot recover, log context and rethrow. + +## State vs Vars: Persistence Rules + +**`c.vars` is ephemeral.** Data in `c.vars` is lost on every restart, crash, upgrade, or sleep/wake cycle. Only use `c.vars` for non-serializable objects (e.g., physics engines, WebSocket references, event emitters, caches) or truly transient runtime data (e.g., current input direction that doesn't matter after disconnect). + +**Persistent storage options.** Any data that must survive restarts belongs in one of these, NOT in `c.vars`: + +- **`c.state`** — CBOR-serializable data for small, bounded datasets. Ideal for configuration, counters, small player lists, phase flags, etc. Keep under 128 KB. Do not store unbounded or growing data here (e.g., chat logs, event histories, spawned entity lists that grow without limit). State is read/written as a single blob on every persistence cycle. +- **`c.kv`** — Key-value store for unbounded data. This is what `c.state` uses under the hood. Supports binary values. Use for larger or variable-size data like user inventories, world chunks, file blobs, or any collection that may grow over time. Keys are scoped to the actor instance. +- **`c.db`** — SQLite database for structured or complex data. Use when you need queries, indexes, joins, aggregations, or relational modeling. Ideal for leaderboards, match histories, player pools, or any data that benefits from SQL. + +**Common mistake:** Storing meaningful game/application data in `c.vars` instead of persisting it. For example, if users can spawn objects in a physics simulation, the spawn definitions (position, size, type) must be persisted in `c.state` (or `c.kv` if unbounded), even though the physics engine handles (non-serializable) live in `c.vars`. On restart, `run()` should recreate the runtime objects from the persisted data. + +## Deploying Rivet Backends + +Assume the user is deploying to Rivet Cloud, unless otherwise specified. If user is self-hosting, read the self-hosting guides below. + +1. Verify that Rivet Actors are working in local dev +2. Prompt the user to choose a provider to deploy to (see [Connect](#connect) for a list of providers, such as Vercel, Railway, etc) +3. Follow the deploy guide for that given provider. You will need to instruct the user when you need manual intervention. + +## API Reference + +The RivetKit OpenAPI specification is available in the skill directory at `openapi.json`. This file documents all HTTP endpoints for managing actors. + +## Misc Notes + +- The Rivet domain is rivet.dev, not rivet.gg + +## TypeScript Caveat: Actor Client Inference + +- In multi-file TypeScript projects, bidirectional actor calls can create a circular type dependency when both actors use `c.client()`. +- Symptoms usually include `c.state` becoming `unknown`, actor methods becoming possibly `undefined`, or `TS2322` / `TS2722` errors after the first cross-actor call. +- If an action returns the result of another actor call, prefer an explicit return type annotation on that action instead of relying on inference through `c.client()`. +- If explicit return types are not enough, use a narrower client or registry type for only the actors that action needs. +- As a last resort, pass `unknown` for the registry type and be explicit that this gives up type safety at that call site. + +## Features + +- **Long-Lived, Stateful Compute**: Each unit of compute is like a tiny server that remembers things between requests – no need to re-fetch data from a database or worry about timeouts. Like AWS Lambda, but with memory and no timeouts. +- **Blazing-Fast Reads & Writes**: State is stored on the same machine as your compute, so reads and writes are ultra-fast. No database round trips, no latency spikes. State is persisted to Rivet for long term storage, so it survives server restarts. +- **Realtime**: Update state and broadcast changes in realtime with WebSockets. No external pub/sub systems, no polling – just built-in low-latency events. +- **Infinitely Scalable**: Automatically scale from zero to millions of concurrent actors. Pay only for what you use with instant scaling and no cold starts. +- **Fault Tolerant**: Built-in error handling and recovery. Actors automatically restart on failure while preserving state integrity and continuing operations. + +## When to Use Rivet Actors + +- **AI agents & sandboxes**: multi-step toolchains, conversation memory, sandbox orchestration. +- **Multiplayer or collaborative apps**: CRDT docs, shared cursors, realtime dashboards, chat. +- **Workflow automation**: background jobs, cron, rate limiters, durable queues, backpressure control. +- **Data-intensive backends**: geo-distributed or per-tenant databases, in-memory caches, sharded SQL. +- **Networking workloads**: WebSocket servers, custom protocols, local-first sync, edge fanout. + +## Minimal Project + +### Backend + +**index.ts** + +### Client Docs + +Use the client SDK that matches your app: + +- [JavaScript Client](/docs/clients/javascript) +- [React Client](/docs/clients/react) +- [Swift Client](/docs/clients/swift) + +## Actor Quick Reference + +### In-Memory State + +Persistent data that survives restarts, crashes, and deployments. State is persisted on Rivet Cloud or Rivet self-hosted, so it survives restarts if the current process crashes or exits. + +### Static Initial State + +### Dynamic Initial State + +[Documentation](/docs/actors/state) + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +[Documentation](/docs/actors/keys) + +### Input + +Pass initialization data when creating actors. Input is only available in `createState` and `onCreate`, so store it in state if you need it later. + +[Documentation](/docs/actors/input) + +### Temporary Variables + +Temporary data that doesn't survive restarts. Use for non-serializable objects (event emitters, connections, etc). + +### Static Initial Vars + +### Dynamic Initial Vars + +[Documentation](/docs/actors/state) + +### Actions + +Actions are the primary way clients and other actors communicate with an actor. + +[Documentation](/docs/actors/actions) + +### Events & Broadcasts + +Events enable real-time communication from actors to connected clients. + +[Documentation](/docs/actors/events) + +### Connections + +Access the current connection via `c.conn` or all connected clients via `c.conns`. Use `c.conn.id` or `c.conn.state` to securely identify who is calling an action. `c.conn` is only available for actions invoked through a connected client; stateless actor-handle calls run without a connection, so guard against that. Connection state is initialized via `connState` or `createConnState`, which receives parameters passed by the client on connect. + +### Static Connection Initial State + +### Dynamic Connection Initial State + +[Documentation](/docs/actors/connections) + +### Queues + +Use queues to process durable messages in order inside a `run` loop. + +[Documentation](/docs/actors/queues) + +### Workflows + +Use workflows when your `run` logic needs durable, replayable multi-step execution. + +[Documentation](/docs/actors/workflows) + +### Actor-to-Actor Communication + +Actors can call other actors using `c.client()`. + +[Documentation](/docs/actors/communicating-between-actors) + +### Scheduling + +Schedule actions to run after a delay or at a specific time. Schedules persist across restarts, upgrades, and crashes. + +[Documentation](/docs/actors/schedule) + +### Destroying Actors + +Permanently delete an actor and its state using `c.destroy()`. + +[Documentation](/docs/actors/destroy) + +### Lifecycle Hooks + +Actors support hooks for initialization, background processing, connections, networking, and state changes. Use `run` for long-lived background loops, and use `c.aborted` or `c.abortSignal` for graceful shutdown. + +[Documentation](/docs/actors/lifecycle) + +### Context Types + +When writing helper functions outside the actor definition, use `*ContextOf` to extract the correct context type. Helpers like `ActionContextOf`, `CreateContextOf`, `ConnContextOf`, and `ConnInitContextOf` are exported from `"rivetkit"`. Do not manually define your own context interface. Always derive it from the actor definition. + +[Documentation](/docs/actors/types) + +### Errors + +Use `UserError` to throw errors that are safely returned to clients. Pass `metadata` to include structured data. Other errors are converted to generic "internal error" for security. + +### Actor + +### Client + +[Documentation](/docs/actors/errors) + +### Low-Level HTTP & WebSocket Handlers + +For custom protocols or integrating libraries that need direct access to HTTP `Request`/`Response` or WebSocket connections, use `onRequest` and `onWebSocket`. + +[HTTP Handler Documentation](/docs/actors/request-handler) · [WebSocket Handler Documentation](/docs/actors/websocket-handler) + +### Icons & Names + +Customize how actors appear in the UI with display names and icons. It's recommended to always provide a name and icon to actors in order to make them easier to distinguish in the dashboard. + +```typescript +import { actor } from "rivetkit"; + +const chatRoom = actor({ + options: { + name: "Chat Room", + icon: "💬", // or FontAwesome: "comments", "chart-line", etc. + }, + // ... +}); +``` + +[Documentation](/docs/actors/appearance) + +## Client Documentation + +Find the full client guides here: + +- [JavaScript Client](/docs/clients/javascript) +- [React Client](/docs/clients/react) +- [Swift Client](/docs/clients/swift) + +## Common Patterns + +Actors scale naturally through isolated state and message-passing. Structure your applications with these patterns: + +[Documentation](/docs/actors/design-patterns) + +### Actor Per Entity + +Create one actor per user, document, or room. Use compound keys to scope entities: + +### Coordinator & Data Actors + +**Data actors** handle core logic (chat rooms, game sessions, user data). **Coordinator actors** track and manage collections of data actors—think of them as an index. + +### Run Loop + +Use a `run` loop for continuous background work inside an actor. Process queue messages in order, run logic on intervals, stream AI responses, or coordinate long-running tasks. + +### Workflow Loop + +Use this pattern for long-lived, durable workflows that initialize resources, process commands in a loop, then clean up. + +[Documentation](/docs/actors/workflows) + +### Actions vs Queues + +- **Actions** are not durable. Use them for realtime reads, ephemeral data, and low-latency communication like player input. +- **Queues** are durable. Use them to serialize mutations through the run loop, avoiding race conditions with SQLite and other local state. Callers can still wait for a response from queued work. + +### Authentication, Security, & CORS + +- Validate credentials in `onBeforeConnect` or `createConnState` and throw an error to reject unauthorized connections. +- Use `c.conn.state` to securely identify users in actions rather than trusting action parameters. +- For cross-origin access, validate the request origin in `onBeforeConnect`. + +[Authentication Documentation](/docs/actors/authentication) · [CORS Documentation](/docs/general/cors) + +### Versions & Upgrades + +When deploying new code, set a version number so Rivet can route new actors to the latest runner and optionally drain old ones. Use a build timestamp, git commit count, or CI build number as the version. It is very important to [configure versioning](/docs/actors/versions) before deploying to production. Without versioning, actors can regress by running on older runner versions, and existing actors will never be forced to migrate to new runners. They will continue running indefinitely on the old runners until they exit. + +[Documentation](/docs/actors/versions) + +### Anti-Patterns + +#### Never build a "god" actor + +Do not put all your logic in a single actor. A god actor serializes every operation through one bottleneck, kills parallelism, and makes the entire system fail as a unit. Split into focused actors per entity. + +#### Never create an actor per request + +Actors are long-lived and maintain state across requests. Creating a new actor for every incoming request throws away the core benefit of the model and wastes resources on actor creation and teardown. Use actors for persistent entities and regular functions for stateless work. + +## Reference Map + +### Actors + +- [Access Control](reference/actors/access-control.md) +- [Actions](reference/actors/actions.md) +- [Actor Keys](reference/actors/keys.md) +- [Actor Runtime Socket](reference/actors/actor-runtime-socket.md) +- [Actor Scheduling](reference/actors/schedule.md) +- [Actor Statuses](reference/actors/statuses.md) +- [Authentication](reference/actors/authentication.md) +- [Cloudflare Workers Quickstart](reference/actors/quickstart/cloudflare.md) +- [Communicating Between Actors](reference/actors/communicating-between-actors.md) +- [Connections](reference/actors/connections.md) +- [Custom Inspector Tabs](reference/actors/inspector-tabs.md) +- [Debugging](reference/actors/debugging.md) +- [Design Patterns](reference/actors/design-patterns.md) +- [Destroying Actors](reference/actors/destroy.md) +- [Effect.ts Quickstart (Beta)](reference/actors/quickstart/effect.md) +- [Errors](reference/actors/errors.md) +- [Fetch and WebSocket Handler](reference/actors/fetch-and-websocket-handler.md) +- [Helper Types](reference/actors/helper-types.md) +- [Icons & Names](reference/actors/appearance.md) +- [In-Memory State](reference/actors/state.md) +- [Input Parameters](reference/actors/input.md) +- [Lifecycle](reference/actors/lifecycle.md) +- [Limits](reference/actors/limits.md) +- [Low-Level HTTP Request Handler](reference/actors/request-handler.md) +- [Low-Level KV Storage](reference/actors/kv.md) +- [Low-Level WebSocket Handler](reference/actors/websocket-handler.md) +- [Metadata](reference/actors/metadata.md) +- [Next.js Quickstart](reference/actors/quickstart/next-js.md) +- [Node.js & Bun Quickstart](reference/actors/quickstart/backend.md) +- [Queues & Run Loops](reference/actors/queues.md) +- [React Quickstart](reference/actors/quickstart/react.md) +- [Realtime](reference/actors/events.md) +- [Rust Quickstart (Beta)](reference/actors/quickstart/rust.md) +- [Scaling & Concurrency](reference/actors/scaling.md) +- [Sharing and Joining State](reference/actors/sharing-and-joining-state.md) +- [SQLite](reference/actors/sqlite.md) +- [SQLite + Drizzle](reference/actors/sqlite-drizzle.md) +- [Supabase Functions Quickstart](reference/actors/quickstart/supabase.md) +- [Testing](reference/actors/testing.md) +- [Troubleshooting](reference/actors/troubleshooting.md) +- [Types](reference/actors/types.md) +- [Vanilla HTTP API](reference/actors/http-api.md) +- [Versions & Upgrades](reference/actors/versions.md) +- [Workflows](reference/actors/workflows.md) + +### Cli + +- [CLI](reference/cli.md) + +### Clients + +- [Node.js & Bun](reference/clients/javascript.md) +- [React](reference/clients/react.md) +- [Rust (Beta)](reference/clients/rust.md) +- [Swift](reference/clients/swift.md) +- [SwiftUI](reference/clients/swiftui.md) + +### Cookbook + +- [AI Agent](reference/cookbook/ai-agent.md) +- [Chat Room](reference/cookbook/chat-room.md) +- [Collaborative Text Editor](reference/cookbook/collaborative-text-editor.md) +- [Cron Jobs and Scheduled Tasks](reference/cookbook/cron-jobs.md) +- [Database per Tenant](reference/cookbook/per-tenant-database.md) +- [Deploying Rivet in a VPC or Air-Gapped Network](reference/cookbook/vpc-air-gapped.md) +- [Live Cursors and Presence](reference/cookbook/live-cursors.md) +- [Multiplayer Game](reference/cookbook/multiplayer-game.md) + +### Deploy + +- [Container Runner](reference/deploy/container-runner.md) +- [Deploy To Amazon Web Services Lambda](reference/deploy/aws-lambda.md) +- [Deploying to AWS ECS](reference/deploy/aws-ecs.md) +- [Deploying to Cloudflare Workers](reference/deploy/cloudflare.md) +- [Deploying to Freestyle](reference/deploy/freestyle.md) +- [Deploying to Google Cloud Run](reference/deploy/gcp-cloud-run.md) +- [Deploying to Hetzner](reference/deploy/hetzner.md) +- [Deploying to Kubernetes](reference/deploy/kubernetes.md) +- [Deploying to Railway](reference/deploy/railway.md) +- [Deploying to Rivet Compute](reference/deploy/rivet-compute.md) +- [Deploying to Supabase Functions](reference/deploy/supabase.md) +- [Deploying to Vercel](reference/deploy/vercel.md) +- [Deploying to VMs & Bare Metal](reference/deploy/vm-and-bare-metal.md) + +### General + +- [Actor Configuration](reference/general/actor-configuration.md) +- [Architecture](reference/general/architecture.md) +- [Cross-Origin Resource Sharing](reference/general/cors.md) +- [Documentation for LLMs & AI](reference/general/docs-for-llms.md) +- [Edge Networking](reference/general/edge.md) +- [Endpoints](reference/general/endpoints.md) +- [Environment Variables](reference/general/environment-variables.md) +- [HTTP Server](reference/general/http-server.md) +- [Logging](reference/general/logging.md) +- [Pool Configuration](reference/general/pool-configuration.md) +- [Production Checklist](reference/general/production-checklist.md) +- [Registry Configuration](reference/general/registry-configuration.md) +- [Runtime Modes](reference/general/runtime-modes.md) +- [WASM vs Native SDK](reference/general/wasm-vs-native-sdk.md) + +### Self Hosting + +- [Configuration](reference/self-hosting/configuration.md) +- [Docker Compose](reference/self-hosting/docker-compose.md) +- [Docker Container](reference/self-hosting/docker-container.md) +- [File System](reference/self-hosting/filesystem.md) +- [FoundationDB (Enterprise)](reference/self-hosting/foundationdb.md) +- [Installing Rivet Engine](reference/self-hosting/install.md) +- [Kubernetes](reference/self-hosting/kubernetes.md) +- [Multi-Region](reference/self-hosting/multi-region.md) +- [PostgreSQL](reference/self-hosting/postgres.md) +- [Production Checklist](reference/self-hosting/production-checklist.md) +- [Railway Deployment](reference/self-hosting/railway.md) +- [Render Deployment](reference/self-hosting/render.md) +- [TLS & Certificates](reference/self-hosting/tls.md) + diff --git a/.agents/skills/ai-agent/SKILL.md b/.agents/skills/ai-agent/SKILL.md new file mode 100644 index 0000000..b3fb1d2 --- /dev/null +++ b/.agents/skills/ai-agent/SKILL.md @@ -0,0 +1,256 @@ +--- +name: "ai-agent" +description: "Build an AI agent backend with persistent memory: one Rivet Actor per conversation, queued message handling, and streaming LLM responses as realtime events." +--- + +# AI Agent + +**IMPORTANT: Before doing anything, you MUST read `BASE_SKILL.md` in this skill's directory. It contains essential guidance on debugging, error handling, state management, deployment, and project setup. Those rules and patterns apply to all RivetKit work. Everything below assumes you have already read and understood it.** + +## Working Examples + +If you need a reference implementation, read the raw working example code in these templates: + +- [ai-agent](https://github.com/rivet-dev/rivet/tree/main/examples/ai-agent) + + +Patterns for building AI agent backends with RivetKit, where each conversation is one Rivet Actor that owns its memory, its message queue, and its streaming output. + +## Starter Code + +Start with one of the working examples on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/ai-agent) and adapt it. The sections below describe the flagship `ai-agent` example unless a variant is called out explicitly. + +| Variant | Starter Code | Use When | +| --- | --- | --- | +| Queue-driven AI SDK agent | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/ai-agent) | You want a streaming chat agent where each conversation keeps its own persistent memory and processes one message at a time. | +| Sandbox coding agent | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/sandbox-coding-agent) | The agent should run a coding agent (Codex by default) inside an isolated [sandbox](/docs/actors/sandbox) via Docker, Daytona, or E2B. | +| Durable streams agent (experimental) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/experimental-durable-streams-ai-agent) | You want replayable, restart-safe prompt and response delivery through durable streams instead of actor state and events. | + +## Conversation Memory + +Use one actor per conversation, keyed by a conversation or agent id (see [Actor Keys](/docs/actors/keys)). The agent actor's persistent [state](/docs/actors/state) is the conversation memory: in the `ai-agent` example, `messages` and `status` live in JSON actor state and survive sleep and restarts with no external database. Every model call rebuilds the prompt from `c.state.messages` plus a system prompt, so memory and inference input are the same data. + +| Variant | Where Memory Lives | Persisted State Fields | +| --- | --- | --- | +| `ai-agent` | JSON actor state | `messages`, `status` | +| `sandbox-coding-agent` | JSON actor state plus the sandbox ACP session | `messages`, `status`, `sessionId` | +| `experimental-durable-streams-ai-agent` | Durable streams; the actor stores only its conversation id and a read cursor | `conversationId`, `promptStreamOffset` | + +## Message Handling + +In the `ai-agent` example, the client pushes user input onto the agent's `message` [queue](/docs/actors/queues) with `agent.connection.send("message", { text, sender })`. This is a queue push, not an action call. The actor's `run` hook (see [Lifecycle](/docs/actors/lifecycle)) consumes the queue serially with `for await (const queued of c.queue.iter())`. + +Serial queue consumption is the per-conversation concurrency guarantee: at most one in-flight model call per actor, with no extra locking. The `status` field (`thinking` while a model call is in flight) is UI signal only; the run loop is the actual lock. The loop also checks `c.aborted` inside the token stream so shutdown exits gracefully. + +| Variant | Message Ingress | Serialization Guarantee | +| --- | --- | --- | +| `ai-agent` | `message` queue pushed via `connection.send` | `run` hook pops one queued message at a time with `c.queue.iter()`. | +| `sandbox-coding-agent` | `sendMessage` [action](/docs/actors/actions), no queue | Each call awaits the sandbox round trip before broadcasting the result. | +| `experimental-durable-streams-ai-agent` | Durable prompt stream long-polled from `onWake` | `promptStreamOffset` is persisted per chunk, so restarts resume without reprocessing prompts. | + +## Streaming Responses + +The `ai-agent` actor broadcasts a `response` [event](/docs/actors/events) for every model text delta. The payload carries `messageId`, the per-token `delta`, the cumulative `content`, and a `done` flag (plus `error` on failure), so clients can either append deltas or idempotently replace the message by `messageId` using `content`. The example frontend replaces by `messageId`, which tolerates dropped events. The terminal broadcast has an empty `delta`, the full `content`, and `done: true`. + +Because the assistant message object lives in `c.state.messages` and is mutated in place during streaming, partial content persists if the actor restarts mid-stream. The example broadcasts once per AI SDK delta with no throttling; batching or throttling deltas is a recommended extension for high-traffic deployments, not something the example implements. + +Variant differences: `sandbox-coding-agent` sends a single `response` broadcast with `done: true` after the sandbox finishes (no incremental streaming), and `experimental-durable-streams-ai-agent` appends per-token chunks to a durable response stream, then broadcasts `responseComplete` or `responseError`. + +## Architecture + +| Topic | Summary | +| --- | --- | +| Topology | `agentManager["primary"]` singleton directory plus one `agent[agentId]` actor per conversation. | +| Ingress | Client pushes `AgentQueueMessage` payloads onto the agent's `message` queue with `connection.send`. | +| Streaming | One `response` broadcast per model delta, terminal broadcast with `done: true`. | +| Memory | Full transcript and status in JSON actor state; no external database. | + +The manager creates `AgentInfo` records and warms each agent through [actor-to-actor communication](/docs/actors/communicating-between-actors): `createAgent` calls `c.client()`, then `client.agent.getOrCreate([info.id])` and awaits `getStatus()` so the conversation actor exists before the client connects. The sandbox variant extends this topology with a `codingSandbox` actor that shares the agent's key (`codingSandbox.getOrCreate([c.key[0]])`), so the agent-to-sandbox mapping is implicit in the key space. + +**Actors** + +- **Key**: `agentManager["primary"]` +- **Responsibility**: Directory actor. Creates `AgentInfo` records, lists agents, and warms each agent actor via `c.client()`. +- **Actions** + - `createAgent` + - `listAgents` +- **Queues** + - None +- **State** + - JSON + - `agents` + +- **Key**: `agent[agentId]` +- **Responsibility**: One actor per conversation. Holds the full message history and status, consumes queued user messages in its `run` loop, calls the model via the AI SDK, and broadcasts streaming deltas. +- **Actions** + - `getHistory` + - `getStatus` +- **Queues** + - `message` +- **Events** + - `messageAdded` + - `status` + - `response` +- **State** + - JSON + - `messages` + - `status` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant AM as agentManager + participant A as agent + participant LLM as Model API + + C->>AM: createAgent(name) + AM->>A: getOrCreate([info.id]) + getStatus() + AM-->>C: AgentInfo + C->>A: connection.send("message", {text, sender}) + Note over A: run loop pops queue via c.queue.iter() + A-->>C: messageAdded (user message) + A-->>C: messageAdded (assistant placeholder) + A-->>C: status (thinking) + A->>LLM: streamText(system prompt + history) + loop each text delta + LLM-->>A: delta + A-->>C: response {messageId, delta, content, done: false} + end + A-->>C: response {delta: "", content, done: true} + A-->>C: status (idle) +``` + +## Security Checklist + +The examples ship without auth so they stay minimal. Apply this baseline before exposing an agent backend. + +- **API keys stay server-side**: `OPENAI_API_KEY` (or `ANTHROPIC_API_KEY`) is read by the AI SDK inside the actor process. The key never reaches the browser; clients only talk to the actor over RivetKit. The sandbox variant forwards keys into the sandbox env, never to the client. +- **Add authentication**: The examples have no auth, so anyone who reaches the server can create agents, list them, and message any agent whose key they can guess. Add `onBeforeConnect` or `createConnState` checks with scoped tokens as a recommended extension. See [Authentication](/docs/actors/authentication). +- **Validate and rate-limit queue payloads**: The example only skips bodies without a string `text`. Enforce payload size limits, schema validation, and per-connection rate limits as a recommended extension. +- **Derive sender identity server-side**: The example trusts the client-supplied `sender` field verbatim. Bind sender identity to the authenticated connection instead. +- **Cap or trim message history**: The example sends the full transcript on every model call with no cap. Trim or summarize old messages as a recommended extension so prompts and state stay bounded. +- **Set cost ceilings per conversation**: Add per-agent token budgets and quotas as a recommended extension. The sandbox variant runs real compute, so also enforce per-user sandbox quotas and restrict sandbox network egress. + +## Reference Map + +### Actors + +- [Access Control](reference/actors/access-control.md) +- [Actions](reference/actors/actions.md) +- [Actor Keys](reference/actors/keys.md) +- [Actor Runtime Socket](reference/actors/actor-runtime-socket.md) +- [Actor Scheduling](reference/actors/schedule.md) +- [Actor Statuses](reference/actors/statuses.md) +- [Authentication](reference/actors/authentication.md) +- [Cloudflare Workers Quickstart](reference/actors/quickstart/cloudflare.md) +- [Communicating Between Actors](reference/actors/communicating-between-actors.md) +- [Connections](reference/actors/connections.md) +- [Custom Inspector Tabs](reference/actors/inspector-tabs.md) +- [Debugging](reference/actors/debugging.md) +- [Design Patterns](reference/actors/design-patterns.md) +- [Destroying Actors](reference/actors/destroy.md) +- [Effect.ts Quickstart (Beta)](reference/actors/quickstart/effect.md) +- [Errors](reference/actors/errors.md) +- [Fetch and WebSocket Handler](reference/actors/fetch-and-websocket-handler.md) +- [Helper Types](reference/actors/helper-types.md) +- [Icons & Names](reference/actors/appearance.md) +- [In-Memory State](reference/actors/state.md) +- [Input Parameters](reference/actors/input.md) +- [Lifecycle](reference/actors/lifecycle.md) +- [Limits](reference/actors/limits.md) +- [Low-Level HTTP Request Handler](reference/actors/request-handler.md) +- [Low-Level KV Storage](reference/actors/kv.md) +- [Low-Level WebSocket Handler](reference/actors/websocket-handler.md) +- [Metadata](reference/actors/metadata.md) +- [Next.js Quickstart](reference/actors/quickstart/next-js.md) +- [Node.js & Bun Quickstart](reference/actors/quickstart/backend.md) +- [Queues & Run Loops](reference/actors/queues.md) +- [React Quickstart](reference/actors/quickstart/react.md) +- [Realtime](reference/actors/events.md) +- [Rust Quickstart (Beta)](reference/actors/quickstart/rust.md) +- [Scaling & Concurrency](reference/actors/scaling.md) +- [Sharing and Joining State](reference/actors/sharing-and-joining-state.md) +- [SQLite](reference/actors/sqlite.md) +- [SQLite + Drizzle](reference/actors/sqlite-drizzle.md) +- [Supabase Functions Quickstart](reference/actors/quickstart/supabase.md) +- [Testing](reference/actors/testing.md) +- [Troubleshooting](reference/actors/troubleshooting.md) +- [Types](reference/actors/types.md) +- [Vanilla HTTP API](reference/actors/http-api.md) +- [Versions & Upgrades](reference/actors/versions.md) +- [Workflows](reference/actors/workflows.md) + +### Cli + +- [CLI](reference/cli.md) + +### Clients + +- [Node.js & Bun](reference/clients/javascript.md) +- [React](reference/clients/react.md) +- [Rust (Beta)](reference/clients/rust.md) +- [Swift](reference/clients/swift.md) +- [SwiftUI](reference/clients/swiftui.md) + +### Cookbook + +- [AI Agent](reference/cookbook/ai-agent.md) +- [Chat Room](reference/cookbook/chat-room.md) +- [Collaborative Text Editor](reference/cookbook/collaborative-text-editor.md) +- [Cron Jobs and Scheduled Tasks](reference/cookbook/cron-jobs.md) +- [Database per Tenant](reference/cookbook/per-tenant-database.md) +- [Deploying Rivet in a VPC or Air-Gapped Network](reference/cookbook/vpc-air-gapped.md) +- [Live Cursors and Presence](reference/cookbook/live-cursors.md) +- [Multiplayer Game](reference/cookbook/multiplayer-game.md) + +### Deploy + +- [Container Runner](reference/deploy/container-runner.md) +- [Deploy To Amazon Web Services Lambda](reference/deploy/aws-lambda.md) +- [Deploying to AWS ECS](reference/deploy/aws-ecs.md) +- [Deploying to Cloudflare Workers](reference/deploy/cloudflare.md) +- [Deploying to Freestyle](reference/deploy/freestyle.md) +- [Deploying to Google Cloud Run](reference/deploy/gcp-cloud-run.md) +- [Deploying to Hetzner](reference/deploy/hetzner.md) +- [Deploying to Kubernetes](reference/deploy/kubernetes.md) +- [Deploying to Railway](reference/deploy/railway.md) +- [Deploying to Rivet Compute](reference/deploy/rivet-compute.md) +- [Deploying to Supabase Functions](reference/deploy/supabase.md) +- [Deploying to Vercel](reference/deploy/vercel.md) +- [Deploying to VMs & Bare Metal](reference/deploy/vm-and-bare-metal.md) + +### General + +- [Actor Configuration](reference/general/actor-configuration.md) +- [Architecture](reference/general/architecture.md) +- [Cross-Origin Resource Sharing](reference/general/cors.md) +- [Documentation for LLMs & AI](reference/general/docs-for-llms.md) +- [Edge Networking](reference/general/edge.md) +- [Endpoints](reference/general/endpoints.md) +- [Environment Variables](reference/general/environment-variables.md) +- [HTTP Server](reference/general/http-server.md) +- [Logging](reference/general/logging.md) +- [Pool Configuration](reference/general/pool-configuration.md) +- [Production Checklist](reference/general/production-checklist.md) +- [Registry Configuration](reference/general/registry-configuration.md) +- [Runtime Modes](reference/general/runtime-modes.md) +- [WASM vs Native SDK](reference/general/wasm-vs-native-sdk.md) + +### Self Hosting + +- [Configuration](reference/self-hosting/configuration.md) +- [Docker Compose](reference/self-hosting/docker-compose.md) +- [Docker Container](reference/self-hosting/docker-container.md) +- [File System](reference/self-hosting/filesystem.md) +- [FoundationDB (Enterprise)](reference/self-hosting/foundationdb.md) +- [Installing Rivet Engine](reference/self-hosting/install.md) +- [Kubernetes](reference/self-hosting/kubernetes.md) +- [Multi-Region](reference/self-hosting/multi-region.md) +- [PostgreSQL](reference/self-hosting/postgres.md) +- [Production Checklist](reference/self-hosting/production-checklist.md) +- [Railway Deployment](reference/self-hosting/railway.md) +- [Render Deployment](reference/self-hosting/render.md) +- [TLS & Certificates](reference/self-hosting/tls.md) + diff --git a/.agents/skills/ai-agent/index.json b/.agents/skills/ai-agent/index.json new file mode 100644 index 0000000..4b3febc --- /dev/null +++ b/.agents/skills/ai-agent/index.json @@ -0,0 +1,694 @@ +{ + "name": "ai-agent", + "description": "Build an AI agent backend with persistent memory: one Rivet Actor per conversation, queued message handling, and streaming LLM responses as realtime events.", + "skill_url": "/metadata/skills/ai-agent/SKILL.md", + "generated_at": "2026-07-18T12:40:07.490Z", + "references": [ + { + "name": "actors/access-control", + "title": "Access Control", + "description": "Authorize actions, queue publishes, and event subscriptions with explicit hooks.", + "canonical_url": "https://rivet.dev/docs/actors/access-control", + "reference_url": "/metadata/skills/ai-agent/reference/actors/access-control.md" + }, + { + "name": "actors/actions", + "title": "Actions", + "description": "Actions are how your backend, frontend, or other actors can communicate with actors.", + "canonical_url": "https://rivet.dev/docs/actors/actions", + "reference_url": "/metadata/skills/ai-agent/reference/actors/actions.md" + }, + { + "name": "general/actor-configuration", + "title": "Actor Configuration", + "description": "This page documents the configuration options available when defining a RivetKit actor. The actor configuration is passed to the `actor()` function.", + "canonical_url": "https://rivet.dev/docs/general/actor-configuration", + "reference_url": "/metadata/skills/ai-agent/reference/general/actor-configuration.md" + }, + { + "name": "actors/keys", + "title": "Actor Keys", + "description": "Actor keys uniquely identify actor instances within each actor type. Keys are used for addressing which specific actor to communicate with.", + "canonical_url": "https://rivet.dev/docs/actors/keys", + "reference_url": "/metadata/skills/ai-agent/reference/actors/keys.md" + }, + { + "name": "actors/actor-runtime-socket", + "title": "Actor Runtime Socket", + "description": "Connect trusted local tools to a running Rivet Actor over an experimental actor-local protocol.", + "canonical_url": "https://rivet.dev/docs/actors/actor-runtime-socket", + "reference_url": "/metadata/skills/ai-agent/reference/actors/actor-runtime-socket.md" + }, + { + "name": "actors/schedule", + "title": "Actor Scheduling", + "description": "Schedule actor actions in the future with persistent timers that survive restarts and upgrades.", + "canonical_url": "https://rivet.dev/docs/actors/schedule", + "reference_url": "/metadata/skills/ai-agent/reference/actors/schedule.md" + }, + { + "name": "actors/statuses", + "title": "Actor Statuses", + "description": "Understand the lifecycle statuses of Rivet Actors, what they mean, how they appear in the API, and how to troubleshoot common issues.", + "canonical_url": "https://rivet.dev/docs/actors/statuses", + "reference_url": "/metadata/skills/ai-agent/reference/actors/statuses.md" + }, + { + "name": "cookbook/ai-agent", + "title": "AI Agent", + "description": "Build an AI agent backend with persistent memory: one Rivet Actor per conversation, queued message handling, and streaming LLM responses as realtime events.", + "canonical_url": "https://rivet.dev/cookbook/ai-agent", + "reference_url": "/metadata/skills/ai-agent/reference/cookbook/ai-agent.md" + }, + { + "name": "general/architecture", + "title": "Architecture", + "description": "- rivetkit is the typescript library used for both local development & to connect your application to rivet - a rivetkit instance is called a \"runner.\" you can run multiple runners to scale rivetkit horizontally. read omre about runners below.", + "canonical_url": "https://rivet.dev/docs/general/architecture", + "reference_url": "/metadata/skills/ai-agent/reference/general/architecture.md" + }, + { + "name": "actors/authentication", + "title": "Authentication", + "description": "Secure your actors with authentication and authorization.", + "canonical_url": "https://rivet.dev/docs/actors/authentication", + "reference_url": "/metadata/skills/ai-agent/reference/actors/authentication.md" + }, + { + "name": "cookbook/chat-room", + "title": "Chat Room", + "description": "Build a realtime chat room backend with Rivet Actors: one actor per room, SQLite-backed message history, and WebSocket broadcast to every connected client.", + "canonical_url": "https://rivet.dev/cookbook/chat-room", + "reference_url": "/metadata/skills/ai-agent/reference/cookbook/chat-room.md" + }, + { + "name": "cli", + "title": "CLI", + "description": "Reference for the optional rivet CLI: deploy to Rivet Compute and run local dev for serverless platforms.", + "canonical_url": "https://rivet.dev/docs/cli", + "reference_url": "/metadata/skills/ai-agent/reference/cli.md" + }, + { + "name": "actors/quickstart/cloudflare", + "title": "Cloudflare Workers Quickstart", + "description": "Set up a Rivet project locally targeting Cloudflare Workers.", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/cloudflare", + "reference_url": "/metadata/skills/ai-agent/reference/actors/quickstart/cloudflare.md" + }, + { + "name": "cookbook/collaborative-text-editor", + "title": "Collaborative Text Editor", + "description": "Build a collaborative text editor backend with Yjs CRDTs and Rivet Actors: per-document actors relay sync and awareness updates and persist snapshots.", + "canonical_url": "https://rivet.dev/cookbook/collaborative-text-editor", + "reference_url": "/metadata/skills/ai-agent/reference/cookbook/collaborative-text-editor.md" + }, + { + "name": "actors/communicating-between-actors", + "title": "Communicating Between Actors", + "description": "Learn how actors can call other actors and share data", + "canonical_url": "https://rivet.dev/docs/actors/communicating-between-actors", + "reference_url": "/metadata/skills/ai-agent/reference/actors/communicating-between-actors.md" + }, + { + "name": "self-hosting/configuration", + "title": "Configuration", + "description": "Rivet Engine can be configured through environment variables or configuration files.", + "canonical_url": "https://rivet.dev/docs/self-hosting/configuration", + "reference_url": "/metadata/skills/ai-agent/reference/self-hosting/configuration.md" + }, + { + "name": "actors/connections", + "title": "Connections", + "description": "Connections represent client connections to your actor. They provide a way to handle client authentication, manage connection-specific data, and control the connection lifecycle.", + "canonical_url": "https://rivet.dev/docs/actors/connections", + "reference_url": "/metadata/skills/ai-agent/reference/actors/connections.md" + }, + { + "name": "deploy/container-runner", + "title": "Container Runner", + "description": "Run any containerized server as a Rivet Actor.", + "canonical_url": "https://rivet.dev/docs/deploy/container-runner", + "reference_url": "/metadata/skills/ai-agent/reference/deploy/container-runner.md" + }, + { + "name": "cookbook/cron-jobs", + "title": "Cron Jobs and Scheduled Tasks", + "description": "Durable cron jobs with Rivet Actors: schedule.after and schedule.at timers survive restarts and crashes, plus re-arming recurring jobs and idempotent handlers.", + "canonical_url": "https://rivet.dev/cookbook/cron-jobs", + "reference_url": "/metadata/skills/ai-agent/reference/cookbook/cron-jobs.md" + }, + { + "name": "general/cors", + "title": "Cross-Origin Resource Sharing", + "description": "Cross-Origin Resource Sharing (CORS) controls which origins (domains) can access your actors. When actors are exposed to the public internet, proper origin validation is critical to prevent security breaches and denial of service attacks.", + "canonical_url": "https://rivet.dev/docs/general/cors", + "reference_url": "/metadata/skills/ai-agent/reference/general/cors.md" + }, + { + "name": "actors/inspector-tabs", + "title": "Custom Inspector Tabs", + "description": "Ship your own UI tabs alongside a Rivet Actor — embedded directly in the dashboard inspector.", + "canonical_url": "https://rivet.dev/docs/actors/inspector-tabs", + "reference_url": "/metadata/skills/ai-agent/reference/actors/inspector-tabs.md" + }, + { + "name": "cookbook/per-tenant-database", + "title": "Database per Tenant", + "description": "Multi-tenant data isolation with one Rivet Actor per tenant: the actor key is the tenant id, so each tenant gets its own isolated dataset and migrations.", + "canonical_url": "https://rivet.dev/cookbook/per-tenant-database", + "reference_url": "/metadata/skills/ai-agent/reference/cookbook/per-tenant-database.md" + }, + { + "name": "actors/debugging", + "title": "Debugging", + "description": "Inspect and debug running Rivet Actors, runners, and provider configs using management, runner, and actor inspector HTTP APIs.", + "canonical_url": "https://rivet.dev/docs/actors/debugging", + "reference_url": "/metadata/skills/ai-agent/reference/actors/debugging.md" + }, + { + "name": "deploy/aws-lambda", + "title": "Deploy To Amazon Web Services Lambda", + "description": "_AWS Lambda is coming soon_", + "canonical_url": "https://rivet.dev/docs/deploy/aws-lambda", + "reference_url": "/metadata/skills/ai-agent/reference/deploy/aws-lambda.md" + }, + { + "name": "cookbook/vpc-air-gapped", + "title": "Deploying Rivet in a VPC or Air-Gapped Network", + "description": "Run Rivet entirely inside your own perimeter: single-binary or Docker Compose install, file system storage with no database infrastructure, and no outbound telemetry by default.", + "canonical_url": "https://rivet.dev/cookbook/vpc-air-gapped", + "reference_url": "/metadata/skills/ai-agent/reference/cookbook/vpc-air-gapped.md" + }, + { + "name": "deploy/aws-ecs", + "title": "Deploying to AWS ECS", + "description": "Run your backend on Amazon ECS with Fargate.", + "canonical_url": "https://rivet.dev/docs/deploy/aws-ecs", + "reference_url": "/metadata/skills/ai-agent/reference/deploy/aws-ecs.md" + }, + { + "name": "deploy/cloudflare", + "title": "Deploying to Cloudflare Workers", + "description": "Deploy an existing Rivet project to Cloudflare Workers.", + "canonical_url": "https://rivet.dev/docs/deploy/cloudflare", + "reference_url": "/metadata/skills/ai-agent/reference/deploy/cloudflare.md" + }, + { + "name": "deploy/freestyle", + "title": "Deploying to Freestyle", + "description": "Deploy RivetKit app to Freestyle.sh, a cloud platform for running AI-generated code with built-in security and scalability.", + "canonical_url": "https://rivet.dev/docs/deploy/freestyle", + "reference_url": "/metadata/skills/ai-agent/reference/deploy/freestyle.md" + }, + { + "name": "deploy/gcp-cloud-run", + "title": "Deploying to Google Cloud Run", + "description": "Deploy your RivetKit app to Google Cloud Run.", + "canonical_url": "https://rivet.dev/docs/deploy/gcp-cloud-run", + "reference_url": "/metadata/skills/ai-agent/reference/deploy/gcp-cloud-run.md" + }, + { + "name": "deploy/hetzner", + "title": "Deploying to Hetzner", + "description": "Please see the VM & Bare Metal guide.", + "canonical_url": "https://rivet.dev/docs/deploy/hetzner", + "reference_url": "/metadata/skills/ai-agent/reference/deploy/hetzner.md" + }, + { + "name": "deploy/kubernetes", + "title": "Deploying to Kubernetes", + "description": "Deploy your RivetKit app to any Kubernetes cluster.", + "canonical_url": "https://rivet.dev/docs/deploy/kubernetes", + "reference_url": "/metadata/skills/ai-agent/reference/deploy/kubernetes.md" + }, + { + "name": "deploy/railway", + "title": "Deploying to Railway", + "description": "Deploy your RivetKit app to Railway.", + "canonical_url": "https://rivet.dev/docs/deploy/railway", + "reference_url": "/metadata/skills/ai-agent/reference/deploy/railway.md" + }, + { + "name": "deploy/rivet-compute", + "title": "Deploying to Rivet Compute", + "description": "Run your backend on Rivet Compute.", + "canonical_url": "https://rivet.dev/docs/deploy/rivet-compute", + "reference_url": "/metadata/skills/ai-agent/reference/deploy/rivet-compute.md" + }, + { + "name": "deploy/supabase", + "title": "Deploying to Supabase Functions", + "description": "Deploy an existing Rivet project to Supabase Edge Functions.", + "canonical_url": "https://rivet.dev/docs/deploy/supabase", + "reference_url": "/metadata/skills/ai-agent/reference/deploy/supabase.md" + }, + { + "name": "deploy/vercel", + "title": "Deploying to Vercel", + "description": "Deploy your Next.js Rivet app to Vercel.", + "canonical_url": "https://rivet.dev/docs/deploy/vercel", + "reference_url": "/metadata/skills/ai-agent/reference/deploy/vercel.md" + }, + { + "name": "deploy/vm-and-bare-metal", + "title": "Deploying to VMs & Bare Metal", + "description": "Deploy your RivetKit app to any Linux VM or bare metal host.", + "canonical_url": "https://rivet.dev/docs/deploy/vm-and-bare-metal", + "reference_url": "/metadata/skills/ai-agent/reference/deploy/vm-and-bare-metal.md" + }, + { + "name": "actors/design-patterns", + "title": "Design Patterns", + "description": "Common patterns and anti-patterns for building scalable actor systems.", + "canonical_url": "https://rivet.dev/docs/actors/design-patterns", + "reference_url": "/metadata/skills/ai-agent/reference/actors/design-patterns.md" + }, + { + "name": "actors/destroy", + "title": "Destroying Actors", + "description": "Actors can be permanently destroyed. Common use cases include:", + "canonical_url": "https://rivet.dev/docs/actors/destroy", + "reference_url": "/metadata/skills/ai-agent/reference/actors/destroy.md" + }, + { + "name": "self-hosting/docker-compose", + "title": "Docker Compose", + "description": "Deploy Rivet Engine with docker-compose for multi-container setups.", + "canonical_url": "https://rivet.dev/docs/self-hosting/docker-compose", + "reference_url": "/metadata/skills/ai-agent/reference/self-hosting/docker-compose.md" + }, + { + "name": "self-hosting/docker-container", + "title": "Docker Container", + "description": "Run Rivet Engine in a single Docker container.", + "canonical_url": "https://rivet.dev/docs/self-hosting/docker-container", + "reference_url": "/metadata/skills/ai-agent/reference/self-hosting/docker-container.md" + }, + { + "name": "general/docs-for-llms", + "title": "Documentation for LLMs & AI", + "description": "Rivet provides optimized documentation formats specifically designed for Large Language Models (LLMs) and AI integration tools.", + "canonical_url": "https://rivet.dev/docs/general/docs-for-llms", + "reference_url": "/metadata/skills/ai-agent/reference/general/docs-for-llms.md" + }, + { + "name": "general/edge", + "title": "Edge Networking", + "description": "Actors automatically run near your users on your provider's global network.", + "canonical_url": "https://rivet.dev/docs/general/edge", + "reference_url": "/metadata/skills/ai-agent/reference/general/edge.md" + }, + { + "name": "actors/quickstart/effect", + "title": "Effect.ts Quickstart (Beta)", + "description": "Build a Rivet Actor with the Effect SDK", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/effect", + "reference_url": "/metadata/skills/ai-agent/reference/actors/quickstart/effect.md" + }, + { + "name": "general/endpoints", + "title": "Endpoints", + "description": "Configure how your backend connects to Rivet and how clients reach your actors.", + "canonical_url": "https://rivet.dev/docs/general/endpoints", + "reference_url": "/metadata/skills/ai-agent/reference/general/endpoints.md" + }, + { + "name": "general/environment-variables", + "title": "Environment Variables", + "description": "This page documents all environment variables that configure RivetKit behavior.", + "canonical_url": "https://rivet.dev/docs/general/environment-variables", + "reference_url": "/metadata/skills/ai-agent/reference/general/environment-variables.md" + }, + { + "name": "actors/errors", + "title": "Errors", + "description": "Rivet provides robust error handling with security built in by default. Errors are handled differently based on whether they should be exposed to clients or kept private.", + "canonical_url": "https://rivet.dev/docs/actors/errors", + "reference_url": "/metadata/skills/ai-agent/reference/actors/errors.md" + }, + { + "name": "actors/fetch-and-websocket-handler", + "title": "Fetch and WebSocket Handler", + "description": "These docs have moved to [Low-Level WebSocket Handler](/docs/actors/websocket-handler) and [Low-Level Request Handler](/docs/actors/request-handler).", + "canonical_url": "https://rivet.dev/docs/actors/fetch-and-websocket-handler", + "reference_url": "/metadata/skills/ai-agent/reference/actors/fetch-and-websocket-handler.md" + }, + { + "name": "self-hosting/filesystem", + "title": "File System", + "description": "The file system backend stores all data on the local disk. This is suitable for single-node deployments, development, and testing.", + "canonical_url": "https://rivet.dev/docs/self-hosting/filesystem", + "reference_url": "/metadata/skills/ai-agent/reference/self-hosting/filesystem.md" + }, + { + "name": "self-hosting/foundationdb", + "title": "FoundationDB (Enterprise)", + "description": "FoundationDB is the recommended storage backend for scalable production Rivet deployments.", + "canonical_url": "https://rivet.dev/docs/self-hosting/foundationdb", + "reference_url": "/metadata/skills/ai-agent/reference/self-hosting/foundationdb.md" + }, + { + "name": "actors/helper-types", + "title": "Helper Types", + "description": "This page has moved to [Types](/docs/actors/types).", + "canonical_url": "https://rivet.dev/docs/actors/helper-types", + "reference_url": "/metadata/skills/ai-agent/reference/actors/helper-types.md" + }, + { + "name": "general/http-server", + "title": "HTTP Server", + "description": "Different ways to run your RivetKit HTTP server.", + "canonical_url": "https://rivet.dev/docs/general/http-server", + "reference_url": "/metadata/skills/ai-agent/reference/general/http-server.md" + }, + { + "name": "actors/appearance", + "title": "Icons & Names", + "description": "Customize actors with display names and icons for the Rivet inspector and dashboard.", + "canonical_url": "https://rivet.dev/docs/actors/appearance", + "reference_url": "/metadata/skills/ai-agent/reference/actors/appearance.md" + }, + { + "name": "actors/state", + "title": "In-Memory State", + "description": "Actors store state in memory for instant reads and writes. State can be persisted automatically or kept ephemeral.", + "canonical_url": "https://rivet.dev/docs/actors/state", + "reference_url": "/metadata/skills/ai-agent/reference/actors/state.md" + }, + { + "name": "actors/input", + "title": "Input Parameters", + "description": "Pass initialization data to actors when creating instances", + "canonical_url": "https://rivet.dev/docs/actors/input", + "reference_url": "/metadata/skills/ai-agent/reference/actors/input.md" + }, + { + "name": "self-hosting/install", + "title": "Installing Rivet Engine", + "description": "Install Rivet Engine using Docker, binaries, or a source build.", + "canonical_url": "https://rivet.dev/docs/self-hosting/install", + "reference_url": "/metadata/skills/ai-agent/reference/self-hosting/install.md" + }, + { + "name": "self-hosting/kubernetes", + "title": "Kubernetes", + "description": "Deploy production-ready Rivet Engine to Kubernetes with PostgreSQL storage.", + "canonical_url": "https://rivet.dev/docs/self-hosting/kubernetes", + "reference_url": "/metadata/skills/ai-agent/reference/self-hosting/kubernetes.md" + }, + { + "name": "actors/lifecycle", + "title": "Lifecycle", + "description": "Learn about actor lifecycle hooks for initialization, state management, and cleanup.", + "canonical_url": "https://rivet.dev/docs/actors/lifecycle", + "reference_url": "/metadata/skills/ai-agent/reference/actors/lifecycle.md" + }, + { + "name": "actors/limits", + "title": "Limits", + "description": "Limits and constraints for Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/actors/limits", + "reference_url": "/metadata/skills/ai-agent/reference/actors/limits.md" + }, + { + "name": "cookbook/live-cursors", + "title": "Live Cursors and Presence", + "description": "Live cursors and multiplayer presence with Rivet Actors: per-connection cursor state, realtime updates over events or raw WebSockets, and throttling.", + "canonical_url": "https://rivet.dev/cookbook/live-cursors", + "reference_url": "/metadata/skills/ai-agent/reference/cookbook/live-cursors.md" + }, + { + "name": "general/logging", + "title": "Logging", + "description": "Actors provide a built-in way to log complex data to the console.", + "canonical_url": "https://rivet.dev/docs/general/logging", + "reference_url": "/metadata/skills/ai-agent/reference/general/logging.md" + }, + { + "name": "actors/request-handler", + "title": "Low-Level HTTP Request Handler", + "description": "Actors can handle HTTP requests through the `onRequest` handler.", + "canonical_url": "https://rivet.dev/docs/actors/request-handler", + "reference_url": "/metadata/skills/ai-agent/reference/actors/request-handler.md" + }, + { + "name": "actors/kv", + "title": "Low-Level KV Storage", + "description": "Use the built-in key-value store on ActorContext for durable string and binary data alongside actor state.", + "canonical_url": "https://rivet.dev/docs/actors/kv", + "reference_url": "/metadata/skills/ai-agent/reference/actors/kv.md" + }, + { + "name": "actors/websocket-handler", + "title": "Low-Level WebSocket Handler", + "description": "Actors can handle WebSocket connections through the `onWebSocket` handler.", + "canonical_url": "https://rivet.dev/docs/actors/websocket-handler", + "reference_url": "/metadata/skills/ai-agent/reference/actors/websocket-handler.md" + }, + { + "name": "actors/metadata", + "title": "Metadata", + "description": "Metadata provides information about the currently running actor.", + "canonical_url": "https://rivet.dev/docs/actors/metadata", + "reference_url": "/metadata/skills/ai-agent/reference/actors/metadata.md" + }, + { + "name": "self-hosting/multi-region", + "title": "Multi-Region", + "description": "Rivet Engine supports scaling transparently across multiple regions.", + "canonical_url": "https://rivet.dev/docs/self-hosting/multi-region", + "reference_url": "/metadata/skills/ai-agent/reference/self-hosting/multi-region.md" + }, + { + "name": "cookbook/multiplayer-game", + "title": "Multiplayer Game", + "description": "Pragmatic patterns for building multiplayer games: matchmaking, tick loops, realtime state, interest management, and validation.", + "canonical_url": "https://rivet.dev/cookbook/multiplayer-game", + "reference_url": "/metadata/skills/ai-agent/reference/cookbook/multiplayer-game.md" + }, + { + "name": "actors/quickstart/next-js", + "title": "Next.js Quickstart", + "description": "Get started with Rivet Actors in Next.js", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/next-js", + "reference_url": "/metadata/skills/ai-agent/reference/actors/quickstart/next-js.md" + }, + { + "name": "clients/javascript", + "title": "Node.js & Bun", + "description": "Connect JavaScript apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/javascript", + "reference_url": "/metadata/skills/ai-agent/reference/clients/javascript.md" + }, + { + "name": "actors/quickstart/backend", + "title": "Node.js & Bun Quickstart", + "description": "Get started with Rivet Actors in Node.js and Bun", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/backend", + "reference_url": "/metadata/skills/ai-agent/reference/actors/quickstart/backend.md" + }, + { + "name": "general/pool-configuration", + "title": "Pool Configuration", + "description": "Reference for runner pool configuration, including drain behavior, actor eviction rate limiting, and serverless-specific options.", + "canonical_url": "https://rivet.dev/docs/general/pool-configuration", + "reference_url": "/metadata/skills/ai-agent/reference/general/pool-configuration.md" + }, + { + "name": "self-hosting/postgres", + "title": "PostgreSQL", + "description": "Configure PostgreSQL for self-hosted Rivet deployments.", + "canonical_url": "https://rivet.dev/docs/self-hosting/postgres", + "reference_url": "/metadata/skills/ai-agent/reference/self-hosting/postgres.md" + }, + { + "name": "general/production-checklist", + "title": "Production Checklist", + "description": "Checklist for deploying Rivet Actors to production.", + "canonical_url": "https://rivet.dev/docs/general/production-checklist", + "reference_url": "/metadata/skills/ai-agent/reference/general/production-checklist.md" + }, + { + "name": "self-hosting/production-checklist", + "title": "Production Checklist", + "description": "Checklist for deploying a self-hosted Rivet Engine to production.", + "canonical_url": "https://rivet.dev/docs/self-hosting/production-checklist", + "reference_url": "/metadata/skills/ai-agent/reference/self-hosting/production-checklist.md" + }, + { + "name": "actors/queues", + "title": "Queues & Run Loops", + "description": "Use actor-local durable queues for serial run loops and request/response workflows.", + "canonical_url": "https://rivet.dev/docs/actors/queues", + "reference_url": "/metadata/skills/ai-agent/reference/actors/queues.md" + }, + { + "name": "self-hosting/railway", + "title": "Railway Deployment", + "description": "Railway provides a simple platform for deploying Rivet Engine with automatic scaling and managed infrastructure.", + "canonical_url": "https://rivet.dev/docs/self-hosting/railway", + "reference_url": "/metadata/skills/ai-agent/reference/self-hosting/railway.md" + }, + { + "name": "clients/react", + "title": "React", + "description": "Connect React apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/react", + "reference_url": "/metadata/skills/ai-agent/reference/clients/react.md" + }, + { + "name": "actors/quickstart/react", + "title": "React Quickstart", + "description": "Build realtime React applications with Rivet Actors", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/react", + "reference_url": "/metadata/skills/ai-agent/reference/actors/quickstart/react.md" + }, + { + "name": "actors/events", + "title": "Realtime", + "description": "Events enable realtime communication from actors to clients. While clients use actions to send data to actors, events allow actors to push updates to connected clients instantly.", + "canonical_url": "https://rivet.dev/docs/actors/events", + "reference_url": "/metadata/skills/ai-agent/reference/actors/events.md" + }, + { + "name": "general/registry-configuration", + "title": "Registry Configuration", + "description": "This page documents the configuration options available when setting up a RivetKit registry. The registry configuration is passed to the `setup()` function.", + "canonical_url": "https://rivet.dev/docs/general/registry-configuration", + "reference_url": "/metadata/skills/ai-agent/reference/general/registry-configuration.md" + }, + { + "name": "self-hosting/render", + "title": "Render Deployment", + "description": "Deploy Rivet Engine to Render with managed PostgreSQL and automatic HTTPS, using the experimental PostgreSQL backend.", + "canonical_url": "https://rivet.dev/docs/self-hosting/render", + "reference_url": "/metadata/skills/ai-agent/reference/self-hosting/render.md" + }, + { + "name": "general/runtime-modes", + "title": "Runtime Modes", + "description": "RivetKit supports two runtime modes for running your actors:", + "canonical_url": "https://rivet.dev/docs/general/runtime-modes", + "reference_url": "/metadata/skills/ai-agent/reference/general/runtime-modes.md" + }, + { + "name": "clients/rust", + "title": "Rust (Beta)", + "description": "Connect Rust apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/rust", + "reference_url": "/metadata/skills/ai-agent/reference/clients/rust.md" + }, + { + "name": "actors/quickstart/rust", + "title": "Rust Quickstart (Beta)", + "description": "Build a Rivet Actor in Rust", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/rust", + "reference_url": "/metadata/skills/ai-agent/reference/actors/quickstart/rust.md" + }, + { + "name": "actors/scaling", + "title": "Scaling & Concurrency", + "description": "This page has moved to [design patterns](/docs/actors/design-patterns).", + "canonical_url": "https://rivet.dev/docs/actors/scaling", + "reference_url": "/metadata/skills/ai-agent/reference/actors/scaling.md" + }, + { + "name": "actors/sharing-and-joining-state", + "title": "Sharing and Joining State", + "description": "This page has moved to [design patterns](/docs/actors/design-patterns).", + "canonical_url": "https://rivet.dev/docs/actors/sharing-and-joining-state", + "reference_url": "/metadata/skills/ai-agent/reference/actors/sharing-and-joining-state.md" + }, + { + "name": "actors/sqlite", + "title": "SQLite", + "description": "Use embedded SQLite in Rivet Actors with raw SQL queries.", + "canonical_url": "https://rivet.dev/docs/actors/sqlite", + "reference_url": "/metadata/skills/ai-agent/reference/actors/sqlite.md" + }, + { + "name": "actors/sqlite-drizzle", + "title": "SQLite + Drizzle", + "description": "Use Drizzle ORM with embedded SQLite in Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/actors/sqlite-drizzle", + "reference_url": "/metadata/skills/ai-agent/reference/actors/sqlite-drizzle.md" + }, + { + "name": "actors/quickstart/supabase", + "title": "Supabase Functions Quickstart", + "description": "Set up a Rivet project locally targeting Supabase Edge Functions.", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/supabase", + "reference_url": "/metadata/skills/ai-agent/reference/actors/quickstart/supabase.md" + }, + { + "name": "clients/swift", + "title": "Swift", + "description": "Connect Swift apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/swift", + "reference_url": "/metadata/skills/ai-agent/reference/clients/swift.md" + }, + { + "name": "clients/swiftui", + "title": "SwiftUI", + "description": "Build SwiftUI apps with Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/swiftui", + "reference_url": "/metadata/skills/ai-agent/reference/clients/swiftui.md" + }, + { + "name": "actors/testing", + "title": "Testing", + "description": "Rivet provides a straightforward testing framework to build reliable and maintainable applications. This guide covers how to write effective tests for your actor-based services.", + "canonical_url": "https://rivet.dev/docs/actors/testing", + "reference_url": "/metadata/skills/ai-agent/reference/actors/testing.md" + }, + { + "name": "self-hosting/tls", + "title": "TLS & Certificates", + "description": "How Rivet validates TLS root certificates.", + "canonical_url": "https://rivet.dev/docs/self-hosting/tls", + "reference_url": "/metadata/skills/ai-agent/reference/self-hosting/tls.md" + }, + { + "name": "actors/troubleshooting", + "title": "Troubleshooting", + "description": "Common issues with Rivet Actors and how to resolve them.", + "canonical_url": "https://rivet.dev/docs/actors/troubleshooting", + "reference_url": "/metadata/skills/ai-agent/reference/actors/troubleshooting.md" + }, + { + "name": "actors/types", + "title": "Types", + "description": "TypeScript types for working with Rivet Actors. This page covers context types used in lifecycle hooks and actions, as well as helper types for extracting types from actor definitions.", + "canonical_url": "https://rivet.dev/docs/actors/types", + "reference_url": "/metadata/skills/ai-agent/reference/actors/types.md" + }, + { + "name": "actors/http-api", + "title": "Vanilla HTTP API", + "description": "Use the low-level HTTP handler to send and receive requests from actors.", + "canonical_url": "https://rivet.dev/docs/actors/http-api", + "reference_url": "/metadata/skills/ai-agent/reference/actors/http-api.md" + }, + { + "name": "actors/versions", + "title": "Versions & Upgrades", + "description": "When you deploy new code, Rivet ensures actors are upgraded seamlessly without downtime.", + "canonical_url": "https://rivet.dev/docs/actors/versions", + "reference_url": "/metadata/skills/ai-agent/reference/actors/versions.md" + }, + { + "name": "general/wasm-vs-native-sdk", + "title": "WASM vs Native SDK", + "description": "RivetKit runs your actors on a native or a WebAssembly runtime depending on your platform.", + "canonical_url": "https://rivet.dev/docs/general/wasm-vs-native-sdk", + "reference_url": "/metadata/skills/ai-agent/reference/general/wasm-vs-native-sdk.md" + }, + { + "name": "actors/workflows", + "title": "Workflows", + "description": "Build durable, replayable run loops in Rivet Actors with steps, queue waits, timers, and rollback.", + "canonical_url": "https://rivet.dev/docs/actors/workflows", + "reference_url": "/metadata/skills/ai-agent/reference/actors/workflows.md" + } + ] +} \ No newline at end of file diff --git a/.agents/skills/ai-agent/openapi.json b/.agents/skills/ai-agent/openapi.json new file mode 100644 index 0000000..ca482f7 --- /dev/null +++ b/.agents/skills/ai-agent/openapi.json @@ -0,0 +1,1311 @@ +{ + "openapi": "3.0.0", + "info": { + "version": "2.2.0", + "title": "RivetKit API" + }, + "components": { + "schemas": {}, + "parameters": {} + }, + "paths": { + "/actors": { + "get": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": false, + "name": "name", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "actor_ids", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "key", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "actors": { + "type": "array", + "items": { + "type": "object", + "properties": { + "actor_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "namespace_id": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "create_ts": { + "type": "number" + }, + "connectable_ts": { + "type": "number", + "nullable": true + }, + "destroy_ts": { + "type": "number", + "nullable": true + }, + "sleep_ts": { + "type": "number", + "nullable": true + }, + "start_ts": { + "type": "number", + "nullable": true + }, + "error": { + "nullable": true + } + }, + "required": [ + "actor_id", + "name", + "key", + "namespace_id", + "runner_name_selector", + "create_ts" + ] + } + } + }, + "required": [ + "actors" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + }, + "put": { + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "datacenter": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "crash_policy": { + "type": "string" + }, + "input": { + "type": "string", + "nullable": true + } + }, + "required": [ + "name", + "key", + "runner_name_selector", + "crash_policy" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "actor": { + "type": "object", + "properties": { + "actor_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "namespace_id": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "create_ts": { + "type": "number" + }, + "connectable_ts": { + "type": "number", + "nullable": true + }, + "destroy_ts": { + "type": "number", + "nullable": true + }, + "sleep_ts": { + "type": "number", + "nullable": true + }, + "start_ts": { + "type": "number", + "nullable": true + }, + "error": { + "nullable": true + } + }, + "required": [ + "actor_id", + "name", + "key", + "namespace_id", + "runner_name_selector", + "create_ts" + ] + }, + "created": { + "type": "boolean" + } + }, + "required": [ + "actor", + "created" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + }, + "post": { + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "datacenter": { + "type": "string" + }, + "name": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "crash_policy": { + "type": "string" + }, + "key": { + "type": "string", + "nullable": true + }, + "input": { + "type": "string", + "nullable": true + } + }, + "required": [ + "name", + "runner_name_selector", + "crash_policy" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "actor": { + "type": "object", + "properties": { + "actor_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "namespace_id": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "create_ts": { + "type": "number" + }, + "connectable_ts": { + "type": "number", + "nullable": true + }, + "destroy_ts": { + "type": "number", + "nullable": true + }, + "sleep_ts": { + "type": "number", + "nullable": true + }, + "start_ts": { + "type": "number", + "nullable": true + }, + "error": { + "nullable": true + } + }, + "required": [ + "actor_id", + "name", + "key", + "namespace_id", + "runner_name_selector", + "create_ts" + ] + } + }, + "required": [ + "actor" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/actors/names": { + "get": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "namespace", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "names": { + "type": "object", + "additionalProperties": { + "type": "object", + "properties": { + "metadata": { + "type": "object", + "additionalProperties": { + "nullable": true + } + } + }, + "required": [ + "metadata" + ] + } + } + }, + "required": [ + "names" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/actors/{actor_id}/kv/keys/{key}": { + "get": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "actor_id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "key", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "value": { + "type": "string", + "nullable": true + } + }, + "required": [ + "value" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/gateway/{actorId}/health": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + } + ], + "responses": { + "200": { + "description": "Health check", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + } + } + } + }, + "/gateway/{actorId}/action/{action}": { + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "action", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The name of the action to execute" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "args": {} + }, + "required": [ + "args" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Action executed successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "output": {} + }, + "required": [ + "output" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Invalid action" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/gateway/{actorId}/request/{path}": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "put": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "delete": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "patch": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "head": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "options": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + } + }, + "/gateway/{actorId}/inspector/state": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Current actor state", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": {} + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + }, + "patch": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": {} + }, + "required": [ + "state" + ] + } + } + } + }, + "responses": { + "200": { + "description": "State updated", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "ok": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/connections": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Current actor connections", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "connections": { + "type": "array", + "items": { + "type": "object" + } + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/rpcs": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Available actor actions/RPCs", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "rpcs": { + "type": "object" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/action/{name}": { + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The name of the action to execute" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "args": { + "type": "array", + "items": {} + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Action executed successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "output": {} + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/queue": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 50 + }, + "description": "Maximum number of queue messages to return" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Queue status", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "size": { + "type": "integer" + }, + "maxSize": { + "type": "integer" + }, + "truncated": { + "type": "boolean" + }, + "messages": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "createdAtMs": { + "type": "integer" + } + } + } + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/traces": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "startMs", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 0 + }, + "description": "Start of time range in epoch milliseconds" + }, + { + "name": "endMs", + "in": "query", + "required": false, + "schema": { + "type": "integer" + }, + "description": "End of time range in epoch milliseconds. Defaults to now." + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 1000 + }, + "description": "Maximum number of spans to return" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Trace spans in OTLP JSON format", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "otlp": { + "type": "object" + }, + "clamped": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/workflow-history": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Workflow history and status", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "history": {}, + "isWorkflowEnabled": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/workflow/replay": { + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "entryId": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Workflow history after scheduling a replay", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "history": {}, + "isWorkflowEnabled": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/summary": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Full actor inspector summary", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": {}, + "connections": { + "type": "array", + "items": { + "type": "object" + } + }, + "rpcs": { + "type": "object" + }, + "queueSize": { + "type": "integer" + }, + "isStateEnabled": { + "type": "boolean" + }, + "isDatabaseEnabled": { + "type": "boolean" + }, + "isWorkflowEnabled": { + "type": "boolean" + }, + "workflowHistory": {} + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + } + } +} \ No newline at end of file diff --git a/.agents/skills/ai-agent/reference/actors/access-control.md b/.agents/skills/ai-agent/reference/actors/access-control.md new file mode 100644 index 0000000..02dc4e8 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/access-control.md @@ -0,0 +1,48 @@ +# Access Control + +> Source: `src/content/docs/actors/access-control.mdx` +> Canonical URL: https://rivet.dev/docs/actors/access-control +> Description: Authorize actions, queue publishes, and event subscriptions with explicit hooks. + +--- +Use access control to decide what authenticated clients are allowed to do. + +This is authorization, not authentication: + +- Use [authentication](/docs/actors/authentication) to identify who is calling. +- Use access-control rules to decide what they can do after connecting. + +## Permission Surfaces + +RivetKit authorization is explicit per surface: + +- `onBeforeConnect` rejects unauthenticated or malformed connections. +- Action handlers (`actions.*`) enforce action permissions. +- `queues..canPublish` allows or denies inbound queue publishes. +- `events..canSubscribe` allows or denies event subscriptions. + +## Fail By Default + +Use deny-by-default rules everywhere: + +1. Keep `onBeforeConnect` strict and reject invalid credentials. +2. In each action, explicitly allow expected roles and throw `forbidden` otherwise. +3. In `canPublish` and `canSubscribe`, return `true` only for allowed roles and end with `return false`. + +## Return Value Contract + +`canPublish` and `canSubscribe` must return a boolean: + +- `true`: allow +- `false`: deny with `forbidden` + +Returning `undefined`, `null`, or any non-boolean throws an internal error. + +## Notes + +- `canPublish` only applies to queue names defined in `queues`. +- Incoming queue messages for undefined queues are ignored and the publish succeeds as completed. +- `canSubscribe` only applies to event names defined in `events`. +- Broadcasting an event not defined in `events` still publishes to subscribers. + +_Source doc path: /docs/actors/access-control_ diff --git a/.agents/skills/ai-agent/reference/actors/actions.md b/.agents/skills/ai-agent/reference/actors/actions.md new file mode 100644 index 0000000..d00324e --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/actions.md @@ -0,0 +1,98 @@ +# Actions + +> Source: `src/content/docs/actors/actions.mdx` +> Canonical URL: https://rivet.dev/docs/actors/actions +> Description: Actions are how your backend, frontend, or other actors can communicate with actors. + +--- +Actions are very lightweight. They can be called thousands of times per second safely. Actions are executed via HTTP requests or via WebSockets if [using `.connect()`](/docs/actors/connections). + +For advanced use cases that require direct access to HTTP requests or WebSocket connections, see [raw HTTP and WebSocket handling](/docs/actors/fetch-and-websocket-handler). + +By default, actions run in parallel. If you need advanced control over concurrency, use [queues](/docs/actors/queues). + +## Writing Actions + +Actions are defined in the `actions` object when creating an actor: + +Each action receives a context object (commonly named `c`) as its first parameter, which provides access to state, connections, and other utilities. Additional parameters follow after that. + +## Calling Actions + +Actions can be called in different ways depending on your use case: + +### Frontend (createClient) + +Learn more about [communicating with actors from the frontend](/docs/actors/communicating-between-actors). + +### Backend (registry.handler) + +Learn more about [communicating with actors from the backend](/docs/actors/communicating-between-actors). + +### Actor-to-Actor (c.client()) + +Learn more about [communicating between actors](/docs/actors/communicating-between-actors). + +Calling actions from the client are async and require an `await`, even if the action itself is not async. + +### Type Safety + +The actor client includes type safety out of the box. When you use `createClient()`, TypeScript automatically infers action parameter and return types: + +## Error Handling + +Actors provide robust error handling out of the box for actions. + +### User Errors + +`UserError` can be used to return rich error data to the client. You can provide: + +- A human-readable message +- A machine-readable code that's useful for matching errors in a try-catch (optional) +- A metadata object for providing richer error context (optional) + +For example: + +### Internal Errors + +All other errors will return an error with the code `internal_error` to the client. This helps keep your application secure, as errors can sometimes expose sensitive information. + +## Schema Validation + +If passing data to an actor from the frontend, use a library like [Zod](https://zod.dev/) to validate input data. + +For example, to validate action parameters: + +## Streaming Data + +Actions have a single return value. To stream realtime data in response to an action, use [events](/docs/actors/events). + +## Canceling Long-Running Actions + +For operations that should be cancelable on-demand, create your own `AbortController`. Chain it with `c.abortSignal` so actor shutdown also cancels the operation. + +See [Actor Shutdown Abort Signal](/docs/actors/lifecycle#actor-shutdown-abort-signal) for automatically canceling operations when the actor stops. + +## Using `ActionContext` Externally + +When writing complex logic for actions, you may want to extract parts of your implementation into separate helper functions. When doing this, you'll need a way to properly type the context parameter. + +Rivet provides the `ActionContextOf` utility type for exactly this purpose: + +See [types](/docs/actors/types) for more details on using `ActionContextOf` and other utility types. + +## Debugging + +- `GET /inspector/rpcs` lists all available actions on an actor. +- `POST /inspector/action/:name` executes an action with JSON args and returns output. +- In non-dev mode, inspector endpoints require authorization. + +## API Reference + +- [`Actions`](/typedoc/interfaces/rivetkit.mod.Actions.html) - Interface for defining actions +- [`ActionContext`](/typedoc/interfaces/rivetkit.mod.ActionContext.html) - Context available in action handlers +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining actors with actions +- [`ActorHandle`](/typedoc/types/rivetkit.client_mod.ActorHandle.html) - Handle for calling actions from client +- [`ActorActionFunction`](/typedoc/types/rivetkit.client_mod.ActorActionFunction.html) - Type for action functions + +_Source doc path: /docs/actors/actions_ diff --git a/.agents/skills/ai-agent/reference/actors/actor-runtime-socket.md b/.agents/skills/ai-agent/reference/actors/actor-runtime-socket.md new file mode 100644 index 0000000..2f736d5 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/actor-runtime-socket.md @@ -0,0 +1,54 @@ +# Actor Runtime Socket + +> Source: `src/content/docs/actors/actor-runtime-socket.mdx` +> Canonical URL: https://rivet.dev/docs/actors/actor-runtime-socket +> Description: Connect trusted local tools to a running Rivet Actor over an experimental actor-local protocol. + +--- +> **Experimental:** The Actor Runtime Socket protocol and API may change between releases. It is available only in the Unix native runtime and must be enabled per actor. + +The **Actor Runtime Socket** is a generic, actor-local protocol for trusted tools running in the same application environment as a Rivet Actor. SQLite is its first capability; Unix domain sockets are its current transport. + +Each running actor generation lazily creates its own socket. The socket is removed when that generation sleeps, stops, or is destroyed, so clients must request the current path again after the actor wakes or restarts. + +## Enable the socket + +Enable the feature under the actor's `options`, then provision it from the actor context: + +```ts @nocheck +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +export const example = actor({ + options: { + enableActorRuntimeSocket: true, + }, + db: db({ + onMigrate: async (db) => { + await db.execute("CREATE TABLE IF NOT EXISTS items (value TEXT)"); + }, + }), + run: async (c) => { + const { path } = await c.actorRuntimeSocket(); + // Give `path` only to trusted, application-local tooling. + }, +}); +``` + +Provisioning fails unless the actor has an enabled LocalNative SQLite database. The per-process socket directory uses mode `0700`, and each actor socket uses mode `0600`. + +## Protocol + +Unix `SOCK_STREAM` provides a reliable local byte stream but does not preserve message boundaries. Every frame is therefore a four-byte big-endian payload length followed by a versioned BARE (`vbare`) payload. The embedded protocol version is a two-byte little-endian prefix. Clients begin with `ClientHello`; the server returns `HelloOk` with the maximum frame size or rejects an unsupported version. + +The current protocol supports: + +- multi-statement SQLite scripts with `SqliteExec`; +- single-statement parameterized queries with `SqliteQuery`; +- transactions spanning requests with `SqliteBegin`, `SqliteCommit`, and `SqliteRollback`. + +A transaction is identified by a client-chosen `leaseKey` scoped to one connection. Other actor SQL and other socket transactions wait in FIFO order while it runs. Transactions default to a 60-second safety timeout; `SqliteBegin.timeoutMs` may override it. If the deadline fires, RivetKit rolls the transaction back and later requests for that key receive `LeaseExpired`. + +The socket is an application-local integration boundary, not a network authentication boundary. It intentionally has no bearer token. Clients must still honor framing and response limits, and should reconnect using a newly provisioned path after actor generation changes. + +_Source doc path: /docs/actors/actor-runtime-socket_ diff --git a/.agents/skills/ai-agent/reference/actors/appearance.md b/.agents/skills/ai-agent/reference/actors/appearance.md new file mode 100644 index 0000000..f60b1a1 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/appearance.md @@ -0,0 +1,50 @@ +# Icons & Names + +> Source: `src/content/docs/actors/appearance.mdx` +> Canonical URL: https://rivet.dev/docs/actors/appearance +> Description: Customize actors with display names and icons for the Rivet inspector and dashboard. + +--- +# Icons & Names + +Actors can be customized with a display name and icon that appear in the Rivet inspector & dashboard. This helps identify actors at a glance when managing your application. + +## Configuration + +Set the `name` and `icon` properties in your actor's `options`: + +## Icon Formats + +The `icon` property accepts two formats: + +### Emoji + +Use any emoji character directly: + +### FontAwesome Icons + +Use [FontAwesome](https://fontawesome.com/search) icon names without the "fa" prefix: + +## Default Behavior + +If no `icon` is specified, actors display the default actor icon. If no `name` is specified, the actor's registry key (e.g., `chatRoom`, `gameServer`) is displayed instead. + +## Examples + +Here are some common patterns: + +## Advanced: Run Handler Metadata + +For library developers creating reusable run handlers, you can bundle icon and name metadata directly with the `run` property. This allows libraries to provide sensible defaults without requiring users to configure them manually. + +Instead of returning a function from your run handler factory, return an object with `name`, `icon`, and `run`: + +Users can then use this directly: + +This run-handler metadata is currently applied through the registry and serverless metadata paths. The native runtime and inspector config read the actor's `options.name` and `options.icon` directly, so set those explicitly if you need the name or icon to appear everywhere. + +Actor-level `options.name` and `options.icon` always take precedence, allowing users to override library defaults: + +The built-in `workflow()` helper uses this pattern to automatically display the workflow icon for workflow-based actors. + +_Source doc path: /docs/actors/appearance_ diff --git a/.agents/skills/ai-agent/reference/actors/authentication.md b/.agents/skills/ai-agent/reference/actors/authentication.md new file mode 100644 index 0000000..c456dde --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/authentication.md @@ -0,0 +1,105 @@ +# Authentication + +> Source: `src/content/docs/actors/authentication.mdx` +> Canonical URL: https://rivet.dev/docs/actors/authentication +> Description: Secure your actors with authentication and authorization. + +--- +## Do You Need Authentication? + +### Rivet Cloud + + Actors are private by default on Rivet Cloud. Only requests with the publishable token can interact with actors. + + - **Backend-only actors**: If your publishable token is only included in your backend, then authentication is not necessary. + - **Frontend-accessible actors**: If your publishable token is included in your frontend, then implementing authentication is recommended. + +### Self-Hosted + + Actors are public by default on self-hosted Rivet. Anyone can access them without a token. + + - **Only accessible within private network**: If Rivet is only accessible within your private network, then authentication is not necessary. + - **Rivet exposed to the public internet**: If Rivet is configured to accept traffic from the public internet, then implementing authentication is recommended. + +## Authentication Connections + +Authentication is configured through either: + +- `onBeforeConnect` for simple pass/fail validation +- `createConnState` when you need to access user data in your actions via `c.conn.state` + +## Access Control + +After a connection is authenticated, use [Access Control](/docs/actors/access-control) to enforce authorization: + +- Check permissions in action handlers. +- Use `queues..canPublish` to gate inbound queue publishes. +- Use `events..canSubscribe` to gate event subscriptions. + +### `onBeforeConnect` + +The `onBeforeConnect` hook validates credentials before allowing a connection. Throw an error to reject the connection. + +### `createConnState` + +Use `createConnState` to extract user data from credentials and store it in connection state. This data is accessible in actions via `c.conn.state`. Like `onBeforeConnect`, throwing an error will reject the connection. See [connections](/docs/actors/connections) for more details. + +## Available Auth Data + +Authentication hooks have access to several properties: + +| Property | Description | +|----------|-------------| +| `params` | Custom data passed by the client when connecting (see [connection params](/docs/actors/connections#extracting-data-from-connection-params)) | +| `c.request` | The underlying HTTP request object | +| `c.request.headers` | Request headers for tokens, API keys (does not work for `.connect()`) | +| `c.state` | Actor state for authorization decisions (see [state](/docs/actors/state)) | +| `c.key` | The actor's key (see [keys](/docs/actors/keys)) | + +It's recommended to use `params` instead of `c.request.headers` whenever possible since it works for both HTTP & WebSocket connections. + +## Client Usage + +### Passing Credentials + +Pass authentication data when connecting. Use `getParams` when you need a fresh JWT for every connection or reconnect: + +### Handling Errors + +Authentication errors use the same system as regular errors. See [errors](/docs/actors/errors) for more details. + +## Examples + +### JWT + +Validate JSON Web Tokens and extract user claims: + +### External Auth Provider + +Validate credentials against an external authentication service: + +### Using `c.state` In Authorization + +Access actor state via `c.state` and the actor's key via `c.key` to make authorization decisions: + +### Role-Based Access Control + +Create helper functions for common authorization patterns: + +### Rate Limiting + +Use `c.vars` to track connection attempts and rate limit by user: + +The limits in this example are [ephemeral](/docs/actors/state#ephemeral-variables). If you wish to persist rate limits, you can optionally replace `vars` with `state`. + +### Caching Tokens + +Cache validated tokens in `c.vars` to avoid redundant validation on repeated connections. See [ephemeral variables](/docs/actors/state#ephemeral-variables) for more details. + +## API Reference + +- [`AuthIntent`](/typedoc/types/rivetkit.mod.AuthIntent.html) - Authentication intent type +- [`OnBeforeConnectContext`](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html) - Context for auth checks +- [`OnConnectContext`](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html) - Context after connection + +_Source doc path: /docs/actors/authentication_ diff --git a/.agents/skills/ai-agent/reference/actors/communicating-between-actors.md b/.agents/skills/ai-agent/reference/actors/communicating-between-actors.md new file mode 100644 index 0000000..8aeaf39 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/communicating-between-actors.md @@ -0,0 +1,42 @@ +# Communicating Between Actors + +> Source: `src/content/docs/actors/communicating-between-actors.mdx` +> Canonical URL: https://rivet.dev/docs/actors/communicating-between-actors +> Description: Learn how actors can call other actors and share data + +--- +Actors can communicate with each other using the server-side actor client, enabling complex workflows and data sharing between different actor instances. + +We recommend reading the [clients documentation](/docs/clients) first. This guide focuses specifically on communication between actors. + +## Using the Server-Side Actor Client + +The server-side actor client allows actors to call other actors within the same registry. Access it via `c.client()` in your actor context: + +If two actors call each other and their return types are inferred from the other actor's response, you may hit circular type errors (`TS2322`, `TS2722`, or `c.state` becoming `unknown`). Fix this by writing explicit return types on those actions. + +## Use Cases and Patterns + +### Actor Orchestration + +Use a coordinator actor to manage complex workflows: + +### Data Aggregation + +Collect data from multiple actors: + +### Event-Driven Architecture + +Use connections to listen for events from other actors: + +### Batch Operations + +Process multiple items in parallel: + +## API Reference + +- [`ActorHandle`](/typedoc/types/rivetkit.client_mod.ActorHandle.html) - Handle for calling other actors +- [`Client`](/typedoc/types/rivetkit.mod.Client.html) - Client type for actor communication +- [`ActorAccessor`](/typedoc/interfaces/rivetkit.client_mod.ActorAccessor.html) - Accessor for getting actor handles + +_Source doc path: /docs/actors/communicating-between-actors_ diff --git a/.agents/skills/ai-agent/reference/actors/connections.md b/.agents/skills/ai-agent/reference/actors/connections.md new file mode 100644 index 0000000..10ef081 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/connections.md @@ -0,0 +1,119 @@ +# Connections + +> Source: `src/content/docs/actors/connections.mdx` +> Canonical URL: https://rivet.dev/docs/actors/connections +> Description: Connections represent client connections to your actor. They provide a way to handle client authentication, manage connection-specific data, and control the connection lifecycle. + +--- +For documentation on connecting to actors from clients, see the [Clients documentation](/docs/clients). For worked presence and chat patterns, see the cookbook: [Live Cursors and Presence](/cookbook/live-cursors/) and [Chat Room](/cookbook/chat-room/). + +## Parameters + +When clients connect to an actor, they can pass connection parameters that are handled during the connection process. Use `params` for static values, or `getParams` when you need fresh connection data each time a connection opens. + +For example: + +## Connection State + +There are two ways to define an actor's connection state: + + +### connState + + Define connection state as a constant value: + + + + This value will be cloned for every new connection using `structuredClone`. + + + +### createConnState + + Create connection state dynamically with a function called for each connection: + + + + +## Connection Lifecycle + +Each client connection goes through a series of lifecycle hooks that allow you to validate, initialize, and clean up connection-specific resources. + +**On Connect** (per client) + +- `onBeforeConnect` +- `createConnState` +- `onConnect` + +Pending connections are not visible in `c.conns` while `onBeforeConnect` or `createConnState` is running. RivetKit adds the connection to `c.conns` after those hooks succeed and before `onConnect` runs. + +**On Disconnect** (per client) + +- `onDisconnect` + +### `createConnState` and `connState` + +[API Reference](/typedoc/interfaces/rivetkit.mod.CreateConnStateContext.html) + +There are two ways to define the initial state for connections: +1. `connState`: Define a constant object that will be used as the initial state for all connections +2. `createConnState`: A function that dynamically creates initial connection state based on connection parameters. Can be async. + +Connections are not visible in `c.conns` until `createConnState` completes successfully. + +### `onBeforeConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html) + +The `onBeforeConnect` hook is called whenever a new client connects to the actor. Can be async. Clients can pass parameters when connecting, accessible via `params`. This hook is used for connection validation and can throw errors to reject connections. + +The `onBeforeConnect` hook does NOT return connection state - it's used solely for validation. + +Connections are not visible in `c.conns` while `onBeforeConnect` is running. + +Connections cannot interact with the actor until this method completes successfully. Throwing an error will abort the connection. This can be used for authentication, see [Authentication](/docs/actors/authentication) for details. + +### `onConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html) + +Executed after the client has successfully connected. Can be async. Receives the connection object as a second parameter. + +By the time `onConnect` runs, the connection is visible in `c.conns`. + +Messages will not be processed for this actor until this hook succeeds. Errors thrown from this hook will cause the client to disconnect. + +### `onDisconnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Called when a client disconnects from the actor. Can be async. Receives the connection object as a second parameter. Use this to clean up any connection-specific resources. + +## Connection List + +All active connections can be accessed through the context object's `conns` property. This is a `Map` of all current connections, keyed by connection ID. + +This is frequently used with `conn.send(name, event)` to send messages directly to clients. To send an event to all connections at once, use `c.broadcast()` instead. See [Events](/docs/actors/events) for more details on broadcasting. + +For example: + +`conn.send()` has no effect on [low-level WebSocket connections](/docs/actors/websocket-handler). For low-level WebSockets, use the WebSocket API directly (e.g., `websocket.send()`). + +## Disconnecting clients + +Connections can be disconnected from within an action: + +If you need to wait for the disconnection to complete, you can use `await`: + +This ensures the underlying network connections close cleanly before continuing. + +## API Reference + +- [`Conn`](/typedoc/interfaces/rivetkit.mod.Conn.html) - Connection interface +- [`ConnInitContext`](/typedoc/interfaces/rivetkit.mod.ConnInitContext.html) - Connection initialization context +- [`CreateConnStateContext`](/typedoc/interfaces/rivetkit.mod.CreateConnStateContext.html) - Context for creating connection state +- [`OnBeforeConnectContext`](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html) - Pre-connection lifecycle hook context +- [`OnConnectContext`](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html) - Post-connection lifecycle hook context +- [`ActorConn`](/typedoc/types/rivetkit.client_mod.ActorConn.html) - Typed connection from client side + +_Source doc path: /docs/actors/connections_ diff --git a/.agents/skills/ai-agent/reference/actors/debugging.md b/.agents/skills/ai-agent/reference/actors/debugging.md new file mode 100644 index 0000000..409b381 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/debugging.md @@ -0,0 +1,644 @@ +# Debugging + +> Source: `src/content/docs/actors/debugging.mdx` +> Canonical URL: https://rivet.dev/docs/actors/debugging +> Description: Inspect and debug running Rivet Actors, runners, and provider configs using management, runner, and actor inspector HTTP APIs. + +--- +## Connecting to Rivet + +All debugging endpoints in this guide are available both locally and in production. In local development, the base URL is `http://localhost:6420` with no authentication. In production (Rivet Cloud or self-hosted), you connect to your Rivet Engine endpoint with a token. + +### Setup + +All examples in this guide use these shell variables. Extract them from your `RIVET_ENDPOINT` (`https://:@`): + +```bash +# From RIVET_ENDPOINT=https://my-namespace:sk_abc123@api.rivet.dev +export RIVET_API="https://api.rivet.dev" +export RIVET_NAMESPACE="my-namespace" +export RIVET_TOKEN="sk_abc123" + +# For local development: +# export RIVET_API="http://localhost:6420" +``` + +Rivet Cloud issues two token types: `sk_` (secret key, server-side only) and `pk_` (public key, client-safe). For debugging, always use `sk_`. See [Endpoints](/docs/general/endpoints) for more details. + +## Management API + +The management API runs on the manager base path (default root path) and is used to list, create, and look up actors. + +### Authentication + +| Environment | Authentication | +|---|---| +| **Local development** | No authentication required. All endpoints are accessible without tokens. | +| **Self-hosted engine** | Set `RIVET_TOKEN` to enable authenticated access to restricted endpoints like KV. | +| **Rivet Cloud** | Authentication is enforced by your deployment entrypoint. For manager KV access, use the bearer token header below when enabled. | + +Restricted endpoints (like KV reads) require the `Authorization: Bearer` header when `RIVET_TOKEN` is configured: + +```bash +curl "$RIVET_API/actors/{actor_id}/kv/keys/{base64_key}" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +### List Actors + +```bash +# List all actors with a given name +curl "$RIVET_API/actors?name=my-actor&namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" + +# Look up one actor by key (name is required when key is provided) +curl "$RIVET_API/actors?name=my-actor&key=%5B%22my-key%22%5D&namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" + +# List actors by IDs (comma-separated) +curl "$RIVET_API/actors?actor_ids=id1,id2&namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Rules: + +- `key` requires `name`. +- `actor_ids` cannot be combined with `name` or `key`. + +Returns: + +```json +{ + "actors": [ + { + "actor_id": "abc123", + "name": "my-actor", + "key": "[\"default\"]", + "namespace_id": "default", + "create_ts": 1706000000000 + } + ] +} +``` + +### Create Actor + +`POST /actors` creates a new actor. + +```bash +curl -X POST "$RIVET_API/actors?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H 'Content-Type: application/json' \ + -d '{ + "name": "my-actor", + "runner_name_selector": "default", + "crash_policy": "restart" + }' +``` + +### Create or Get Actor + +`PUT /actors` creates an actor if it does not exist, otherwise returns the existing one. + +```bash +curl -X PUT "$RIVET_API/actors?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H 'Content-Type: application/json' \ + -d '{ + "name": "my-actor", + "key": "[\"default\"]", + "runner_name_selector": "default", + "crash_policy": "restart" + }' +``` + +Returns the actor object with its `actor_id`. + +### List Actor Names + +```bash +curl "$RIVET_API/actors/names?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns all registered actor names and their metadata. + +### Read Actor KV + +Requires authentication (see above). + +```bash +curl "$RIVET_API/actors/{actor_id}/kv/keys/{base64_key}" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns the value stored at the given key in the actor KV compatibility snapshot. After an actor has migrated to SQLite-backed runtime storage, this endpoint is stale for user KV and internal runtime records; it continues to expose the frozen pre-migration KV data. The inspector token key is the exception and remains mirrored for dashboard compatibility. + +See the [OpenAPI spec](https://github.com/rivet-dev/rivet/tree/main/rivetkit-openapi) for the full schema of all management endpoints. + +## Runner API + +Use the runner endpoints to debug scheduler capacity and provider configuration (for example serverless URL, headers, and limits) through the Rivet API. + +### List Runner Names + +```bash +curl "$RIVET_API/runners/names?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns the runner pools available in the namespace: + +```json +{ + "names": ["default", "gpu-workers"], + "pagination": { "cursor": null } +} +``` + +### List Runners in a Pool + +```bash +curl "$RIVET_API/runners?namespace=$RIVET_NAMESPACE&name=default&include_stopped=true&limit=100" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Useful fields when debugging: + +- `remaining_slots` / `total_slots` for capacity. +- `drain_ts` and `stop_ts` for shutdown behavior. +- `last_ping_ts` and `last_connected_ts` for connectivity. + +### Inspect Provider Config (Runner Config) + +```bash +curl "$RIVET_API/runner-configs?namespace=$RIVET_NAMESPACE&runner_name=default" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns the configured provider settings per datacenter and the latest pool error (if any): + +```json +{ + "runner_configs": { + "default": { + "datacenters": { + "dc-1": { + "serverless": { + "url": "https://your-deployment.example.com/rivet", + "headers": { "Authorization": "Bearer token" }, + "request_lifespan": 55, + "slots_per_runner": 1, + "max_runners": 10 + }, + "runner_pool_error": null + } + } + } + }, + "pagination": { "cursor": null } +} +``` + +`runner_pool_error` mirrors actor scheduling errors such as `serverless_http_error`, `serverless_connection_error`, and `serverless_stream_ended_early`. + +### Check Serverless Provider Health + +Use this to test whether Rivet can reach your serverless provider URL and read runner metadata: + +```bash +curl -X POST "$RIVET_API/runner-configs/serverless-health-check?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "url": "https://your-deployment.example.com/rivet", + "headers": { + "Authorization": "Bearer token" + } + }' +``` + +Possible responses: + +```json +{ "success": { "version": "1.2.3" } } +``` + +```json +{ + "failure": { + "error": { + "message": "non-success status from metadata endpoint", + "details": "received status 503" + } + } +} +``` + +### Refresh Provider Metadata + +If you deploy new actor code or routes and metadata has not updated yet, force a refresh: + +```bash +curl -X POST "$RIVET_API/runner-configs/default/refresh-metadata?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{}' +``` + +## Actor API + +All actor-level endpoints are accessed through the gateway. The gateway routes requests to the correct actor instance using the actor ID in the URL path: + +``` +{RIVET_API}/gateway/{actor_id}/{path} +``` + +The gateway only accepts actor IDs, not names. Use `GET /actors?name=...` from the management API to look up actor IDs first. + +### Authentication + +Standard actor endpoints (health, actions, requests) and inspector endpoints have separate authentication requirements. + +#### Standard Endpoints + +| Environment | Authentication | +|---|---| +| **Local development** | No authentication required. | +| **Self-hosted engine** | The Rivet Engine handles authentication at the gateway level. | +| **Rivet Cloud** | Authentication is handled by the Rivet Cloud platform at the gateway level. | + +#### Inspector Endpoints + +Each actor generates a unique inspector token on first start and persists it in internal SQLite storage. It is also mirrored to legacy KV key `0x03` (base64 `Aw==`) for dashboard compatibility. Pass it as a bearer token in the `Authorization` header. + +Inspector endpoints always require the actor's inspector token, including in local development. There is no local-development bypass. + +| Environment | Authentication | +|---|---| +| **Local development** | Bearer the actor's inspector token in the `Authorization` header. Fetch it through the management KV endpoint (see below). | +| **Self-hosted engine** | Bearer the actor's inspector token in the `Authorization` header. The Rivet dashboard fetches it automatically; for direct API access, fetch it through the management KV endpoint (see below). | +| **Rivet Cloud** | Bearer the actor's inspector token in the `Authorization` header. The Rivet dashboard fetches it automatically; for direct API access, fetch it through the management KV endpoint (see below). | + +```bash +curl "$RIVET_API/gateway/{actor_id}/inspector/summary" \ + -H 'Authorization: Bearer YOUR_INSPECTOR_TOKEN' +``` + +#### Retrieving the Inspector Token + +Each actor generates a unique inspector token on first start and persists it in internal SQLite storage. The token is also mirrored to the legacy KV key below so the Rivet dashboard can continue to retrieve it through the management KV endpoint. This applies in every environment, including local development. + +The inspector token is stored at internal KV key `0x03` (base64: `Aw==`). The response value is also base64-encoded. + +```bash +# Fetch the inspector token for a specific actor +ACTOR_ID="your-actor-id" + +RESPONSE=$(curl -s "$RIVET_API/actors/$ACTOR_ID/kv/keys/Aw==" \ + -H "Authorization: Bearer $RIVET_TOKEN") + +# Extract and decode the base64 value +INSPECTOR_TOKEN=$(echo "$RESPONSE" | jq -r '.value' | base64 -d) + +# Use it to call inspector endpoints +curl "$RIVET_API/gateway/$ACTOR_ID/inspector/summary" \ + -H "Authorization: Bearer $INSPECTOR_TOKEN" +``` + +### Standard Actor Endpoints + +These are the built-in actor endpoints available through the gateway: + +```bash +# Health check +curl $RIVET_API/gateway/{actor_id}/health + +# Metadata +curl $RIVET_API/gateway/{actor_id}/metadata + +# Call an action +curl -X POST $RIVET_API/gateway/{actor_id}/action/myAction \ + -H 'Content-Type: application/json' \ + -d '{"args": [1, 2, 3]}' + +# Send queue message (queue name in path) +curl -X POST $RIVET_API/gateway/{actor_id}/queue/jobs \ + -H 'Content-Type: application/json' \ + -d '{"body":{"id":"job-1"}}' + +# Send queue message and wait for completion (optional timeout in ms) +curl -X POST $RIVET_API/gateway/{actor_id}/queue/jobs \ + -H 'Content-Type: application/json' \ + -d '{"body":{"id":"job-1"},"wait":true,"timeout":5000}' + +# Forward an HTTP request to the actor's onRequest handler +curl $RIVET_API/gateway/{actor_id}/request/my/custom/path +``` + +Queue send responses always include a `status` field: + +```json +{ "status": "completed" } +``` + +The `response` field is only present when the queue handler returns a value: + +```json +{ "status": "completed", "response": { "result": "ok" } } +``` + +If `wait: true` and the timeout is reached, `status` is `"timedOut"`. + +### Inspector Endpoints + +The inspector HTTP API exposes JSON endpoints for querying and modifying actor internals at runtime. These are designed for agent-based debugging and tooling. + +Every inspector endpoint requires the actor's inspector token as a bearer token, including in local development. The examples below omit the `Authorization` header for brevity, but you must add `-H "Authorization: Bearer $INSPECTOR_TOKEN"` to each request. See [Retrieving the Inspector Token](#retrieving-the-inspector-token) above. + +#### Get State + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/state +``` + +Returns the actor's current persisted state: + +```json +{ + "state": { "count": 42, "users": [] }, + "isStateEnabled": true +} +``` + +#### Set State + +```bash +curl -X PATCH $RIVET_API/gateway/{actor_id}/inspector/state \ + -H 'Content-Type: application/json' \ + -d '{"state": {"count": 0, "users": []}}' +``` + +Returns: + +```json +{ "ok": true } +``` + +#### Get Connections + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/connections +``` + +Returns all active connections with their params, state, and metadata: + +```json +{ + "connections": [ + { + "type": "websocket", + "id": "conn-id", + "details": { + "type": "websocket", + "params": {}, + "stateEnabled": true, + "state": {}, + "subscriptions": 2, + "isHibernatable": true + } + } + ] +} +``` + +#### Get RPCs + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/rpcs +``` + +Returns a list of available actions: + +```json +{ "rpcs": ["increment", "getCount"] } +``` + +#### Execute Action + +```bash +curl -X POST $RIVET_API/gateway/{actor_id}/inspector/action/increment \ + -H 'Content-Type: application/json' \ + -d '{"args": [5]}' +``` + +Returns: + +```json +{ "output": 47 } +``` + +#### Get Queue Status + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/queue?limit=10 +``` + +Returns queue status with messages: + +```json +{ + "size": 3, + "maxSize": 1000, + "truncated": false, + "messages": [ + { "id": 1, "name": "process", "createdAtMs": 1706000000000 } + ] +} +``` + +#### Get Workflow History + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/workflow-history +``` + +Returns: + +```json +{ + "history": null, + "isWorkflowEnabled": false +} +``` + +#### Get Database Schema + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/database/schema +``` + +Returns discovered SQLite tables and views when the actor has `c.db` enabled: + +```json +{ + "schema": { + "tables": [ + { + "table": { "schema": "main", "name": "test_data", "type": "table" }, + "columns": [ + { "cid": 0, "name": "id", "type": "", "notnull": 0, "dflt_value": null, "pk": 0 } + ], + "foreignKeys": [], + "records": 2 + } + ] + } +} +``` + +#### Get Database Rows + +```bash +curl "$RIVET_API/gateway/{actor_id}/inspector/database/rows?table=test_data&limit=100&offset=0" +``` + +Returns paged rows for a specific SQLite table or view: + +```json +{ + "rows": [ + { + "id": 1, + "value": "Alice", + "payload": "", + "created_at": 1706000000000 + } + ] +} +``` + +#### Execute SQLite + +Run manual SQL against an actor's SQLite database. This supports both read-only queries and mutations. + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/database/execute \ + -H 'Content-Type: application/json' \ + -d '{ + "sql": "SELECT id, value FROM test_data WHERE value = ? ORDER BY id DESC", + "args": ["alpha"] + }' +``` + +Returns: + +```json +{ + "rows": [ + { "id": 2, "value": "alpha" } + ] +} +``` + +You can also use named SQLite bindings through a `properties` object: + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/database/execute \ + -H 'Content-Type: application/json' \ + -d '{ + "sql": "SELECT id, value FROM test_data WHERE value = :value ORDER BY id DESC", + "properties": { + "value": "alpha" + } + }' +``` + +For mutations, use `RETURNING` if you want rows back. Otherwise the statement still runs and `rows` is empty: + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/database/execute \ + -H 'Content-Type: application/json' \ + -d '{ + "sql": "INSERT INTO test_data (value, created_at) VALUES (?, ?) RETURNING id, value", + "args": ["beta", 1706000000000] + }' +``` + +For workflow-enabled actors, `history` is a JSON object with `nameRegistry`, `entries`, and `entryMetadata`. Step outputs, loop state, and message payloads are decoded from CBOR into normal JSON values. + +#### Replay Workflow From Step + +Reset a workflow to a specific step and restart execution immediately. Omitting `entryId` replays the workflow from the beginning. + +If the workflow is still running when you call replay, the endpoint rejects the request with `409 Conflict` and an `actor/workflow_in_flight` error instead of cancelling the live run for you. + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/workflow/replay \ + -H 'Content-Type: application/json' \ + -d '{"entryId":"workflow-step-id"}' +``` + +Returns the same JSON shape as `/inspector/workflow-history`: + +```json +{ + "history": { + "nameRegistry": ["step-one", "step-two"], + "entries": [], + "entryMetadata": {} + }, + "isWorkflowEnabled": true +} +``` + +While a workflow is in flight, the response shape is: + +```json +{ + "group": "actor", + "code": "workflow_in_flight", + "message": "Workflow replay is unavailable while the workflow is currently in flight.", + "metadata": null +} +``` + +#### Summary + +Get a full snapshot of the actor in a single request: + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/summary +``` + +Returns: + +```json +{ + "state": { "count": 42 }, + "connections": [], + "rpcs": ["increment", "getCount"], + "queueSize": 0, + "isStateEnabled": true, + "isDatabaseEnabled": false, + "isWorkflowEnabled": false, + "workflowHistory": null +} +``` + +When workflow history is present in `/inspector/summary`, `workflowHistory` is returned as the same decoded JSON shape as `/inspector/workflow-history`. + +### Polling + +Inspector endpoints are safe to poll. For live monitoring, poll at 1-5 second intervals. The `/inspector/summary` endpoint is useful for periodic snapshots since it returns all data in a single request. + +## OpenAPI Spec + +An OpenAPI specification covering many of the management and actor endpoints is available: + +- In the repository at [`rivetkit-openapi/openapi.json`](https://github.com/rivet-dev/rivet/tree/main/rivetkit-openapi) +- Served at `/doc` on the manager when running locally + +The checked-in spec does not yet list every endpoint documented on this page (for example the actor metadata and queue routes and the inspector database routes), so treat this page as the authoritative reference where they differ. + +_Source doc path: /docs/actors/debugging_ diff --git a/.agents/skills/ai-agent/reference/actors/design-patterns.md b/.agents/skills/ai-agent/reference/actors/design-patterns.md new file mode 100644 index 0000000..77ecb40 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/design-patterns.md @@ -0,0 +1,163 @@ +# Design Patterns + +> Source: `src/content/docs/actors/design-patterns.mdx` +> Canonical URL: https://rivet.dev/docs/actors/design-patterns +> Description: Common patterns and anti-patterns for building scalable actor systems. + +--- +## How Actors Scale + +Actors are inherently scalable because of how they're designed: + +- **Isolated state:** Each actor manages its own private data. No shared state means no conflicts and no locks, so actors run concurrently without coordination. +- **Actor-to-actor communication:** Actors interact through [actions](/docs/actors/actions) and [events](/docs/actors/events), so they don't need to coordinate access to shared data. This makes it easy to distribute them across machines. +- **Small, focused units:** Each actor handles a limited scope (a single user, document, or chat room), so load naturally spreads across many actors rather than concentrating in one place. +- **Horizontal scaling:** Adding more machines automatically distributes actors across them. + +These properties form the foundation for the patterns described below. + +## Actor Per Entity + +The core pattern is creating one actor per entity in your system. Each actor represents a single user, document, chat room, or other distinct object. This keeps actors small, independent, and easy to scale. + +**Good examples** + +- `User`: Manages user profile, preferences, and authentication +- `Document`: Handles document content, metadata, and versioning +- `ChatRoom`: Manages participants and message history + +**Bad examples** + +- `Application`: Too broad, handles everything +- `DocumentWordCount`: Too granular, should be part of Document actor + +## Coordinator & Data Actors + +Actors scale by splitting state into isolated entities. However, it's common to need to track and coordinate actors in a central place. This is where coordinator actors come in. + +**Data actors** handle the main logic in your application. Examples: chat rooms, user sessions, game lobbies. + +**Coordinator actors** track other actors. Think of them as an index of data actors. Examples: a list of chat rooms, a list of active users, a list of game lobbies. + +**Example: Chat Room Coordinator** + +### Actor + +### Client + +## Sharding + +Sharding splits a single actor's workload across multiple actors based on a key. Use this when one actor can't handle all the load or data for an entity. + +**How it works:** +- Partition data using a shard key (user ID, region, time bucket, or random) +- Requests are routed to shards based on the key +- Shards operate independently without coordination + +**Example: Sharding by Time** + +### Actor + +### Client + +**Example: Random Sharding** + +### Actor + +### Client + +Choose shard keys that distribute load evenly. Note that cross-shard queries require coordination. + +## Fan-In & Fan-Out + +Fan-in and fan-out are patterns for distributing work and aggregating results. + +**Fan-Out**: One actor spawns work across multiple actors. Use for parallel processing or broadcasting updates. + +**Fan-In**: Multiple actors send results to one aggregator. Use for collecting results or reducing data. + +**Example: Map-Reduce** + +### Actor + +### Client + +## Integrating With External Databases & APIs + +Actors can integrate with external resources like databases or external APIs. + +### Loading State + +Load external data during actor initialization using `createVars`. This keeps your actor's persisted state clean while caching expensive lookups. + +Use this when: + +- Fetching user profiles, configs, or permissions from a database +- Loading data that changes externally and shouldn't be persisted +- Caching expensive API calls or computations + +**Example: Loading User Profile** + +### Actor + +### Client + +### Syncing State Changes + +Use `onStateChange` to automatically sync actor state changes to external resources. This hook runs after state changes are flushed, which is coalesced to once per event loop tick rather than once per individual field mutation. + +Use this when: + +- You need to mirror actor state in an external database +- Triggering external side effects when state changes +- Keeping external systems in sync with actor state + +**Example: Syncing to Database** + +### Actor + +### Client + +`onStateChange` is called once per flush with the final coalesced state, ensuring external resources stay in sync. In the `updateEmail` example above, the two synchronous assignments produce a single `onStateChange` call. + +Do not mutate `c.state` inside `onStateChange`; re-entrant state mutation is rejected. + +## Anti-Patterns + +### "God" Actor + +Avoid creating a single actor that handles everything. This defeats the purpose of the actor model and creates a bottleneck. + +**Problem:** +```ts +import { actor } from "rivetkit"; + +// Bad: one actor doing everything +const app = actor({ + state: { users: {}, orders: {}, inventory: {}, analytics: {} }, + actions: { + createUser: (c, user) => { /* ... */ }, + processOrder: (c, order) => { /* ... */ }, + updateInventory: (c, item) => { /* ... */ }, + trackEvent: (c, event) => { /* ... */ }, + }, +}); +``` + +**Solution:** Split into focused actors per entity (User, Order, Inventory, Analytics). + +### Actor-Per-Request + +Actors are designed to maintain state across multiple requests. Creating a new actor for each request wastes resources and loses the benefits of persistent state. + +**Problem:** + +**Solution:** Use actors for entities that persist (users, sessions, documents), not for one-off operations. For stateless request handling, use regular functions. + +## API Reference + +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for pattern examples +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - Context usage patterns +- [`ActionContext`](/typedoc/interfaces/rivetkit.mod.ActionContext.html) - Action patterns + +_Source doc path: /docs/actors/design-patterns_ diff --git a/.agents/skills/ai-agent/reference/actors/destroy.md b/.agents/skills/ai-agent/reference/actors/destroy.md new file mode 100644 index 0000000..87e1b76 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/destroy.md @@ -0,0 +1,71 @@ +# Destroying Actors + +> Source: `src/content/docs/actors/destroy.mdx` +> Canonical URL: https://rivet.dev/docs/actors/destroy +> Description: Actors can be permanently destroyed. Common use cases include: + +--- +- User account deletion +- Ending a user session +- Closing a room or game +- Cleaning up temporary resources +- GDPR/compliance data removal + +Actors sleep when idle, so destruction is only needed to permanently remove data — not to save compute. + +## Destroying An Actor + +### Destroy via Action + +To destroy an actor, use `c.destroy()` like this: + +### Destroy via HTTP + +Send a DELETE request to destroy an actor. This requires a token for authentication: + +- **Rivet Cloud**: Use the service key (`sk_*`) from your `RIVET_ENDPOINT` URL. Find this in the dashboard under **Settings > Advanced > Backend Configuration** (e.g. the `sk_...` portion of `https://default:sk_abc123@api.rivet.dev`). +- **Self-hosted**: Use an admin token. + +```typescript +const actorId = "your-actor-id"; +const namespace = "default"; +const token = "your-token"; + +await fetch(`https://api.rivet.dev/actors/${actorId}?namespace=${namespace}`, { + method: "DELETE", + headers: { + Authorization: `Bearer ${token}`, + }, +}); +``` + +```bash +curl -X DELETE "https://api.rivet.dev/actors/{actorId}?namespace={namespace}" \ + -H "Authorization: Bearer {token}" +``` + +To find the actor ID, you can list actors first: + +```bash +curl "https://api.rivet.dev/actors?namespace={namespace}" \ + -H "Authorization: Bearer {token}" +``` + +### Destroy via Dashboard + +To destroy an actor via the dashboard, navigate to the actor and press the red "X" in the top right. + +## Lifecycle Hook + +Once destroyed, the `onDestroy` hook will be called. This can be used to clean up resources related to the actor. For example: + +## Accessing Actor After Destroy + +Once an actor is destroyed, any subsequent requests to it will fail with an `actor.not_found` error (`{ group: "actor", code: "not_found" }`). The actor's state is permanently deleted. + +## API Reference + +- [`ActorHandle`](/typedoc/types/rivetkit.client_mod.ActorHandle.html) - Has destroy methods +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - Context during destruction + +_Source doc path: /docs/actors/destroy_ diff --git a/.agents/skills/ai-agent/reference/actors/errors.md b/.agents/skills/ai-agent/reference/actors/errors.md new file mode 100644 index 0000000..af24c4c --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/errors.md @@ -0,0 +1,81 @@ +# Errors + +> Source: `src/content/docs/actors/errors.mdx` +> Canonical URL: https://rivet.dev/docs/actors/errors +> Description: Rivet provides robust error handling with security built in by default. Errors are handled differently based on whether they should be exposed to clients or kept private. + +--- +There are two types of errors: + +- **UserError**: Thrown from actors and safely returned to clients with full details +- **Internal errors**: All other errors that are converted to a generic error message for security + +## Throwing and Catching Errors + +`UserError` lets you throw custom errors that will be safely returned to the client. + +Throw a `UserError` with just a message: + +### Actor + +### Client (Connection) + +### Client (Stateless) + +## Error Codes + +Use error codes for explicit error matching in try-catch blocks: + +### Actor + +### Client (Connection) + +### Client (Stateless) + +## Errors With Metadata + +Include metadata to provide additional context for rich error handling: + +### Actor + +### Client (Connection) + +### Client (Stateless) + +## Internal Errors + +All errors that are not UserError instances are automatically converted to a generic "internal error" response. This prevents accidentally leaking sensitive information like stack traces, database details, or internal system information. + +### Actor + +### Client (Connection) + +### Client (Stateless) + +### Server-Side Logging + +**All internal errors are logged server-side with full details.** When an internal error occurs, the complete error message, stack trace, and context are written to your server logs. This is where you should look first when debugging internal errors in production. + +The client receives only a generic "Internal error" message for security, but you can find the full error details in your server logs including: + +- Complete error message +- Stack trace +- Request context (actor ID, action name, connection ID, etc.) +- Timestamp + +**Always check your server logs to see the actual error details when debugging internal errors.** + +### Exposing Errors to Clients (Development Only) + +**Warning:** Only enable error exposure in development environments. In production, this will leak sensitive internal details to clients. + +For faster debugging during development, you can expose internal error details to clients by setting `RIVET_EXPOSE_ERRORS=1`. + +With error exposure enabled, clients will see the full error message instead of the generic "Internal error" response: + +## API Reference + +- [`UserError`](/typedoc/classes/rivetkit.actor_errors.UserError.html) - User-facing error class +- [`ActorError`](/typedoc/classes/rivetkit.client_mod.ActorError.html) - Errors received by the client + +_Source doc path: /docs/actors/errors_ diff --git a/.agents/skills/ai-agent/reference/actors/events.md b/.agents/skills/ai-agent/reference/actors/events.md new file mode 100644 index 0000000..ec4a7d5 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/events.md @@ -0,0 +1,145 @@ +# Realtime + +> Source: `src/content/docs/actors/events.mdx` +> Canonical URL: https://rivet.dev/docs/actors/events +> Description: Events enable realtime communication from actors to clients. While clients use actions to send data to actors, events allow actors to push updates to connected clients instantly. + +--- +Events can be sent to clients connected using `.connect()`. They have no effect on [low-level WebSocket connections](/docs/actors/websocket-handler). + +For worked realtime patterns, see the cookbook: [Live Cursors and Presence](/cookbook/live-cursors/) and [Chat Room](/cookbook/chat-room/). + +## Publishing Events from Actors + +### Broadcasting to All Clients + +Define event names and payload types with `events` and `event()`, then use `c.broadcast(eventName, ...args)` to send events to all connected clients: + +### Sending to Specific Connections + +Send events to individual connections using `conn.send(eventName, ...args)`: + +Send events to all connections except the sender: + +## Subscribing to Events from Clients + +Clients must establish a connection to receive events from actors. Use `.connect()` to create a persistent connection, then listen for events. + +### Basic Event Subscription + +Use `connection.on(eventName, callback)` to listen for events: + +```tsx React @nocheck +import { useState } from "react"; +import { useActor } from "./rivetkit"; + +function ChatRoom() { + const [messages, setMessages] = useState>([]); + + const chatRoom = useActor({ + name: "chatRoom", + key: ["general"] + }); + + // Listen for events + chatRoom.useEvent("messageReceived", (message) => { + setMessages(prev => [...prev, message]); + }); + + // ...rest of component... +} +``` + +### One-time Event Listeners + +Use `connection.once(eventName, callback)` for events that should only trigger once: + +```tsx React @nocheck +import { useState, useEffect } from "react"; +import { useActor } from "./rivetkit"; + +function GameLobby() { + const [gameStarted, setGameStarted] = useState(false); + + const gameRoom = useActor({ + name: "gameRoom", + key: ["room-456"], + params: { + playerId: "player-789", + role: "player" + } + }); + + // Listen for game start (only once) + useEffect(() => { + if (!gameRoom.connection) return; + + const handleGameStart = () => { + console.log('Game has started!'); + setGameStarted(true); + }; + + gameRoom.connection.once('gameStarted', handleGameStart); + }, [gameRoom.connection]); + + // ...rest of component... +} +``` + +### Removing Event Listeners + +Use the callback returned from `.on()` to remove event listeners: + +```tsx React @nocheck +import { useState, useEffect } from "react"; +import { useActor } from "./rivetkit"; + +function ConditionalListener() { + const [isListening, setIsListening] = useState(false); + const [messages, setMessages] = useState([]); + + const chatRoom = useActor({ + name: "chatRoom", + key: ["general"] + }); + + useEffect(() => { + if (!chatRoom.connection || !isListening) return; + + // Add listener + const unsubscribe = chatRoom.connection.on('messageReceived', (message) => { + setMessages(prev => [...prev, message.text]); + }); + + // Cleanup - remove listener when component unmounts or listening stops + return () => { + unsubscribe(); + }; + }, [chatRoom.connection, isListening]); + + // ...rest of component... +} +``` + +## Debugging + +- `GET /inspector/connections` shows active connections and connection metadata. +- Use this to confirm clients are connected before expecting broadcasts. +- `GET /inspector/summary` provides connections, RPCs, and queue size in one response. +- In non-dev mode, inspector endpoints require authorization. + +## More About Connections + +For more details on actor connections, including connection lifecycle, authentication, and advanced connection patterns, see the [Connections documentation](/docs/actors/connections). + +## API Reference + +- [`RivetEvent`](/typedoc/interfaces/rivetkit.mod.RivetEvent.html) - Base event interface +- [`RivetMessageEvent`](/typedoc/interfaces/rivetkit.mod.RivetMessageEvent.html) - Message event type +- [`RivetCloseEvent`](/typedoc/interfaces/rivetkit.mod.RivetCloseEvent.html) - Close event type +- [`UniversalEvent`](/typedoc/interfaces/rivetkit.mod.UniversalEvent.html) - Universal event type +- [`UniversalMessageEvent`](/typedoc/interfaces/rivetkit.mod.UniversalMessageEvent.html) - Universal message event +- [`UniversalErrorEvent`](/typedoc/interfaces/rivetkit.mod.UniversalErrorEvent.html) - Universal error event +- [`EventUnsubscribe`](/typedoc/types/rivetkit.client_mod.EventUnsubscribe.html) - Unsubscribe function type + +_Source doc path: /docs/actors/events_ diff --git a/.agents/skills/ai-agent/reference/actors/fetch-and-websocket-handler.md b/.agents/skills/ai-agent/reference/actors/fetch-and-websocket-handler.md new file mode 100644 index 0000000..b8b0509 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/fetch-and-websocket-handler.md @@ -0,0 +1,10 @@ +# Fetch and WebSocket Handler + +> Source: `src/content/docs/actors/fetch-and-websocket-handler.mdx` +> Canonical URL: https://rivet.dev/docs/actors/fetch-and-websocket-handler +> Description: These docs have moved to [Low-Level WebSocket Handler](/docs/actors/websocket-handler) and [Low-Level Request Handler](/docs/actors/request-handler). + +--- + + +_Source doc path: /docs/actors/fetch-and-websocket-handler_ diff --git a/.agents/skills/ai-agent/reference/actors/helper-types.md b/.agents/skills/ai-agent/reference/actors/helper-types.md new file mode 100644 index 0000000..55555c7 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/helper-types.md @@ -0,0 +1,10 @@ +# Helper Types + +> Source: `src/content/docs/actors/helper-types.mdx` +> Canonical URL: https://rivet.dev/docs/actors/helper-types +> Description: This page has moved to [Types](/docs/actors/types). + +--- + + +_Source doc path: /docs/actors/helper-types_ diff --git a/.agents/skills/ai-agent/reference/actors/http-api.md b/.agents/skills/ai-agent/reference/actors/http-api.md new file mode 100644 index 0000000..1d8d5be --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/http-api.md @@ -0,0 +1,10 @@ +# Vanilla HTTP API + +> Source: `src/content/docs/actors/http-api.mdx` +> Canonical URL: https://rivet.dev/docs/actors/http-api +> Description: Use the low-level HTTP handler to send and receive requests from actors. + +--- +TODO + +_Source doc path: /docs/actors/http-api_ diff --git a/.agents/skills/ai-agent/reference/actors/input.md b/.agents/skills/ai-agent/reference/actors/input.md new file mode 100644 index 0000000..c5c5dde --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/input.md @@ -0,0 +1,51 @@ +# Input Parameters + +> Source: `src/content/docs/actors/input.mdx` +> Canonical URL: https://rivet.dev/docs/actors/input +> Description: Pass initialization data to actors when creating instances + +--- +Actors can receive input parameters when created, allowing for flexible initialization and configuration. Input is passed during actor creation and is available in lifecycle hooks. + +## Passing Input to Actors + +Input is provided when creating actor instances using the `input` property: + +## Accessing Input in Lifecycle Hooks + +Input is available as the second argument to the `createState` and `onCreate` lifecycle hooks: + +## Input Validation + +You can validate input parameters in the `createState` or `onCreate` hooks: + +## Input vs Connection Parameters + +Input parameters are different from connection parameters: + +- **Input**: + - Passed when creating the actor instance + - Use for actor-wide configuration + - Available in lifecycle hooks +- **Connection parameters**: + - Passed when connecting to an existing actor + - Used for connection-specific configuration + - Available in connection hooks + +## Input Best Practices + +### Use Type Safety + +Define input types to ensure type safety: + +### Store Input in State + +Input is only available in `createState` and `onCreate` lifecycle hooks. If you need to access input data later (in actions, timers, or other hooks), store it in the actor's state during creation. This is the recommended pattern because input shapes can evolve over time, and persisting input in state ensures you always have access to the values the actor was created with: + +## API Reference + +- [`CreateOptions`](/typedoc/interfaces/rivetkit.client_mod.CreateOptions.html) - Options for creating actors +- [`CreateRequest`](/typedoc/types/rivetkit.client_mod.CreateRequest.html) - Request type for creation +- [`ActorDefinition`](/typedoc/classes/rivetkit.mod.ActorDefinition.html) - Actor definition returned by `actor()` + +_Source doc path: /docs/actors/input_ diff --git a/.agents/skills/ai-agent/reference/actors/inspector-tabs.md b/.agents/skills/ai-agent/reference/actors/inspector-tabs.md new file mode 100644 index 0000000..34de206 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/inspector-tabs.md @@ -0,0 +1,251 @@ +# Custom Inspector Tabs + +> Source: `src/content/docs/actors/inspector-tabs.mdx` +> Canonical URL: https://rivet.dev/docs/actors/inspector-tabs +> Description: Ship your own UI tabs alongside a Rivet Actor — embedded directly in the dashboard inspector. + +--- +Custom inspector tabs let you embed your own UI directly in the Rivet +dashboard, next to the built-in tabs. Declare a tab on your actor, point +it at a folder of static files, and the dashboard picks it up +automatically. + +Common uses: + +- Domain-specific debugging panels (queue depth, connection maps, log + filters). +- Operational tools (admin buttons, drain controls, snapshot uploaders). +- Any author-defined view that ships with your actor. + +A runnable example lives at +[`examples/inspector-tabs`](https://github.com/rivet-dev/rivet/tree/main/examples/inspector-tabs). + +## Quickstart + +Declare a tab on your actor: + +Drop an `index.html` in the `source` directory: + +```html + + + + + + + +

Counter: …

+ + + +``` + +Open the dashboard and the "Counter" tab appears alongside the built-ins. + +## Configuration + +Each entry in `inspector.tabs[]` is either a **custom tab** or a +**hide modifier** for a built-in. + +### Custom tab + +```ts @nocheck +{ + id: string, // URL-safe id: /^[A-Za-z0-9_-]+$/ + label: string, // Shown in the tab strip + source: string, // Directory of static assets + icon?: string, // Optional icon id +} +``` + +- **`id`** — used as the URL segment and tab-strip key. Cannot collide + with a built-in id (`workflow`, `database`, `state`, `queue`, + `connections`, `console`). +- **`source`** — directory of static files. The bytes you put there are + the bytes the browser sees. Point it at a Vite/webpack `dist/` and + any framework works (React, Vue, Svelte, vanilla — all fine). +- **`icon`** — one of `workflow`, `database`, `state`, `queue`, `plug`, + `terminal`, `tag`, `logs`. Anything else falls back to a neutral icon. + +### Hide a built-in tab + +```ts @nocheck +{ + id: "workflow" | "database" | "state" | "queue" | "connections" | "console", + hidden: true, +} +``` + +Use this to clean up the strip when the actor doesn't use a given +subsystem — e.g. a counter actor with no queues: + +```ts +inspector: { tabs: [{ id: "queue", hidden: true }] } +``` + +Misconfigurations (missing directory, duplicate id, invalid characters, +empty label) throw at registry construction, so problems show up +immediately. + +## Talking to the dashboard + +The tab loads in an iframe and communicates with the dashboard via +`postMessage`. The contract is small. + +### From the dashboard + +The dashboard sends an `init` message on load and again whenever the +inspector token rotates. Always overwrite the cached token when it +arrives. + +```ts @nocheck +{ + type: "init", + v: 1, + actorId: string, + authToken: string, // Per-actor inspector bearer token + theme?: "light" | "dark", + activeTab?: string, // For multi-view tabs +} +``` + +Multi-view tabs can read the optional `activeTab` field on `init` to +seed their initial sub-view. The dashboard does not send a separate +message when the user switches custom tabs — it navigates the iframe +`src` instead, so the tab reloads and receives a fresh `init`. + +### From the tab + +Send `ready` once your message listener is registered: + +```ts @nocheck +{ type: "ready", v: 1 } +``` + +If a fetch returns 401, the token has rotated. Ask the dashboard for a +fresh one and wait for the next `init` — don't retry with the stale +token: + +```ts @nocheck +{ type: "token-refresh-needed", v: 1 } +``` + +### Security check + +Always reject messages whose `event.origin` doesn't match the +`?shellOrigin=` URL parameter. Without this check, any page that frames +your tab could forge an `init` and feed you a fake token. + +### TypeScript types + +If you build the tab with TypeScript, the message and response types +are exported as types-only: + +## Reading state and calling actions + +The tab can hit any inspector endpoint with the supplied bearer token. +Use relative paths so the tab doesn't need to know the engine origin or +actor id: + +```js +fetch("../../state", { headers: { Authorization: `Bearer ${token}` } }); +fetch("../../action/increment", { method: "POST", headers: { ... }, body: ... }); +fetch("../../rpcs", { headers: { Authorization: `Bearer ${token}` } }); +fetch("../../connections", { headers: { Authorization: `Bearer ${token}` } }); +fetch("../../queue", { headers: { Authorization: `Bearer ${token}` } }); +``` + +The action body shape is `{ args: [...] }` — the array is passed as +positional arguments to the action. + +Full endpoint reference: +[Debugging → Inspector Endpoints](/docs/actors/debugging#inspector-endpoints). + +For high-frequency UIs, prefer the inspector WebSocket +(`/inspector/connect`) over polling. + +## Styling + +A shared stylesheet matching the dashboard's design tokens is served at +`../../tab.css`: + +```html + +``` + +It defines `--rivet-*` tokens for colors, spacing, radius, and +typography, plus sensible defaults so a bare tab looks at home without +custom CSS: + +```css +.my-card { + background: var(--rivet-card); + color: var(--rivet-foreground); + border: 1px solid var(--rivet-border); + border-radius: var(--rivet-radius-md); + padding: var(--rivet-space-4); +} +``` + +Toggle dark mode by adding the `dark` class to `` — the dashboard +sends the active theme in the `init` message. + +Color tokens come in both pre-wrapped (`--rivet-card`) and raw HSL +(`--rivet-card-raw`) forms, so you can compose with alpha: + +```css +.overlay { background: hsl(var(--rivet-background-raw) / 0.6); } +``` + +You're free to skip the stylesheet entirely and bring your own. + +## Security + +The tab runs in an iframe at the engine origin and can call any +inspector endpoint with the supplied token. Treat the bundle like any +author code that ships with your actor: + +- **Don't inline secrets.** The bundle is fetchable by anyone who can + reach the actor. +- **Always validate `event.origin`.** Reject inbound messages from + anywhere other than the dashboard origin. +- **Never retry silently on 401.** Post `token-refresh-needed` and wait + for a fresh `init`. + +## See also + +- [Debugging](/docs/actors/debugging) — full inspector HTTP API +- [Actions](/docs/actors/actions) — actions your tab can invoke +- [State](/docs/actors/state) — state your tab can read +- [`examples/inspector-tabs`](https://github.com/rivet-dev/rivet/tree/main/examples/inspector-tabs) — runnable example + +_Source doc path: /docs/actors/inspector-tabs_ diff --git a/.agents/skills/ai-agent/reference/actors/keys.md b/.agents/skills/ai-agent/reference/actors/keys.md new file mode 100644 index 0000000..b8f1614 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/keys.md @@ -0,0 +1,51 @@ +# Actor Keys + +> Source: `src/content/docs/actors/keys.mdx` +> Canonical URL: https://rivet.dev/docs/actors/keys +> Description: Actor keys uniquely identify actor instances within each actor type. Keys are used for addressing which specific actor to communicate with. + +--- +## Key Format + +Actor keys can be either a string or an array of strings: + +### Compound Keys & User Data + +Array keys are useful when you need compound keys with user-provided data. Using arrays makes adding user data safe by preventing key injection attacks: + +This allows you to create hierarchical addressing schemes and organize actors by multiple dimensions. + +Don't build keys using string interpolation like `"foo:${userId}:bar"` when `userId` contains user data. If a user provides a value containing the delimiter (`:` in this example), it can break your key structure and cause key injection attacks. + +### Omitting Keys + +You can create actors without specifying a key in situations where there is a singleton actor (i.e. only one actor of a given type). For example: + +This pattern should be avoided, since a singleton actor usually means you have a single actor serving all traffic & your application will not scale. See [scaling documentation](/docs/actors/scaling) for more information. + +### Key Uniqueness + +Keys are unique within each actor name. Different actor types can use the same key: + +## Accessing Keys in Metadata + +Access the actor's key within the actor using the [metadata](/docs/actors/metadata) API: + +## Configuration Examples + +### Simple Configuration with Keys + +Use keys to provide basic actor configuration: + +### Complex Configuration with Input + +For more complex configuration, use [input parameters](/docs/actors/input): + +## API Reference + +- [`ActorKey`](/typedoc/types/rivetkit.mod.ActorKey.html) - Key type for actors +- [`ActorQuery`](/typedoc/types/rivetkit.mod.ActorQuery.html) - Query type using keys +- [`GetOptions`](/typedoc/interfaces/rivetkit.client_mod.GetOptions.html) - Options for getting by key +- [`QueryOptions`](/typedoc/interfaces/rivetkit.client_mod.QueryOptions.html) - Options for querying + +_Source doc path: /docs/actors/keys_ diff --git a/.agents/skills/ai-agent/reference/actors/kv.md b/.agents/skills/ai-agent/reference/actors/kv.md new file mode 100644 index 0000000..384769b --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/kv.md @@ -0,0 +1,44 @@ +# Low-Level KV Storage + +> Source: `src/content/docs/actors/kv.mdx` +> Canonical URL: https://rivet.dev/docs/actors/kv +> Description: Use the built-in key-value store on ActorContext for durable string and binary data alongside actor state. + +--- +KV is deprecated. It is a low-level escape hatch kept for backward compatibility. For new actors, prefer [in-memory state](/docs/actors/state) for small serializable values or [SQLite](/docs/actors/sqlite) for larger or queryable data. + +Every Rivet Actor includes a lightweight key-value store on `c.kv`. It is useful for dynamic keys, blobs, or data that does not fit well in structured state. + +If your data has a known schema, prefer [state](/docs/actors/state). KV is best for flexible or user-defined keys. + +## Basic Usage + +Keys and values default to `text`, so you can use strings without extra options. + +## Value Types + +You can store binary values by passing `Uint8Array` or `ArrayBuffer`. Use `type` on both reads and writes to get the right value type: `binary` for `Uint8Array` and `arrayBuffer` for `ArrayBuffer`. + +TypeScript returns a concrete type based on the option you pass in: + +## Key Types + +Keys accept either `string` or `Uint8Array`. String keys are encoded as UTF-8 by default. + +When listing by prefix, you can control how keys are decoded with `keyType`. Returned keys have the prefix removed. + +If you use binary keys, set `keyType: "binary"` so the returned keys stay as `Uint8Array`. + +## Range Operations + +Use `listRange(start, end)` to read an arbitrary half-open range `[start, end)`. Use `deleteRange(start, end)` to clear that same range efficiently. + +## Batch Operations + +KV supports batch operations for efficiency. `batchPut` and `batchGet` work on raw `Uint8Array` keys and values, so encode strings before passing them in. + +## API Reference + +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - `c.kv` is available on the context + +_Source doc path: /docs/actors/kv_ diff --git a/.agents/skills/ai-agent/reference/actors/lifecycle.md b/.agents/skills/ai-agent/reference/actors/lifecycle.md new file mode 100644 index 0000000..89955bb --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/lifecycle.md @@ -0,0 +1,388 @@ +# Lifecycle + +> Source: `src/content/docs/actors/lifecycle.mdx` +> Canonical URL: https://rivet.dev/docs/actors/lifecycle +> Description: Learn about actor lifecycle hooks for initialization, state management, and cleanup. + +--- +# Lifecycle + +Actors follow a well-defined lifecycle with hooks at each stage. Understanding these hooks is essential for proper initialization, state management, and cleanup. + +## Lifecycle + +Actors transition through several states during their lifetime. Each transition triggers specific hooks that let you initialize resources, manage connections, and clean up state. + +``` +Loading ──Start──▶ Ready ──spawn driver──▶ Started + │ + ┌────────────────────────────────────────┤ + │ │ + │ idle timer + can_sleep │ Destroy command + ▼ ▼ + SleepGrace ─── grace window closes ──▶ Destroying + │ │ + ▼ │ + SleepFinalize ──── stop sequence ───────────┤ + ▼ + Terminated +``` + +**On Create** (runs once per actor) + +1. `onMigrate` +2. `createState` +3. `onCreate` +4. `createVars` +5. `onWake` +6. `run` (background, does not block) + +**On Destroy** + +1. `onDestroy` + +**On Wake** (after sleep, restart, or crash) + +1. `onMigrate` +2. `createVars` +3. `onWake` +4. `run` (background, does not block) + +**On Sleep** (after idle period) + +1. Wait for `run` to complete (with timeout) +2. `onSleep` + +**On Connect** (per client) + +1. `onBeforeConnect` +2. `createConnState` +3. `onConnect` + +**On Disconnect** (per client) + +1. `onDisconnect` + +**On Inbound Action Invoke** (per action call) + +1. Action handler executes + +**On Inbound Queue Publish** (per `handle.send(...)`) + +1. `queues..canPublish` (if defined) +2. Queue message is enqueued + +**On Event Subscription Request** (per subscribe request) + +1. `events..canSubscribe` (if defined) +2. Subscription is applied + +## Lifecycle Hooks + +Actor lifecycle hooks are defined as functions in the actor configuration. + +### `state` + +The `state` constant defines the initial state of the actor. See [state documentation](/docs/actors/state) for more information. + +### `onMigrate` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onMigrate` hook runs on every actor start, before `createState`, `onCreate`, `createVars`, and `onWake`. Can be async. It runs early so that database migrations are applied before any other lifecycle hook accesses the database. The second parameter is `true` when the actor is being created for the first time. + +### `createState` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `createState` function dynamically initializes state based on input. Called only once when the actor is first created. Can be async. See [state documentation](/docs/actors/state) for more information. + +### `vars` + +The `vars` constant defines ephemeral variables for the actor. These variables are not persisted and are useful for storing runtime-only data. The value for `vars` must be clonable via `structuredClone`. See [ephemeral variables documentation](/docs/actors/state#ephemeral-variables) for more information. + +### `createVars` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `createVars` function dynamically initializes ephemeral variables. Can be async. Use this when you need to initialize values at runtime. See [ephemeral variables documentation](/docs/actors/state#ephemeral-variables) for more information. + +### `onCreate` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onCreate` hook is called when the actor is first created. Can be async. Use this hook for initialization logic that doesn't affect the initial state. + +### `onDestroy` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onDestroy` hook is called when the actor is being permanently destroyed. Can be async. Use this for final cleanup operations like closing external connections, releasing resources, or performing any last-minute state persistence. + +The actor is still fully functional when `onDestroy` runs. You can access the database, broadcast events, call `waitUntil`, send queue messages, and use `schedule.after`. State mutations made during `onDestroy` are persisted before the actor is torn down. + +### `onWake` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +This hook is called any time the actor is started (e.g. after restarting, upgrading code, or crashing). Can be async. + +This is called after the actor has been initialized but before any connections are accepted. + +Use this hook to set up any resources or start any background tasks, such as `setInterval`. + +### `onSleep` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +This hook is called when the actor is going to sleep. Can be async. Use this to clean up resources, close connections, or perform any shutdown operations. + +The actor is still fully functional when `onSleep` runs. You can access the database, broadcast events, call `waitUntil`, send queue messages, and use `schedule.after`. State mutations made during `onSleep` are persisted before the actor finishes sleeping. + +This hook may not always be called in situations like crashes or forced terminations. Don't rely on it for critical cleanup operations. + +Not supported on Cloudflare Workers. + +### `run` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `run` hook is called after the actor starts and runs in the background without blocking actor startup. This is ideal for long-running background tasks like: + +- Reading from message queues in a loop +- Tick loops for periodic work +- Custom workflow logic +- Background processing + +The handler exposes `c.aborted` for loop checks and `c.abortSignal` for canceling operations when the actor is stopping. You should always check or listen for shutdown to exit gracefully. + +**Important behavior:** +- The actor may go to sleep at any time during the `run` handler. Wrap work that must keep the actor awake with `c.keepAwake(promise)` to block idle sleep until the promise settles. +- If the `run` handler exits (returns), the actor follows its normal idle sleep timeout once it becomes idle +- If the `run` handler throws an error, the actor logs the error and then follows its normal idle sleep timeout once it becomes idle +- On shutdown, `c.abortSignal` fires so the `run` handler can exit within the graceful shutdown window. + +Finite `run` handlers leave the actor alive after they finish. If you want a one shot task to clean itself up when it is done, call `c.destroy()` before returning. + +### `onStateChange` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Called whenever the actor's state changes. Cannot be async. This is often used to broadcast state updates. + +Do not mutate `c.state` inside `onStateChange`; re-entrant state mutation is rejected. + +### `createConnState` and `connState` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +There are two ways to define the initial state for connections: +1. `connState`: Define a constant object that will be used as the initial state for all connections +2. `createConnState`: A function that dynamically creates initial connection state based on connection parameters. Can be async. + +### `onBeforeConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.BeforeConnectContext.html) + +The `onBeforeConnect` hook is called whenever a new client connects to the actor. Can be async. Clients can pass parameters when connecting, accessible via `params`. This hook is used for connection validation and can throw errors to reject connections. + +The `onBeforeConnect` hook does NOT return connection state - it's used solely for validation. + +Connections cannot interact with the actor until this method completes successfully. Throwing an error will abort the connection. This can be used for authentication - see [Authentication](/docs/actors/authentication) for details. + +### `onConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ConnectContext.html) + +Executed after the client has successfully connected. Can be async. Receives the connection object as a second parameter. + +Messages will not be processed for this actor until this hook succeeds. Errors thrown from this hook will cause the client to disconnect. + +### `canPublish` and `canSubscribe` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Use schema-level hooks to authorize queue publishes and event subscriptions. Both hooks can be async and must return booleans: + +- `queues..canPublish` runs before inbound queue publishes. +- `events..canSubscribe` runs before inbound event subscription requests. + +For actions, enforce authorization directly inside each action handler. + +Use deny-by-default rules for each hook and return `false` unless explicitly allowed. See [Access Control](/docs/actors/access-control) for full guidance. + +### `onDisconnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Called when a client disconnects from the actor. Can be async. Receives the connection object as a second parameter. Use this to clean up any connection-specific resources. + +### `onRequest` + +[API Reference](/typedoc/interfaces/rivetkit.mod.RequestContext.html) + +The `onRequest` hook handles HTTP requests sent to your actor at `/actors/{actorName}/http/*` endpoints. Can be async. It receives the request context and a standard `Request` object, and should return a `Response` object. + +See [Request Handler](/docs/actors/request-handler) for more details. + +### `onWebSocket` + +[API Reference](/typedoc/interfaces/rivetkit.mod.WebSocketContext.html) + +The `onWebSocket` hook handles WebSocket connections to your actor. Can be async. It receives the actor context and a `WebSocket` object. Use this to set up WebSocket event listeners and handle real-time communication. + +See [WebSocket Handler](/docs/actors/websocket-handler) for more details. + +### `onBeforeActionResponse` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onBeforeActionResponse` hook is called before sending an action response to the client. Can be async. Use this hook to modify or transform the output of an action before it's sent to the client. This is useful for formatting responses, adding metadata, or applying transformations to the output. + +## Sleeping + +Actors automatically sleep after a period of inactivity to free up resources. When a request arrives for a sleeping actor, it wakes up, restores its state, and handles the request. + +### When Actors Sleep + +#### Idle Timeout + +An actor is considered idle and eligible to sleep when **all** of the following are true: + +- No active HTTP requests +- No active connections (unless they are hibernatable WebSockets) +- No active `run` handler (unless it is waiting on a queue) +- No outstanding `c.keepAwake(promise)` promises +- No pending disconnect callbacks +- No async `onWebSocket` event handlers (eg `open`, `message`, `close`) still running + +Once the actor becomes idle, the sleep timer starts. After `sleepTimeout` (default 30 seconds) of continuous inactivity, the actor begins the sleep process. Any activity resets the timer. + +Outbound requests (e.g. `fetch` calls) do not count as activity and will not keep the actor awake. Wrap them with `c.waitUntil()` if they must complete before the actor sleeps. + +#### Upgrades & Eviction + +The platform may force an actor to migrate to a new machine during version upgrades or when a serverless request is about to timeout. The same [shutdown sequence](#shutdown-sequence) runs, then the actor is rescheduled on a new machine and wakes up with its persisted state. + +Use `onSleep`, `waitUntil`, or `keepAwake` to control the length of the grace period before the actor moves to another machine. + +### Manual Lifecycle Controls + +You can also trigger lifecycle transitions from the Rivet Cloud API. These endpoints are useful for operational workflows, debugging, and forcing an actor to move through the same sleep or reschedule path that the platform would normally trigger. + +```bash +curl -X POST \ + "https://cloud-api.rivet.dev/actors/$ACTOR_ID/sleep?namespace=$NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{}' +``` + +```bash +curl -X POST \ + "https://cloud-api.rivet.dev/actors/$ACTOR_ID/reschedule?namespace=$NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{}' +``` + +`/sleep` asks the actor to enter the normal sleep shutdown sequence. `/reschedule` asks the platform to allocate the actor again, which is useful after crashes or when you need to force a fresh placement. Both endpoints require the actor ID and namespace. + +### Skip Ready Wait + +The gateway normally holds requests until the actor is ready. The actor is not ready during startup (before `onWake` finishes) or during the sleep grace period (while `onSleep` and `waitUntil` are running). Probes and readiness checks can opt out with `skipReadyWait` to reach the actor's `onRequest` or `onWebSocket` handler in either window. + +See [Skip Ready Wait](/docs/clients/javascript#skip-ready-wait) on the JavaScript client page for usage. + +### Keeping the Actor Awake + +RivetKit gives you two primitives for holding the actor awake across background work. Both take a `Promise` and differ in how they interact with idle sleep and the grace period. + +| Method | Accepts | Blocks idle sleep | Blocks grace finalize | Use case | +| --- | --- | --- | --- | --- | +| `c.keepAwake(promise)` | `Promise` (returns same promise) | Yes | Yes | Critical work that must keep the actor running end to end (for example a turn in a game, an ongoing tool call). | +| `c.waitUntil(promise)` | `Promise` (returns void) | No | Yes | Best-effort finalization work that may complete during the grace window (for example analytics flushes, cleanup writes). | + +`c.keepAwake(promise)` is the preferred primitive for long-running work the actor should not sleep through. It holds a keep-awake counter until the promise settles, which blocks both idle sleep and the grace finalize step. The promise is returned unchanged, so you can `await` it if you need the value. + +`setPreventSleep(enabled)` is deprecated and now a no-op. Wrap the work you want to keep alive with `c.keepAwake(promise)` instead. + +### On Sleep Hook + +The [`onSleep`](#onsleep) hook runs during shutdown for cleanup like clearing intervals or closing connections. It is best-effort and will not run if the actor crashes. + +### Wait Before Sleep + +`c.waitUntil(promise)` registers a background promise that must resolve before the actor finishes sleeping. Use this to flush data or finish in-flight work during shutdown without blocking the main execution flow. + +The actor waits up to `sleepGracePeriod` for graceful sleep work during the [shutdown sequence](#shutdown-sequence). That single budget covers `onSleep`, `waitUntil`, `keepAwake`, async raw WebSocket handlers such as `message` and `close`. By default, this graceful sleep window is 15 seconds total. If the timeout is exceeded, the actor proceeds with sleep anyway. + +### Sleep Timeouts + +| Option | Default | Description | +|--------|---------|-------------| +| `sleepTimeout` | 30 seconds | Time of inactivity before the actor begins sleeping. | +| `sleepGracePeriod` | 15 seconds | Total graceful shutdown window for hooks, `waitUntil`, `keepAwake`, async raw WebSocket handlers, and disconnects. | + +Rivet enforces a hard limit of **30 minutes** for the entire stop process. These can be configured in the [options](#options). + +### WebSocket Hibernation + +WebSocket connections are preserved across sleep cycles by default and transparently migrated to the new actor instance. Client stays connected and sees no interruption. Actor migration is very fast, realtime workloads are not interrupted. + +### Shutdown Sequence + +When an actor sleeps or is destroyed, it enters the graceful shutdown window: + +1. `c.abortSignal` fires and `c.aborted` becomes `true`. New connections and dispatch are rejected. Alarm timeouts are cancelled. On sleep, scheduled events are persisted and will be re-armed when the actor wakes. +2. `onSleep` or `onDestroy` and `onDisconnect` for each closing connection run during the same window. User `waitUntil` promises and async raw WebSocket handlers are drained. Hibernatable WebSocket connections are preserved on sleep and closed on destroy. +3. Once graceful work has completed, state is saved and final cleanup runs. + +The entire window is bounded by `sleepGracePeriod` on both sleep and destroy. Defaults to 15 seconds. If the window is exceeded, the actor proceeds to state save anyway. + +#### Graceful shutdown window + +During steps 1 through 6, the actor is still fully functional. Database access, `broadcast`, `waitUntil`, `queue.send`, and `schedule.after` all work. State mutations are persisted at step 7. Actions invoked by pre-existing connections or lifecycle hooks continue to execute normally. + +New connections and raw WebSocket upgrades are rejected as soon as the shutdown sequence begins. New requests that arrive during shutdown are held until the actor wakes up again. The caller does not need to retry. + +If `schedule.after` is called during shutdown, the event is persisted so it survives the sleep/wake cycle, but no local timeout is scheduled. The event will fire after the actor wakes. + +In-flight actions are **not** waited on during shutdown. If an action must complete before the actor stops, wrap the critical work with `c.waitUntil()`. + +## Options + +The `options` object allows you to configure various timeouts and behaviors for your actor. + +| Option | Default | Description | +|--------|---------|-------------| +| `createVarsTimeout` | 5000ms | Timeout for `createVars` function | +| `createConnStateTimeout` | 5000ms | Timeout for `createConnState` function | +| `onConnectTimeout` | 5000ms | Timeout for `onConnect` hook | +| `sleepGracePeriod` | 15000ms | Total graceful shutdown window for both sleep and destroy | +| `stateSaveInterval` | 1000ms | Interval for persisting state | +| `actionTimeout` | 60000ms | Timeout for action execution | +| `connectionLivenessTimeout` | 2500ms | Timeout for connection liveness check | +| `connectionLivenessInterval` | 5000ms | Interval for connection liveness check | +| `sleepTimeout` | 30000ms | Time before actor sleeps due to inactivity | +| `canHibernateWebSocket` | false | Whether WebSockets can hibernate (experimental) | + +## Advanced + +### Actor Shutdown Abort Signal + +The `c.abortSignal` provides an `AbortSignal` that fires when the actor is stopping, and `c.aborted` is the shorthand boolean for loop checks. Use these to cancel ongoing operations when the actor sleeps or is destroyed. + +The abort signal fires at the very start of the [shutdown sequence](#shutdown-sequence), before `onSleep` or `onDestroy` runs. This means `c.aborted` is already `true` inside those lifecycle hooks. The signal fires early so that the `run` handler can exit promptly, but the actor remains fully functional throughout the graceful shutdown window. + +See [Canceling Long-Running Actions](/docs/actors/actions#canceling-long-running-actions) for manually canceling operations on-demand. + +### Using `ActorContext` Type Externally + +When extracting logic from lifecycle hooks or actions into external functions, you'll often need to define the type of the context parameter. Rivet provides helper types that make it easy to extract and pass these context types to external functions. + +See [Types](/docs/actors/types) for more details on using `ActorContextOf`. + +## Full Example + +_Source doc path: /docs/actors/lifecycle_ diff --git a/.agents/skills/ai-agent/reference/actors/limits.md b/.agents/skills/ai-agent/reference/actors/limits.md new file mode 100644 index 0000000..57d7194 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/limits.md @@ -0,0 +1,169 @@ +# Limits + +> Source: `src/content/docs/actors/limits.mdx` +> Canonical URL: https://rivet.dev/docs/actors/limits +> Description: Limits and constraints for Rivet Actors. + +--- +This page documents the limits for Rivet Actors. + +There are two types of limits: + +- **Soft Limit**: Application-level limit, configurable in RivetKit. These cannot exceed the hard limit. +- **Hard Limit**: Infrastructure-level limit that cannot be configured. + +Soft limits are configured in two places. Registry-level WebSocket message-size limits are passed to `setup`: + +Per-actor limits such as queue sizes and lifecycle timeouts are passed to `actor(...)` via `options`: + +## Limits + +### WebSocket + +These limits affect actions that use `.connect()` and [low-level WebSockets](/docs/actors/websocket-handler). + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max incoming message size | 64 KiB | 32 MiB | Maximum size of incoming WebSocket messages. Soft limit configurable via `maxIncomingMessageSize`; hard limit configurable in self-hosted engine config via `guard.websocket_max_message_size`. | +| Max outgoing message size | 1 MiB | 32 MiB | Maximum size of outgoing WebSocket messages. Soft limit configurable via `maxOutgoingMessageSize`; hard limit configurable in self-hosted engine config via `guard.websocket_max_message_size`. | +| Max WebSocket frame size | — | 32 MiB | Maximum size of a single WebSocket frame accepted by Rivet's transport edge. Configurable in self-hosted engine config via `guard.websocket_max_frame_size`. This is not configurable by browser clients and is not negotiated during the WebSocket handshake. | +| WebSocket open timeout | — | 15 seconds | Time allowed for WebSocket connection to be established, including `onBeforeConnect` and `createConnState` hooks. Connection is closed if exceeded. | +| Message ack timeout | — | 30 seconds | Time allowed for message acknowledgment before connection is closed. Only relevant in the case of a network issue and does not affect your application. | + +### Hibernating WebSocket + +Hibernating WebSockets allow actors to sleep while keeping client connections alive. All WebSocket limits above also apply to hibernating WebSockets. See [WebSocket Hibernation](/docs/actors/websocket-handler#web-socket-hibernation) for details. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max pending buffer size | — | 128 MiB | Total size of all buffered messages per connection while actor is sleeping. | +| Max pending message count | — | 65,535 | Maximum number of buffered messages per connection while actor is sleeping. | +| Hibernation timeout | — | 90 seconds | Maximum time an actor has to wake up before the client is disconnected. Only relevant if something is wrong with starting actors. | + +### HTTP + +These limits affect actions that do not use `.connect()` and [low-level HTTP requests](/docs/actors/request-handler). + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max request body size | — | 20 MiB | Maximum size of HTTP request bodies. | +| Max response body size | — | 20 MiB | Maximum size of HTTP response bodies. | +| Request timeout | 60 seconds | — | Maximum time for an `onRequest` handler to complete. Defaults to `actionTimeout`; configure with `actionTimeout`. | + +### Networking + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Connection ping timeout | — | 30 seconds | Connection is closed if a ping is not acknowledged within this time. Applies to both HTTP and WebSocket. Only relevant in the case of a network issue and does not affect your application. | + +### Queue + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max queue size | 1,000 messages | — | Maximum number of messages in the queue before new messages are rejected. Configurable via `maxQueueSize`. | +| Max queue message size | 64 KiB | 128 KiB (effective) | Maximum size of each individual queue message. Configurable via `maxQueueMessageSize`. Actual payload is slightly lower after queue serialization overhead. | + +### Actor KV Storage + +These limits apply to the low-level KV storage interface powering Rivet Actors. They likely do not affect your application, but are documented for completeness. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max key size | — | 2 KiB | Maximum size of a single key. | +| Max value size | — | 128 KiB | Maximum size of a single value. | +| Max keys per operation | — | 128 | Maximum number of keys in a single batch get/put/delete operation. Does not apply to range operations (`listRange`, `deleteRange`). | +| Max batch put payload size | — | 976 KiB | Maximum total size of all key-value pairs in a single batch put operation. | +| Max storage size per actor | — | 10 GiB | Maximum total KV storage size for a single actor. | +| List default limit | — | 16,384 | Default maximum number of keys returned by a list operation. | + +### Actor SQLite Storage + +These limits apply to the [SQLite database](/docs/actors/state#sqlite-database) available via `this.sql`. SQLite data is stored through the KV layer, so the storage limit is shared with KV storage. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max storage size per actor | — | 10 GiB | Maximum total storage size for a single actor. This limit is shared with KV storage. | +| Max dirty data per commit | — | 1,310,720 bytes | Maximum raw SQLite page data that can be written in a single commit. This is 320 dirty pages at 4 KiB per page. | +| Transaction deadline | 60 seconds | — | Safety backstop for `db.transaction()`. Configure per transaction with `{ timeout: milliseconds }`; there is no product-level maximum. | +| Transaction coordinator queue | — | 128 operations | Maximum admitted SQLite operations waiting behind an active coordinated transaction. Additional operations fail with `sqlite.transaction_queue_full`. | + +SQLite commit deltas are compressed and split into internal chunks before storage, but all chunks for one commit are published atomically. The commit limit is therefore based on raw dirty page bytes before compression, not the compressed delta size. + +Avoid `VACUUM` inside actor databases. It rewrites the database in one transaction and can exceed the dirty-page commit limit even when ordinary incremental writes fit. + +### Actor Runtime Socket + +The experimental [Actor Runtime Socket](/docs/actors/actor-runtime-socket) negotiates its active frame limit during the handshake. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Frame payload size | 32 MiB | — | Default maximum request or response payload. Self-hosted native runtimes can configure `RIVET_ACTOR_RUNTIME_SOCKET_MAX_FRAME_BYTES`; oversized responses return `ResponseTooLarge`. | + +### KV Preloading + +When an actor starts, the engine can pre-fetch KV data declared in the actor name metadata and deliver it alongside the start command. This removes round-trips to storage during actor startup. RivetKit emits the preload manifest from its own key layout and exposes per-actor overrides via `options`. Operators can still enforce a global cap in the [engine config](/docs/self-hosting/configuration) with `pegboard.preload_max_total_bytes`. In serverless mode, this data is serialized into the `/api/rivet/start` request body along with actor config and protocol metadata, so the accepted body size must be larger than the preload budget. RivetKit defaults `serverless.maxStartPayloadBytes` to 16 MiB to leave margin for the default 1 MiB preload budget and larger SQLite startup page preloads. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max total preload size | 1 MiB | — | Maximum total size of all preloaded KV data sent with the start command. Configurable via `pegboard.preload_max_total_bytes`. Setting to 0 disables all preloading. | +| Max workflow preload size | 128 KiB | — | Default maximum size of preloaded workflow data for RivetKit actors. Configurable per actor via `options.preloadMaxWorkflowBytes`. Setting to 0 disables workflow preloading for that actor. | +| Max connections preload size | 64 KiB | — | Default maximum size of preloaded connection data for RivetKit actors. Configurable per actor via `options.preloadMaxConnectionsBytes`. Setting to 0 disables connections preloading for that actor. | + +### Actor Input + +See [Actor Input](/docs/actors/input) for details. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max actor input size | — | 4 MiB | Maximum size of the input passed when creating an actor. | +| Max connection params size | — | 4 KiB | Maximum size of connection parameters passed when connecting to an actor. | +| Max actor key component size | — | 128 bytes | Maximum size of each component in an actor key array. | +| Max actor key total size | — | 1,024 bytes | Maximum total size of the serialized actor key string. | +| Max actor name length | — | 64 characters | Maximum length for actor and project identifiers. | + +### Rate Limiting + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Rate limit | — | 1200 requests/minute | Default rate limit per actor per IP address with a 1 minute time bucket. | +| Max in-flight requests | — | 32 | Default maximum concurrent requests to an actor per IP address. | + +### Timeouts + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Action timeout | 60 seconds | — | Timeout for RPC actions. Configurable via `actionTimeout`. | +| On request timeout | 60 seconds | — | Timeout for raw `onRequest` handlers. Defaults to `actionTimeout`; configure with `actionTimeout`. | +| On before connect timeout | 5 seconds | — | Timeout for the `onBeforeConnect` hook. Configurable via `onBeforeConnectTimeout`. | +| Create vars timeout | 5 seconds | — | Timeout for `createVars` hook. Configurable via `createVarsTimeout`. | +| Create conn state timeout | 5 seconds | — | Timeout for `createConnState` hook. Configurable via `createConnStateTimeout`. | +| On connect timeout | 5 seconds | — | Timeout for `onConnect` hook. Configurable via `onConnectTimeout`. | +| On migrate timeout | 30 seconds | — | Timeout for `onMigrate` hook. Configurable via `onMigrateTimeout`. | +| Sleep grace period | 15 seconds | — | Total graceful shutdown budget for both sleep and destroy. Covers `onSleep`/`onDestroy`, run handler shutdown, `waitUntil`, `keepAwake`, async raw WebSocket handlers, and connection cleanup. Configurable via `sleepGracePeriod`. | +| Sleep timeout | 30 seconds | — | Time of inactivity before actor hibernates. Configurable via `sleepTimeout`. | +| State save interval | 1 second | — | Interval between automatic state saves. Configurable via `stateSaveInterval`. | +| Connection liveness timeout | 2.5 seconds | — | Time a stateful connection can miss liveness checks before RivetKit treats it as unhealthy. Configurable via `connectionLivenessTimeout`. | +| Connection liveness interval | 5 seconds | — | Interval between stateful connection liveness checks. Configurable via `connectionLivenessInterval`. | + +### Serverless Shutdown + +These timeouts control how actors are shut down when a serverless request reaches its lifespan limit. See [Shutdown Sequence](/docs/general/runtime-modes#shutdown-sequence) for details. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Request lifespan | 3600 seconds (60 min) | — | Total lifespan of a serverless request before drain begins. Configurable via `requestLifespan` in [`configurePool`](/docs/general/registry-configuration). | +| Runner config drain grace period | — | 30 minutes | Time a serverless runner reserves for actors to stop gracefully. Configurable via `drainGracePeriod` in [`configurePool`](/docs/general/registry-configuration). | +| Engine serverless drain fallback | — | 10 seconds | Engine-level fallback used when no per-runner config applies. Configurable via [engine config](/docs/self-hosting/configuration) (`pegboard.serverless_drain_grace_period`). | + +### Actor Lifecycle + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Actor start threshold | — | 30 seconds | Maximum time for an actor to start before it is considered lost and rescheduled. | +| Actor stop threshold | — | 30 minutes | Maximum time for an actor to stop before it is considered lost. | + +## Increasing Limits + +These limits are sane defaults designed to protect your application from exploits and accidental runaway bugs. If you have a use case that requires different limits, [contact us](https://rivet.dev/contact) to discuss your requirements. + +_Source doc path: /docs/actors/limits_ diff --git a/.agents/skills/ai-agent/reference/actors/metadata.md b/.agents/skills/ai-agent/reference/actors/metadata.md new file mode 100644 index 0000000..d3dcc24 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/metadata.md @@ -0,0 +1,39 @@ +# Metadata + +> Source: `src/content/docs/actors/metadata.mdx` +> Canonical URL: https://rivet.dev/docs/actors/metadata +> Description: Metadata provides information about the currently running actor. + +--- +## Actor ID + +Get the unique instance ID of the actor: + +## Actor Name + +Get the actor type name: + +This is useful when you need to know which actor type is running, especially if you have generic utility functions that are shared between different actor implementations. + +## Actor Key + +Get the actor key used to identify this actor instance: + +The key is used to route requests to the correct actor instance and can include parameters passed when creating the actor. + +Learn more about using keys for actor addressing and configuration in the [keys documentation](/docs/actors/keys). + +## Region + +Region can be accessed from the context object via `c.region`. + +`c.region` is only supported on Rivet at the moment. + +## Example Usage + +## API Reference + +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining metadata +- [`CreateOptions`](/typedoc/interfaces/rivetkit.client_mod.CreateOptions.html) - Options for creating an actor, including `region` and `input` + +_Source doc path: /docs/actors/metadata_ diff --git a/.agents/skills/ai-agent/reference/actors/queues.md b/.agents/skills/ai-agent/reference/actors/queues.md new file mode 100644 index 0000000..8ebeb7b --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/queues.md @@ -0,0 +1,122 @@ +# Queues & Run Loops + +> Source: `src/content/docs/actors/queues.mdx` +> Canonical URL: https://rivet.dev/docs/actors/queues +> Description: Use actor-local durable queues for serial run loops and request/response workflows. + +--- +## What are queues? + +- **Realtime**: messages are delivered to a live actor as soon as possible. +- **Durable**: messages are persisted and survive actor sleep/restart. +- **Request/response**: clients can wait for a queue completion response. +- **Scalable**: queues absorb large bursts and handle heavy backpressure safely. +- **Local per actor**: each actor instance has its own queue storage (scoped by actor key/id). + +Queues are commonly referred to as "mailboxes" in other actor frameworks. + +For a worked queue-driven pattern, see the cookbook: [AI Agent](/cookbook/ai-agent/). + +## What are queues good for? + +- Great for any task that changes actor state. +- Helps avoid race conditions by handling work in order. +- Makes complex behavior easier to organize. + +## Basic queue + +This is the default pattern. Define queue names in `queues`, process them in `run`, and publish from the client with `handle.send(...)`. + +## Completable messages + +Use this when you want explicit completion/ack semantics but do not need to return data. + +- `message.complete()` resolves a sender waiting on `wait: true` (or `enqueueAndWait`). It does not change durability: messages are removed from queue storage when they are received, not when they are completed. +- If processing fails before `message.complete()`, the message is not redelivered, and any waiting sender times out instead of receiving a completion. +- `status: "timedOut"` means sender timeout elapsed before `message.complete(...)`. + +## Request/reply pattern + +Use this when the sender needs data back from queued work. + +## Queue messages from within an actor + +Queueing is useful from inside actor logic too, not just from clients. + +- Use actions as entrypoints, then enqueue into the run loop to keep mutations serialized. +- You can also call `c.queue.send(...)` from other parts of `run` when needed. +- `c.queue.send(...)` confirms durable enqueue. It does not wait for processing to finish. + +## Defining queue schemas + +You can define queue types with `queue()` or with schema objects. Schema objects support [Standard Schema](https://standardschema.dev/) validators, including [Zod](https://zod.dev/). + +## Pull messages with `next` and `nextBatch` + +Use `next` when you want to wait for one queue message. +Use `nextBatch` when you want to wait for multiple queue messages. + +- Waits until messages are available unless timeout is hit. +- Omit `timeout` to wait indefinitely. + +## Poll messages + +Use `tryNext` when you need one non-blocking read. +Use `tryNextBatch` for non-blocking batch reads. + +- Returns immediately and never waits. + +## Abort signals + +Use `signal` when your receive loop needs external cancellation semantics in addition to actor shutdown behavior. + +## Multiple queues + +Multiple queues let you separate message flows by purpose. By default, receive calls race across all queues when `names` is not specified. In this pattern, prompt messages run through a streaming loop while stop messages act as control signals on a separate receive path. + +Use `iter({ names: ["prompt"] })` as the main stream and `next({ names: ["stop"] })` as a stop signal. + +## Sleeping behavior + +If an actor has a `run` handler, it does not sleep while that handler is actively doing work. It only can sleep when the run loop is blocked waiting for queue entries (for example inside `iter(...)` or `next(...)`). + +This means you can run normal code in `run` without worrying about sleep interrupting it mid-call. + +## Debugging + +- `GET /inspector/queue?limit=50` returns queue size and pending message metadata. +- `GET /inspector/summary` includes `queueSize` for quick queue health checks. +- `POST /queue/:name` with `wait: true` is useful to verify completable/request-response behavior. +- In non-dev mode, inspector endpoints require authorization. + +## Recommendations + +- Actions are for getting data, queue entries are for mutating data. +- Implement connection auth in `onBeforeConnect`. See [Authentication](/docs/actors/authentication). +- Route most state changes through one queue loop so ordering stays predictable. +- If you need more complex multi-step run loops, consider using workflows. +- Use `c.aborted` and `c.abortSignal` for actor shutdown. Use your own `AbortController` for earlier loop cancellation. +- Add `timeout` when callers need bounded wait behavior. +- Use `wait: true` only when the caller actually needs a response. + +## Pitfalls + +### Avoid `wait: true` between actors + +`wait: true` blocks the sender's run loop until the receiver finishes. Between actors, this adds unnecessary overhead and risks deadlocks, especially if the target actor needs to communicate back. If an actor sends a `wait: true` message to *itself*, it is a guaranteed deadlock because the run loop is already busy processing the current message. + +Reserve `wait: true` for external callers (HTTP handlers, CLI tools, client apps). For actor-to-actor communication, send a queue message to the other actor without `wait: true`, then have that actor send a queue message back when the work is done. + +## Tips + +### Message TTL + +Every queue message includes a `createdAt` timestamp. Use this to skip or discard stale messages in your run loop: + +### Delayed delivery + +Use [`c.schedule`](/docs/actors/schedule) to enqueue messages at a future time instead of processing them immediately: + +See [Schedule](/docs/actors/schedule) for the full scheduling API. + +_Source doc path: /docs/actors/queues_ diff --git a/.agents/skills/ai-agent/reference/actors/quickstart/backend.md b/.agents/skills/ai-agent/reference/actors/quickstart/backend.md new file mode 100644 index 0000000..86cbdf2 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/quickstart/backend.md @@ -0,0 +1,64 @@ +# Node.js & Bun Quickstart + +> Source: `src/content/docs/actors/quickstart/backend.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/backend +> Description: Get started with Rivet Actors in Node.js and Bun + +--- +Prefer to start from a complete project? See the runnable [`hello-world`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world) example. + +## Steps + +### Add Rivet Skill to Coding Agent (Optional) + +If you're using an AI coding assistant (like Claude Code, Cursor, Windsurf, etc.), add Rivet skills for enhanced development assistance: + +```sh +npx skills add rivet-dev/skills +``` + +### Install Rivet + +```sh +npm install rivetkit +``` + +### Create Actors and Start Server + +Create a file with your actors, set up the registry, and start the server: + +### Run Server + +```sh Node.js +npx tsx --watch index.ts +``` + +```sh Bun +bun --watch index.ts +``` + +```sh Deno +deno run --allow-net --allow-read --allow-env --watch index.ts +``` + +Your server is now running on `http://localhost:6420`. Clients connect directly to the Rivet Engine on this port. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend: + +### TypeScript + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### React + +See the [React documentation](/docs/clients/react) for more information. + +### Deploy + +## Configuration Options + +_Source doc path: /docs/actors/quickstart/backend_ diff --git a/.agents/skills/ai-agent/reference/actors/quickstart/cloudflare.md b/.agents/skills/ai-agent/reference/actors/quickstart/cloudflare.md new file mode 100644 index 0000000..e39cbe4 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/quickstart/cloudflare.md @@ -0,0 +1,165 @@ +# Cloudflare Workers Quickstart + +> Source: `src/content/docs/actors/quickstart/cloudflare.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/cloudflare +> Description: Set up a Rivet project locally targeting Cloudflare Workers. + +--- +Set up a Rivet project locally that runs on Cloudflare Workers. The `@rivetkit/cloudflare-workers` package wires the WebAssembly runtime for you. + +Prefer to start from a complete project? See the runnable [`hello-world-cloudflare-workers`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-cloudflare-workers) example (with [Hono](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-cloudflare-workers-hono) and [raw router](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-cloudflare-workers-raw) variants). + +## Steps + +### Install Packages + +```sh +npm install rivetkit @rivetkit/cloudflare-workers +npm install --save-dev wrangler +``` + +### Configure Wrangler + +```toml wrangler.toml +name = "rivetkit-cloudflare" +main = "src/index.ts" +compatibility_date = "2025-04-01" +compatibility_flags = ["nodejs_compat"] +``` + +The `nodejs_compat` flag is required so the runtime can read its connection config from `process.env`. + +### Create the Worker + +`createHandler` serves the Rivet manager API on `/api/rivet`. Pick how you want to handle your own routes: + +- **Default**: Rivet handles everything. +- **Hono**: Mount a [Hono](https://hono.dev) app for your routes (`npm install hono`). +- **Raw**: Provide a `fetch` and route requests yourself. + +```ts Default @nocheck +import { actor } from "rivetkit"; +import { createHandler } from "@rivetkit/cloudflare-workers"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +export default createHandler({ use: { counter } }); +``` + +```ts Hono @nocheck +import { actor } from "rivetkit"; +import { createClient } from "rivetkit/client"; +import { createHandler, setup } from "@rivetkit/cloudflare-workers"; +import { Hono } from "hono"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +// `setup` returns a typed registry, so the client below is fully typed. +const registry = setup({ use: { counter } }); + +const app = new Hono(); + +app.get("/", (c) => c.text("Hello from Hono + Rivet Actors!")); + +app.post("/increment/:name", async (c) => { + // `createClient` reads RIVET_ENDPOINT from the environment (passed by `rivet + // dev`, or set as a Worker secret in production). + const client = createClient(); + const count = await client.counter.getOrCreate(c.req.param("name")).increment(1); + return c.json({ count }); +}); + +// Rivet keeps `/api/rivet`; Hono handles everything else. +export default createHandler(registry, { fetch: app.fetch }); +``` + +```ts Raw @nocheck +import { actor } from "rivetkit"; +import { createClient } from "rivetkit/client"; +import { createHandler, setup } from "@rivetkit/cloudflare-workers"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +// `setup` returns a typed registry, so the client below is fully typed. +const registry = setup({ use: { counter } }); + +// Rivet keeps `/api/rivet`; your `fetch` handles everything else. +export default createHandler(registry, { + fetch: async (request: Request) => { + const url = new URL(request.url); + + if (url.pathname === "/") { + return new Response("Hello from a raw Rivet Worker router!"); + } + + const increment = url.pathname.match(/^\/increment\/(.+)$/); + if (request.method === "POST" && increment) { + // `createClient` reads RIVET_ENDPOINT from the environment (passed by + // `rivet dev`, or set as a Worker secret in production). + const client = createClient(); + const count = await client.counter.getOrCreate(increment[1]).increment(1); + return Response.json({ count }); + } + + return new Response("Not found", { status: 404 }); + }, +}); +``` + +### Run Locally + +Start Rivet. The CLI runs the local engine and spawns `wrangler dev` for you: + +```sh +npx @rivetkit/cli dev --provider cloudflare +``` + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend. It connects directly to the local engine on `http://localhost:6420`: + +### TypeScript + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### React + +See the [React documentation](/docs/clients/react) for more information. + +### Deploy + +Ready to ship? See [Deploying to Cloudflare Workers](/docs/deploy/cloudflare). + +## Related + +- [Quickstart](/docs/actors/quickstart) +- [Deploying to Cloudflare Workers](/docs/deploy/cloudflare) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/actors/quickstart/cloudflare_ diff --git a/.agents/skills/ai-agent/reference/actors/quickstart/effect.md b/.agents/skills/ai-agent/reference/actors/quickstart/effect.md new file mode 100644 index 0000000..fc252e9 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/quickstart/effect.md @@ -0,0 +1,239 @@ +# Effect.ts Quickstart (Beta) + +> Source: `src/content/docs/actors/quickstart/effect.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/effect +> Description: Build a Rivet Actor with the Effect SDK + +--- +Effect support is in beta. The `@rivetkit/effect` API may change between releases. See the [`hello-world-effect`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-effect) and [`chat-room-effect`](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room-effect) examples for complete runnable projects. + +## Steps + +### Install Rivet + +Add `rivetkit`, the Effect SDK, and its Effect peers: + +```sh +npm install rivetkit @rivetkit/effect effect @effect/platform-node +``` + +### Define Your Actor + +Split each actor into a public contract and a server-only implementation so the contract can be imported from client code without leaking server details. + +The contract declares the actor and its actions. Actions are standalone values with explicit [`effect/Schema`](https://effect.website/docs/schema/introduction/) payloads and successes, validated end to end: + +```ts src/actors/counter/api.ts @nocheck +import { Action, Actor } from "@rivetkit/effect"; +import { Schema } from "effect"; + +export const Increment = Action.make("Increment", { + payload: { amount: Schema.Number }, + success: Schema.Number, +}); + +export const GetCount = Action.make("GetCount", { + success: Schema.Number, +}); + +export const Counter = Actor.make("Counter", { + actions: [Increment, GetCount], +}); +``` + +The implementation registers the actor with `.toLayer`. The wake function runs once when the actor awakes and returns the action handlers. Persisted state is accessed through a `SubscriptionRef`-like `State` API: + +```ts src/actors/counter/live.ts @nocheck +import { Actor, State } from "@rivetkit/effect"; +import { Effect, Schema } from "effect"; +import { Counter } from "./api.ts"; + +export const CounterLive = Counter.toLayer( + Effect.fnUntraced(function* ({ rawRivetkitContext, state }) { + return Counter.of({ + Increment: Effect.fnUntraced(function* ({ payload }) { + const next = yield* State.updateAndGet(state, (current) => ({ + count: current.count + payload.amount, + })).pipe(Effect.orDie); + + // Broadcast the new value to every connected client. + rawRivetkitContext.broadcast("newCount", next.count); + + return next.count; + }), + GetCount: () => + State.get(state).pipe( + Effect.map((current) => current.count), + Effect.orDie, + ), + }); + }), + { + state: { + schema: Schema.Struct({ count: Schema.Number }), + initialValue: () => ({ count: 0 }), + }, + name: "Counter", + icon: "calculator", + }, +); +``` + +### Serve The Registry + +Compose the actor layers and serve them with `Registry.serve`. `Registry.layer()` reads engine config from the environment, and the actor layer is provided a `Client` so actors can call other actors: + +```ts src/main.ts @nocheck +import { NodeRuntime } from "@effect/platform-node"; +import { Client, Registry } from "@rivetkit/effect"; +import { Layer } from "effect"; +import { CounterLive } from "./actors/counter/live.ts"; + +const endpoint = process.env.RIVET_ENDPOINT ?? "http://127.0.0.1:6420"; + +const ActorsLayer = CounterLive.pipe(Layer.provide(Client.layer({ endpoint }))); + +const MainLayer = Registry.serve(ActorsLayer).pipe(Layer.provide(Registry.layer())); + +// Keeps the layer alive. Tears down on SIGINT/SIGTERM. +Layer.launch(MainLayer).pipe(NodeRuntime.runMain); +``` + +### Run The Server + +Set `RIVET_RUN_ENGINE=1` to spawn a local Rivet Engine alongside the server. The engine binary is downloaded and cached the first time you run, so there is nothing else to install: + +```sh +RIVET_RUN_ENGINE=1 npx tsx --watch src/main.ts +``` + +Your server now connects to the Rivet Engine on `http://localhost:6420`. Clients connect directly to the engine on this port. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +To point at a remote engine instead, set `RIVET_ENDPOINT=https://...` and omit `RIVET_RUN_ENGINE`. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend: + +### Effect + +The Effect client imports the same actor contract from your registry. `Counter.client` yields a typed accessor backed by the client layer: + +```ts src/client.ts @nocheck +import { NodeRuntime } from "@effect/platform-node"; +import { Client } from "@rivetkit/effect"; +import { Effect } from "effect"; +import { Counter } from "./actors/counter/api.ts"; + +const program = Effect.gen(function* () { + const counter = (yield* Counter.client).getOrCreate("my-counter"); + + const count = yield* counter.Increment({ amount: 3 }); + yield* Effect.log(`New count: ${count}`); + + const total = yield* counter.GetCount(); + yield* Effect.log(`Total: ${total}`); +}); + +const ClientLayer = Client.layer({ endpoint: "http://localhost:6420" }); + +program.pipe(Effect.provide(ClientLayer), NodeRuntime.runMain); +``` + +With the server still running, start the client in another terminal: + +```sh +npx tsx src/client.ts +``` + +See the [`chat-room-effect`](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room-effect) example for a larger project with typed errors and actor-to-actor calls. + +### TypeScript + +A plain RivetKit client can call your Effect actor by name through the same engine. Actor and action names are resolved at runtime, so the client is untyped here: + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient("http://localhost:6420"); + +const counter = client.Counter.getOrCreate(["my-counter"]); + +const count = await counter.Increment({ amount: 3 }); +console.log("New count:", count); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### Deploy + +## Feature Support + +The Effect SDK wraps the most common actor features with typed, schema-validated APIs. Everything else is still fully usable through the raw RivetKit context (see [Raw Escape Hatch](#raw-escape-hatch) below), so no feature is off limits, it just isn't typed yet. + +| Feature | Effect-native API | Access | +| --- | --- | --- | +| Actor contract & actions | `Actor.make`, `Action.make` | Typed | +| Persisted state | `State.get` / `set` / `update` / `updateAndGet` / `changes` | Typed | +| Typed client | `Actor.client`, `Client.layer` | Typed | +| Typed errors | `RivetError` | Typed | +| Logging | `RivetLogger` | Typed | +| Sleep request | `Actor.Sleep` | Typed | +| Actor address (`actorId` / `name` / `key`) | `Actor.CurrentAddress` | Typed | +| Registry serve / test / web handler | `Registry` | Typed | +| [Events & broadcast](/docs/actors/events) | Not yet wrapped | `rawRivetkitContext.broadcast(...)` | +| [Schedule](/docs/actors/schedule) | Not yet wrapped | `rawRivetkitContext.schedule.*` | +| [Embedded SQLite](/docs/actors/sqlite) | Not yet wrapped | `rawRivetkitContext.db.execute(...)` | +| [Destroy](/docs/actors/lifecycle) | Not yet wrapped | `rawRivetkitContext.destroy()` | +| Queues, connections, vars, alarms | Not yet wrapped | `rawRivetkitContext.*` | +| Lifecycle hooks (`onSleep` / `onDestroy`) | Not yet wrapped | `rawRivetkitContext.*` | +| Raw HTTP / WebSocket handlers | Not yet wrapped | `rawRivetkitContext.*` | + +### Raw Escape Hatch + +Every wake function receives `rawRivetkitContext`, the underlying RivetKit [actor context](/docs/actors). Reach for it to use any feature that does not have a typed wrapper yet. The typed `state` argument and the raw context point at the same actor, so you can mix both: + +```ts src/actors/counter/live.ts @nocheck +export const CounterLive = Counter.toLayer( + Effect.fnUntraced(function* ({ rawRivetkitContext, state }) { + return Counter.of({ + Increment: Effect.fnUntraced(function* ({ payload }) { + // Typed state wrapper + const next = yield* State.updateAndGet(state, (current) => ({ + count: current.count + payload.amount, + })).pipe(Effect.orDie); + + // Untyped features run through the raw context + rawRivetkitContext.broadcast("newCount", next.count); + rawRivetkitContext.schedule.after(1_000, "tick", {}); + + return next.count; + }), + }); + }), + { + state: { + schema: Schema.Struct({ count: Schema.Number }), + initialValue: () => ({ count: 0 }), + }, + name: "Counter", + }, +); +``` + +Calls through `rawRivetkitContext` are not validated by `effect/Schema` and their payloads are typed as they are in the base RivetKit API. + +## Next Steps + + +- [Actions](/docs/actors/actions) — Define the RPC surface clients call on your actor. + + +- [State](/docs/actors/state) — Persist and load actor state across sleeps and restarts. + + +- [Events](/docs/actors/events) — Broadcast realtime updates to connected clients. + +_Source doc path: /docs/actors/quickstart/effect_ diff --git a/.agents/skills/ai-agent/reference/actors/quickstart/next-js.md b/.agents/skills/ai-agent/reference/actors/quickstart/next-js.md new file mode 100644 index 0000000..f621606 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/quickstart/next-js.md @@ -0,0 +1,117 @@ +# Next.js Quickstart + +> Source: `src/content/docs/actors/quickstart/next-js.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/next-js +> Description: Get started with Rivet Actors in Next.js + +--- +### Add Rivet Skill to Coding Agent (Optional) + +If you're using an AI coding assistant (like Claude Code, Cursor, Windsurf, etc.), add Rivet skills for enhanced development assistance: + +```sh +npx skills add rivet-dev/skills +``` + +### Create a Next.js App + +```sh +npx create-next-app@latest my-app +cd my-app +``` + +### Install RivetKit + +### Create an Actor + +Create a file at `src/rivet/registry.ts` with a simple counter actor: + +### Setup Rivet API route + +Create a file at `src/app/api/rivet/[...all]/route.ts` to setup the API routes: + +```ts src/app/api/rivet/[...all]/route.ts @nocheck +import { toNextHandler } from "@rivetkit/next-js"; +import { registry } from "@/rivet/registry"; + +export const maxDuration = 300; + +export const { GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS } = toNextHandler(registry); +``` + +### Use the Actor in a component + +Create a Counter component and add it to your page: + +```tsx src/components/Counter.tsx @nocheck +"use client"; + +import { createRivetKit } from "@rivetkit/next-js/client"; +import type { registry } from "@/rivet/registry"; +import { useState } from "react"; + +export const { useActor } = createRivetKit({ + endpoint: + process.env.NEXT_PUBLIC_RIVET_ENDPOINT ?? "http://localhost:3000/api/rivet", + namespace: process.env.NEXT_PUBLIC_RIVET_NAMESPACE, + token: process.env.NEXT_PUBLIC_RIVET_TOKEN, +}); + +export function Counter() { + const [count, setCount] = useState(0); + + // Get or create a counter actor for the key "my-counter" + const counter = useActor({ + name: "counter", + key: ["my-counter"] + }); + + // Listen to realtime events + counter.useEvent("newCount", (x: number) => setCount(x)); + + const increment = async () => { + // Call actions + await counter.connection?.increment(1); + }; + + return ( +
+

Count: {count}

+ +
+ ); +} +``` + +```tsx src/app/page.tsx @nocheck +import { Counter } from "@/components/Counter"; + +export default function Home() { + return ( +
+

My App

+ +
+ ); +} +``` + +For information about the Next.js client API, see the [React Client API Reference](/docs/clients/react). + +### Run Locally + +Start the Next.js dev server. Rivet auto-starts a local engine alongside it: + +```sh +npm run dev +``` + +Open `http://localhost:3000` in your browser to use the app. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Deploy to Vercel + +See the [Vercel deployment guide](/docs/deploy/vercel) for detailed instructions on deploying your Rivet app to Vercel. + +_Source doc path: /docs/actors/quickstart/next-js_ diff --git a/.agents/skills/ai-agent/reference/actors/quickstart/react.md b/.agents/skills/ai-agent/reference/actors/quickstart/react.md new file mode 100644 index 0000000..8722fed --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/quickstart/react.md @@ -0,0 +1,82 @@ +# React Quickstart + +> Source: `src/content/docs/actors/quickstart/react.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/react +> Description: Build realtime React applications with Rivet Actors + +--- +## Steps + +### Add Rivet Skill to Coding Agent (Optional) + +If you're using an AI coding assistant (like Claude Code, Cursor, Windsurf, etc.), add Rivet skills for enhanced development assistance: + +```sh +npx skills add rivet-dev/skills +``` + +### Install Dependencies + +```sh +npm install rivetkit @rivetkit/react +``` + +### Create Backend Actor and Start Server + +Create your actor registry on the backend and start the server: + +### Create React Frontend + +Set up your React application: + +For detailed information about the React client API, see the [React Client API Reference](/docs/clients/react). + +### Setup Vite Configuration + +Configure Vite for development: + +```ts vite.config.ts @nocheck +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [react()], + server: { + port: 5173, + }, +}) +``` + +### Run Your Application + +Start both the backend and frontend: + +**Terminal 1**: Start the backend + +```sh Node.js +npx tsx --watch backend/index.ts +``` + +```sh Bun +bun --watch backend/index.ts +``` + +```sh Deno +deno run --allow-net --allow-read --allow-env --watch backend/index.ts +``` + +**Terminal 2**: Start the frontend + +```sh Frontend +npx vite +``` + +Open `http://localhost:5173` in your browser. Try opening multiple tabs to see realtime sync in action. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Deploy + +## Configuration Options + +_Source doc path: /docs/actors/quickstart/react_ diff --git a/.agents/skills/ai-agent/reference/actors/quickstart/rust.md b/.agents/skills/ai-agent/reference/actors/quickstart/rust.md new file mode 100644 index 0000000..1e55471 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/quickstart/rust.md @@ -0,0 +1,249 @@ +# Rust Quickstart (Beta) + +> Source: `src/content/docs/actors/quickstart/rust.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/rust +> Description: Build a Rivet Actor in Rust + +--- +Rust support is in beta. The supported public Rust API is `rivetkit` and `rivetkit-client`; lower-level crates are internal implementation details and do not carry a stability guarantee. See the full API reference on [docs.rs/rivetkit](https://docs.rs/rivetkit), or the runnable [`hello-world-rust`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-rust) example. + +## Steps + +### Add Rivet + +Add the `rivetkit` crate and its companions: + +```sh +cargo add rivetkit anyhow async-trait +cargo add serde --features derive +cargo add tokio --features full +``` + +### Define Your Actor + +Put the actor in `src/lib.rs` so both your server and your client can share the same types. An actor is a type that implements `Actor`, plus one `Handles` implementation for each action. Persisted state lives in `type State`; ephemeral runtime state is just fields on your actor struct. + +```rust src/lib.rs +use std::{future::Future, pin::Pin, sync::Arc}; + +use async_trait::async_trait; +use rivetkit::prelude::*; +use serde::{Deserialize, Serialize}; + +type BoxFuture = Pin> + Send>>; + +pub struct Counter; + +#[derive(Default, Serialize, Deserialize)] +pub struct CounterState { + pub count: i64, +} + +#[derive(Serialize, Deserialize)] +pub struct Increment { + pub amount: i64, +} + +impl Action for Increment { + type Output = i64; + + const NAME: &'static str = "increment"; +} + +#[derive(Serialize, Deserialize)] +pub struct NewCount { + pub count: i64, +} + +impl Event for NewCount { + const NAME: &'static str = "newCount"; +} + +#[async_trait] +impl Actor for Counter { + type State = CounterState; + type Input = (); + type Actions = (Increment,); + type Events = (NewCount,); + type Queue = (); + type ConnParams = (); + type ConnState = (); + type Action = action::Raw; + + async fn create_state(_ctx: &Ctx, _input: Self::Input) -> Result { + Ok(CounterState::default()) + } + + async fn create(_ctx: &Ctx) -> Result { + Ok(Self) + } +} + +impl Handles for Counter { + type Future = BoxFuture; + + fn handle(self: Arc, ctx: Ctx, action: Increment) -> Self::Future { + Box::pin(async move { + let count = { + let mut state = ctx.state_mut(); + state.count += action.amount; + state.count + }; + ctx.emit(NewCount { count })?; + Ok(count) + }) + } +} + +pub fn registry() -> Registry { + let mut registry = Registry::new(); + registry.register_actor::("counter"); + registry +} +``` + +### Serve The Registry + +Your `src/main.rs` just starts the registry from the library: + +```rust src/main.rs +#[tokio::main] +async fn main() -> anyhow::Result<()> { + counter::registry().start().await +} +``` + +Replace `counter` with your crate name (the package `name` in `Cargo.toml`, with dashes as underscores). + +### Run The Server + +The Rust runtime connects to the Rivet Engine. Setting `RIVETKIT_ENGINE_AUTO_DOWNLOAD=1` lets the runtime download and cache a matching engine binary the first time you run, so there is nothing else to install: + +```sh +RIVETKIT_ENGINE_AUTO_DOWNLOAD=1 cargo run +``` + +Your server now connects to the Rivet Engine on `http://localhost:6420`. Clients connect directly to the engine on this port. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +Already have an engine binary? Set `RIVET_ENGINE_BINARY_PATH=/path/to/rivet-engine` to point at it instead. If you are working inside the [Rivet monorepo](https://github.com/rivet-dev/rivet), a local `cargo build -p rivet-engine` is discovered automatically from `target/debug`. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend: + +### Rust + +Add a `src/bin/client.rs` that imports the same actor types from your library. There is no need to redefine the actor on the client. + +```rust src/bin/client.rs +use counter::{Counter, Increment, NewCount}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + let count = counter.send(Increment { amount: 3 }).await?; + println!("New count: {count}"); + + let connection = counter.connect(); + connection + .on::(|event| println!("Count changed: {}", event.count)) + .await; + connection.send(Increment { amount: 1 }).await?; + + Ok(()) +} +``` + +With the server still running, start the client in another terminal: + +```sh +cargo run --bin client +``` + +See the [`hello-world-rust`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-rust) example for a complete runnable counter. + +### TypeScript + +A TypeScript client can call your Rust actor by name through the same engine. Actor and action names are resolved at runtime, so the client is untyped here: + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient("http://localhost:6420"); + +const counter = client.counter.getOrCreate(["my-counter"]); + +const counterConnection = counter.connect(); +counterConnection.on("newCount", (event) => { + console.log("Event count:", event.count); +}); + +const count = await counterConnection.increment(3); +console.log("New count:", count); + +await counterConnection.increment(1); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### React + +```tsx Counter.tsx @nocheck +import { createRivetKit } from "@rivetkit/react"; +import { useState } from "react"; + +const { useActor } = createRivetKit("http://localhost:6420"); + +function Counter() { + const [count, setCount] = useState(0); + + const counter = useActor({ + name: "counter", + key: ["my-counter"], + }); + + const increment = async () => { + await counter.connection?.increment(1); + }; + + counter.useEvent("newCount", (event) => { + setCount(event.count); + }); + + return ( +
+

Count: {count}

+ +
+ ); +} +``` + +See the [React documentation](/docs/clients/react) for more information. + +### Deploy + +## Next Steps + + +- [API Reference](https://docs.rs/rivetkit) — Full `rivetkit` crate documentation on docs.rs. + + +- [Actions](/docs/actors/actions) — Define the RPC surface clients call on your actor. + + +- [State](/docs/actors/state) — Persist and load actor state across sleeps and restarts. + + +- [Events](/docs/actors/events) — Broadcast realtime updates to connected clients. + +_Source doc path: /docs/actors/quickstart/rust_ diff --git a/.agents/skills/ai-agent/reference/actors/quickstart/supabase.md b/.agents/skills/ai-agent/reference/actors/quickstart/supabase.md new file mode 100644 index 0000000..20b59d0 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/quickstart/supabase.md @@ -0,0 +1,109 @@ +# Supabase Functions Quickstart + +> Source: `src/content/docs/actors/quickstart/supabase.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/supabase +> Description: Set up a Rivet project locally targeting Supabase Edge Functions. + +--- +Set up a Rivet project locally that runs on Supabase Edge Functions. The `@rivetkit/supabase` package wires the WebAssembly runtime for you. + +Prefer to start from a complete project? See the runnable [`hello-world-supabase-functions`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-supabase-functions) example. + +## Steps + +### Prerequisites + +- [Node.js](https://nodejs.org/) +- [Supabase CLI](https://supabase.com/docs/guides/cli) +- Docker, for Supabase's local Edge Runtime + +The CLI runs the local Rivet engine as a bundled native binary, so Docker is only needed for Supabase itself. A Supabase project is only needed to deploy. + +### Create the Function + +```sh +npx supabase functions new rivet +``` + +Add the packages used by the function: + +```sh +npm install rivetkit @rivetkit/supabase +``` + +### Configure the Function + +Call `serve` from `@rivetkit/supabase`. It loads the WebAssembly runtime and serves the Rivet handler. + +```ts supabase/functions/rivet/index.ts @nocheck +import { actor } from "rivetkit"; +import { serve, setup } from "@rivetkit/supabase"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +// `setup` returns a typed registry, so a client can type itself with +// `typeof registry`. +export const registry = setup({ use: { counter } }); + +await serve(registry); +``` + +Add a `deno.json` next to the function so the deploy bundles only the WebAssembly runtime. It points `rivetkit` at the pre-bundled `@rivetkit/supabase`, keeping the deploy small. Without it, the deploy pulls Rivet's native engine and 413s. + +```json supabase/functions/rivet/deno.json +{ + "imports": { + "rivetkit": "npm:@rivetkit/supabase", + "@rivetkit/supabase": "npm:@rivetkit/supabase" + } +} +``` + +Your function code keeps importing from `rivetkit` as usual. The import map only changes how Deno resolves it at bundle time. + +### Run Locally + +Start Rivet. The CLI runs the local engine, spawns `supabase functions serve` for you, and populates the connection values: + +```sh +npx @rivetkit/cli dev --provider supabase +``` + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Call the Actor + +Connect to your actor from a client. This connects directly to the local engine on `http://localhost:6420`: + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./supabase/functions/rivet/index"; + +const client = createClient("http://localhost:6420"); + +const counter = client.counter.getOrCreate(["my-counter"]); +const count = await counter.increment(3); +console.log("New count:", count); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### Deploy + +Ready to ship? See [Deploying to Supabase Functions](/docs/deploy/supabase). + +## Related + +- [Quickstart](/docs/actors/quickstart) +- [Deploying to Supabase Functions](/docs/deploy/supabase) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/actors/quickstart/supabase_ diff --git a/.agents/skills/ai-agent/reference/actors/request-handler.md b/.agents/skills/ai-agent/reference/actors/request-handler.md new file mode 100644 index 0000000..0536b9c --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/request-handler.md @@ -0,0 +1,79 @@ +# Low-Level HTTP Request Handler + +> Source: `src/content/docs/actors/request-handler.mdx` +> Canonical URL: https://rivet.dev/docs/actors/request-handler +> Description: Actors can handle HTTP requests through the `onRequest` handler. + +--- +For most use cases, [actions](/docs/actors/actions) provide high-level API powered by HTTP that's easier to work with than low-level HTTP. However, low-level handlers are required when implementing custom use cases or integrating external libraries that need direct access to the underlying HTTP `Request`/`Response` objects or WebSocket connections. + +## Handling HTTP Requests + +The `onRequest` handler processes HTTP requests sent to your actor. It receives the actor context and a standard `Request` object and returns a `Response` object. + +### Raw HTTP + +### Hono + +See also the [raw fetch handler example](https://github.com/rivet-dev/rivet/tree/main/examples/raw-fetch-handler). + +## Sending Requests To Actors + +### Via RivetKit Client + +Use the `.fetch()` method on an actor handle to send HTTP requests to the actor's `onRequest` handler. This can be executed from either your frontend or backend. + +### Via getGatewayUrl + +Use `.getGatewayUrl()` to get the raw gateway URL for the actor. This is useful when you need to use the URL with external tools or custom HTTP clients. + +### Via HTTP API + +This handler can be accessed with raw HTTP using `https://api.rivet.dev/gateway/{actorId}/request/{...path}`. + +For example, to call `POST /increment` on the counter actor above: + +```bash +curl -X POST "https://api.rivet.dev/gateway/{actorId}/request/increment" \ + -H "x-rivet-token: {token}" +``` + +The request is routed to the actor's `onRequest` handler where: + +- `request.method` is `"POST"` +- `request.url` ends with `/increment` (the path after `/request/`) +- Headers, body, and other request properties are passed through unchanged + +See the [HTTP API reference](/docs/actors/http-api) for more information on HTTP routing and authentication. + +### Via Proxying Requests + +You can proxy HTTP requests from your own server to actor handlers using the RivetKit client. This is useful when you need to add custom authentication, rate limiting, or request transformation before forwarding to actors. + +## Connection & Lifecycle Hooks + +`onRequest` will trigger the `onBeforeConnect`, `onConnect`, and `onDisconnect` hooks. Read more about [lifecycle hooks](/docs/actors/lifecycle). + +Requests in flight will be listed in `c.conns`. Read more about [connections](/docs/actors/connections). + +## WinterTC Compliance + +The `onRequest` handler is WinterTC compliant and will work with existing libraries using the standard `Request` and `Response` types. + +## Limitations + +- Does not support streaming responses & server-sent events at the moment. See the [tracking issue](https://github.com/rivet-dev/rivet/issues/3529). +- `OPTIONS` requests currently are handled by Rivet and are not passed to `onRequest` + +## Advanced + +### Skip Ready Wait + +Requests are normally held at the gateway until the actor is ready. Pass `skipReadyWait: true` on `handle.fetch()` to deliver immediately, including while the actor is still starting or in the [sleep grace period](/docs/actors/lifecycle#shutdown-sequence). See [Skip Ready Wait](/docs/clients/javascript#skip-ready-wait) for details. + +## API Reference + +- [`RequestContext`](/typedoc/interfaces/rivetkit.mod.RequestContext.html) - Context for HTTP request handlers +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining request handlers + +_Source doc path: /docs/actors/request-handler_ diff --git a/.agents/skills/ai-agent/reference/actors/scaling.md b/.agents/skills/ai-agent/reference/actors/scaling.md new file mode 100644 index 0000000..b597115 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/scaling.md @@ -0,0 +1,10 @@ +# Scaling & Concurrency + +> Source: `src/content/docs/actors/scaling.mdx` +> Canonical URL: https://rivet.dev/docs/actors/scaling +> Description: This page has moved to [design patterns](/docs/actors/design-patterns). + +--- + + +_Source doc path: /docs/actors/scaling_ diff --git a/.agents/skills/ai-agent/reference/actors/schedule.md b/.agents/skills/ai-agent/reference/actors/schedule.md new file mode 100644 index 0000000..8dfdb1f --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/schedule.md @@ -0,0 +1,40 @@ +# Actor Scheduling + +> Source: `src/content/docs/actors/schedule.mdx` +> Canonical URL: https://rivet.dev/docs/actors/schedule +> Description: Schedule actor actions in the future with persistent timers that survive restarts and upgrades. + +--- +Scheduling is used to trigger events in the future. The actor scheduler is like `setTimeout`, except the timeout will persist even if the actor restarts, upgrades, or crashes. + +For a pattern guide to durable recurring jobs, see the cookbook: [Cron Jobs and Scheduled Tasks](/cookbook/cron-jobs/). + +## Use Cases + +Scheduling is helpful for long-running timeouts like month-long billing periods or account trials. + +## Scheduling + +### `c.schedule.after(duration, actionName, ...args)` + +Schedules a function to be executed after a specified duration. This function persists across actor restarts, upgrades, or crashes. + +Parameters: + +- `duration` (number): The delay in milliseconds. +- `actionName` (string): The name of the action to be executed. +- `...args` (unknown[]): Additional arguments to pass to the function. + +### `c.schedule.at(timestamp, actionName, ...args)` + +Schedules a function to be executed at a specific timestamp. This function persists across actor restarts, upgrades, or crashes. + +Parameters: + +- `timestamp` (number): The exact time in milliseconds since the Unix epoch when the function should be executed. +- `actionName` (string): The name of the action to be executed. +- `...args` (unknown[]): Additional arguments to pass to the function. + +## Full Example + +_Source doc path: /docs/actors/schedule_ diff --git a/.agents/skills/ai-agent/reference/actors/sharing-and-joining-state.md b/.agents/skills/ai-agent/reference/actors/sharing-and-joining-state.md new file mode 100644 index 0000000..1fe0683 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/sharing-and-joining-state.md @@ -0,0 +1,10 @@ +# Sharing and Joining State + +> Source: `src/content/docs/actors/sharing-and-joining-state.mdx` +> Canonical URL: https://rivet.dev/docs/actors/sharing-and-joining-state +> Description: This page has moved to [design patterns](/docs/actors/design-patterns). + +--- + + +_Source doc path: /docs/actors/sharing-and-joining-state_ diff --git a/.agents/skills/ai-agent/reference/actors/sqlite-drizzle.md b/.agents/skills/ai-agent/reference/actors/sqlite-drizzle.md new file mode 100644 index 0000000..f0184d9 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/sqlite-drizzle.md @@ -0,0 +1,248 @@ +# SQLite + Drizzle + +> Source: `src/content/docs/actors/sqlite-drizzle.mdx` +> Canonical URL: https://rivet.dev/docs/actors/sqlite-drizzle +> Description: Use Drizzle ORM with embedded SQLite in Rivet Actors. + +--- +Use Drizzle when you want typed schema, typed queries, and generated migrations on top of actor-local SQLite. + +For a high-level overview of where to store actor data, see [State & Storage](/docs/actors/state). For a worked multi-tenant pattern, see the cookbook: [Database per Tenant](/cookbook/per-tenant-database/). + +## What is Drizzle good for? + +- **Typed schema**: define tables in TypeScript and get typed query results. +- **Typed query builder**: write SQL-like queries with autocompletion. +- **Migration workflow**: generate SQL migration files from schema changes. +- **Raw SQL escape hatch**: use `c.db.execute(...)` for direct SQLite when needed. + +## Project structure + +Use one folder per actor database: + +```txt +src/ + actors/ + todo-list/ + index.ts + schema.ts + drizzle.config.ts + drizzle/ + 0000_init.sql + migrations.js + migrations.d.ts + meta/ + _journal.json +``` + +- `index.ts` is the actor implementation. +- `drizzle/` holds the SQL migrations (`*.sql`) and `meta/_journal.json` generated by `drizzle-kit`. +- `migrations.js` is a small RivetKit glue file you maintain by hand. It imports the journal and each `*.sql` file and exports a `{ journal, migrations }` object keyed by migration (for example `m0000`). Add a new entry here whenever `db:generate` produces a new migration. +- Commit the generated migration files and `migrations.js` to source control. + +## Basic setup + +```json package.json +{ + "scripts": { + "db:generate": "find src/actors -name drizzle.config.ts -exec drizzle-kit generate --config {} \\;" + }, + "dependencies": { + "rivetkit": "*", + "drizzle-orm": "^0.44.2" + }, + "devDependencies": { + "drizzle-kit": "^0.31.2" + } +} +``` + +```ts vite.config.ts @nocheck +import { defineConfig, type Plugin } from "vite"; +import { readFileSync } from "node:fs"; + +function sqlRawPlugin(): Plugin { + return { + name: "sql-raw", + transform(_code, id) { + if (id.endsWith(".sql")) { + const content = readFileSync(id, "utf-8"); + return { code: `export default ${JSON.stringify(content)};` }; + } + }, + }; +} + +export default defineConfig({ + plugins: [sqlRawPlugin()], +}); +``` + +```ts drizzle.config.ts @nocheck +import { defineConfig } from "rivetkit/db/drizzle"; + +export default defineConfig({ + schema: "./src/actors/todo-list/schema.ts", + out: "./src/actors/todo-list/drizzle", +}); +``` + +```sql 0000_init.sql +CREATE TABLE `todos` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `title` text NOT NULL, + `created_at` integer NOT NULL +); +``` + +```json _journal.json +{ + "version": "7", + "dialect": "sqlite", + "entries": [ + { + "idx": 0, + "version": "7", + "when": 1735689600000, + "tag": "0000_init", + "breakpoints": true + } + ] +} +``` + +```ts migrations.js @nocheck +import journal from "./meta/_journal.json"; +import m0000 from "./0000_init.sql"; + +export default { + journal, + migrations: { + m0000, + }, +}; +``` + +```ts index.ts @nocheck +import { actor } from "rivetkit"; +import { db } from "rivetkit/db/drizzle"; +import migrations from "./drizzle/migrations.js"; +import { schema, todos } from "./schema.ts"; + +export const todoList = actor({ + db: db({ schema, migrations }), + actions: { + addTodo: async (c, title: string) => { + const rows = await c.db + .insert(todos) + .values({ title, createdAt: Date.now() }) + .returning(); + return rows[0]; + }, + getTodos: async (c) => { + return await c.db.select().from(todos).orderBy(todos.id); + }, + getTodoCount: async (c) => { + const rows = (await c.db.execute( + "SELECT COUNT(*) AS count FROM todos", + )) as { count: number }[]; + return rows[0]?.count ?? 0; + }, + }, +}); +``` + +```ts index.ts @nocheck +import { setup } from "rivetkit"; +import { todoList } from "./todo-list/index.ts"; + +export const registry = setup({ use: { todoList } }); +registry.start(); +``` + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const todoList = client.todoList.getOrCreate(["main"]); + +await todoList.addTodo("Write Drizzle docs"); + +const todos = await todoList.getTodos(); +const count = await todoList.getTodoCount(); + +console.log(todos, count); +``` + +## Queries + +### Query builder + +Use Drizzle's typed query APIs for most reads and writes. + +```ts @nocheck +import { eq } from "drizzle-orm"; + +await c.db.insert(todos).values({ title, createdAt: Date.now() }); + +const rows = await c.db + .select() + .from(todos) + .where(eq(todos.title, title)); +``` + +### Raw SQL + +`rivetkit/db/drizzle` also exposes raw SQLite access through `c.db.execute(...)`. + +```ts @nocheck +await c.db.execute( + "CREATE INDEX IF NOT EXISTS idx_todos_created_at ON todos(created_at)", +); +``` + +## Queues + +Use queues for ordered mutations and keep actions read-only. Import `queue` alongside `actor` from `rivetkit`. + +```ts @nocheck +import { actor, queue } from "rivetkit"; + +// ... + +queues: { + addTodo: queue<{ title: string }>(), +}, +run: async (c) => { + for await (const message of c.queue.iter()) { + if (message.name === "addTodo") { + await c.db.insert(todos).values({ + title: message.body.title, + createdAt: Date.now(), + }); + } + } +}, +actions: { + getTodos: async (c) => await c.db.select().from(todos), +}, +``` + +## Recommendations + +- Prefer Drizzle query APIs for app code and use raw SQL for advanced SQLite features. +- Keep one `drizzle.config.ts` per actor folder. +- Re-run `db:generate` after schema changes and commit generated migration files. +- Use queues for writes and actions for reads. +- Keep related writes in one action or queue message to reduce interleaved query risk. + +## Read more + +- [Drizzle SQLite quickstart](https://orm.drizzle.team/docs/get-started-sqlite) +- [Drizzle `drizzle-kit generate`](https://orm.drizzle.team/docs/drizzle-kit-generate) +- [Drizzle + Cloudflare D1](https://orm.drizzle.team/docs/deploy-cloudflare-d1) +- [Drizzle + Cloudflare Durable Objects](https://orm.drizzle.team/docs/deploy-cloudflare-do) +- [Cloudflare Durable Objects SQLite storage](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/) + +_Source doc path: /docs/actors/sqlite-drizzle_ diff --git a/.agents/skills/ai-agent/reference/actors/sqlite.md b/.agents/skills/ai-agent/reference/actors/sqlite.md new file mode 100644 index 0000000..fb55998 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/sqlite.md @@ -0,0 +1,127 @@ +# SQLite + +> Source: `src/content/docs/actors/sqlite.mdx` +> Canonical URL: https://rivet.dev/docs/actors/sqlite +> Description: Use embedded SQLite in Rivet Actors with raw SQL queries. + +--- +For a high-level overview of where to store actor data, including when to use `c.state` versus SQLite, see [State & Storage](/docs/actors/state). For a worked multi-tenant pattern, see the cookbook: [Database per Tenant](/cookbook/per-tenant-database/). + +## What is SQLite? + +- **Database per actor**: each actor instance has its own SQLite database, scoped to that actor. +- **High performance**: Rivet Actors keep compute and storage together, so queries avoid network round trips to an external database. +- **Larger-than-memory storage**: SQLite stores data on disk, so you can work with datasets that do not fit in actor memory. +- **Embedded relational database**: use tables, indexes, and SQL queries directly inside actor logic. + +### SQLite features + +- **Indexes**: speed up lookups on frequently queried fields. +- **Search and filtering**: use `WHERE`, `LIKE`, and `ORDER BY` instead of manual in-memory loops. +- **Relationships**: use multiple tables and `JOIN` queries for connected data. +- **Constraints**: use primary keys, unique constraints, and foreign keys for data integrity. +- **Transactions**: apply multiple writes atomically when changes must stay consistent. + +## Raw SQL vs ORM (Drizzle) + +Rivet supports both raw SQL and [Drizzle](https://orm.drizzle.team/) for actor-local SQLite. + +Use **raw SQL** when you want direct query control and minimal abstraction. + +```ts @nocheck +await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); +const rows = await c.db.execute("SELECT id, title FROM todos ORDER BY id DESC"); +``` + +Use **Drizzle** when you want typed schema and typed query APIs. + +```ts @nocheck +await c.vars.drizzle.insert(todos).values({ title }); +const rows = await c.vars.drizzle.select().from(todos).orderBy(desc(todos.id)); +``` + +You can mix both in the same actor. + +For Drizzle setup, see [SQLite + Drizzle](/docs/actors/sqlite-drizzle). + +## Basic setup + +Define `db: db({ onMigrate })` on your actor, create your schema in `onMigrate`, and execute SQL with `c.db.execute(...)`. + +RivetKit wraps `onMigrate` in a SQLite savepoint, so migration steps are atomic. If `onMigrate` throws, all SQL run by that hook is rolled back before the actor starts. + +## Queries + +`c.db.execute(...)` returns an array of row objects for `SELECT` queries. + +```ts @nocheck +const rows = await c.db.execute( + "SELECT id, title FROM todos WHERE title LIKE ?", + `%${query}%`, +); +``` + +### Parameterized queries + +Use `?` placeholders for dynamic values and pass parameters in order after the SQL string. + +```ts @nocheck +await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); +``` + +You can also use named SQLite bindings by passing a single properties object. + +```ts @nocheck +const rows = await c.db.execute( + "SELECT id, title FROM todos WHERE title = :title", + { title: "Write SQLite docs" }, +); +``` + +### Transactions + +Use transactions when multiple writes must succeed or fail together. + +```ts @nocheck +await c.db.transaction(async (tx) => { + await tx.execute("INSERT INTO todos (title) VALUES (?)", title); + await tx.execute( + "INSERT INTO comments (todo_id, body) VALUES (last_insert_rowid(), ?)", + body, + ); +}); +``` + +RivetKit commits when the callback resolves and rolls back when it throws. Other transactions and ordinary actor SQL queue in FIFO order until the callback finishes. Transactions have a 60-second safety timeout by default; increase it for legitimately long work with `{ timeout: 120_000 }`. + +Always use the callback's `tx` value inside the transaction. Starting another transaction or using the outer `c.db` from the callback waits behind the active transaction and eventually reaches the safety timeout; the resulting error points to this possible deadlock. + +Manual `BEGIN`/`COMMIT` calls remain supported for compatibility, but cannot protect against interleaving callers. RivetKit logs a warning recommending `db.transaction()`. Set `warnOnManualTransactions: false` in `db(...)` to disable the warning; the warning itself mentions this flag. + +## Queues + +It's recommended to use queues for mutations and actions for read-only queries. This is the same code structure as the basic setup, but mutation writes are routed through queues. + +## Debugging + +- `GET /inspector/summary` includes `isDatabaseEnabled` so you can confirm SQLite is configured. +- `GET /inspector/database/schema` returns the tables and views discovered in the actor's SQLite database. +- `GET /inspector/database/rows?table=...&limit=100&offset=0` returns paged rows for a specific table or view. +- `POST /inspector/database/execute` lets you run ad-hoc SQL for debugging and data fixes with positional `args` or named `properties`. +- Keep a small read-only action for quick query verification while debugging. +- In non-dev mode, inspector endpoints require authorization. + +## Recommendations + +- Keep schema creation and migration steps in `onMigrate`; RivetKit runs them atomically inside a SQLite savepoint. +- Use `?` placeholders for dynamic values. +- Prefer queue-driven writes for ordered or background work. +- Use transactions for related multi-step mutations when atomicity matters. + +## Read more + +- [SQLite + Drizzle in Rivet Actors](/docs/actors/sqlite-drizzle) +- [SQLite docs](https://sqlite.org/docs.html) +- [SQLite SQL language reference](https://sqlite.org/lang.html) + +_Source doc path: /docs/actors/sqlite_ diff --git a/.agents/skills/ai-agent/reference/actors/state.md b/.agents/skills/ai-agent/reference/actors/state.md new file mode 100644 index 0000000..559b49c --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/state.md @@ -0,0 +1,270 @@ +# In-Memory State + +> Source: `src/content/docs/actors/state.mdx` +> Canonical URL: https://rivet.dev/docs/actors/state +> Description: Actors store state in memory for instant reads and writes. State can be persisted automatically or kept ephemeral. + +--- +## Types of State + +There are three ways to store data in an actor, depending on what it looks like and whether it needs to survive restarts. + +### Durable + +Simple, serializable data on `c.state` that is automatically persisted and restored across restarts. The default starting point. + +### Ephemeral + +Live objects on `c.vars` like database connections, API clients, and event emitters, or data loaded from an external source. Never persisted. + +```typescript @nocheck External database +import { actor } from "rivetkit"; +import { Pool } from "pg"; + +// One shared pool for the whole process, created once and reused by every actor +const pool = new Pool({ connectionString: process.env.DATABASE_URL }); + +const userActor = actor({ + state: { profile: null as Record | null }, + + // Load this actor's row from the shared pool on each start + createVars: async (c) => { + const { rows } = await pool.query("SELECT * FROM users WHERE id = $1", [c.key[0]]); + return { profile: rows[0] }; + }, + + actions: { + updateEmail: async (c, email: string) => { + await pool.query("UPDATE users SET email = $1 WHERE id = $2", [email, c.key[0]]); + } + } +}); +``` + +### SQLite + +Rivet also provides an embedded SQLite database (`c.db`) for when your data needs to be queried, requires safe schema migrations, or grows too large to hold in memory. See [SQLite](/docs/actors/sqlite). + +```typescript @nocheck Basic +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +const todoList = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL + ); + `); + }, + }), + + actions: { + add: async (c, title: string) => { + await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); + }, + + list: async (c) => { + return (await c.db.execute( + "SELECT id, title FROM todos ORDER BY id DESC", + )) as { id: number; title: string }[]; + }, + }, +}); +``` + +```typescript @nocheck Load into memory +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +const counter = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS counter ( + id INTEGER PRIMARY KEY CHECK (id = 1), + count INTEGER NOT NULL + ); + `); + await db.execute("INSERT OR IGNORE INTO counter (id, count) VALUES (1, 0)"); + }, + }), + + // Load the count from SQLite into memory on every start + createVars: async (c) => { + const rows = (await c.db.execute( + "SELECT count FROM counter WHERE id = 1", + )) as { count: number }[]; + return { count: rows[0].count }; + }, + + actions: { + get: (c) => c.vars.count, + + increment: async (c) => { + // Update the in-memory value and write it back to SQLite + c.vars.count += 1; + await c.db.execute("UPDATE counter SET count = ? WHERE id = 1", c.vars.count); + return c.vars.count; + }, + }, +}); +``` + +## State Isolation + +Each actor's state is fully isolated. Other actors and clients can't touch it directly; all reads and writes go through the actor's own [Actions](/docs/actors/actions). To share state across actors, see [sharing and joining state](/docs/actors/sharing-and-joining-state). + +## Durable State + +`c.state` lives in memory and is persisted automatically, so reads and writes have no added latency while the data still survives sleeps, restarts, upgrades, and crashes. Use it for small, simple values like counters, flags, and small maps. + +`createState` runs once when the actor is first created. On later starts, state is loaded from storage instead of recreated. See [Lifecycle](/docs/actors/lifecycle). + +### When state saves + +Mutating `c.state` schedules a save automatically. Rapid mutations are batched into a single write on a throttle (`stateSaveInterval`, default 1 second). Reads never trigger a save, saves aren't tied to action or handler boundaries, and state is also flushed when the actor sleeps or shuts down. + +To force a save mid-action, call `c.saveState()`: + +- `c.saveState({ immediate: true })` writes immediately and resolves once the write completes. +- `c.saveState()` schedules a throttled save and returns right away, without waiting for the write. + +Force an immediate save before a risky side effect so a crash can't lose progress: + +### Supported types + +State must be serializable. + +- `null`, `undefined`, `boolean`, `string`, `number`, `BigInt` +- `Date`, `RegExp`, `Error` +- `ArrayBuffer` and typed arrays (`Uint8Array`, `Int8Array`, `Float32Array`, etc.) +- `Map`, `Set`, `Array` +- Plain objects + +When data grows large or needs querying, store it in [Embedded SQLite](#embedded-sqlite) instead. + +## Ephemeral State + +`c.vars` holds data that exists only while the actor runs and is never saved. Use it for live objects that can't be serialized (connections, clients, emitters) or for data loaded from an external source. Most actors use both: `state` for durable data, `vars` for live objects. + +`createVars` runs on every actor start, unlike `createState` which runs once. That makes it the place to open connections and load data each time the actor wakes. + +### Runtime objects + +Build non-serializable objects in `createVars` and use them from actions: + +### Loading from external sources + +Create the connection pool once at module scope and share it across all actors, then use `createVars` (which can be `async`) to load this actor's data from it on each start: + +```typescript @nocheck +import { actor } from "rivetkit"; +import { Pool } from "pg"; + +// One shared pool for the whole process, not one per actor +const pool = new Pool({ connectionString: process.env.DATABASE_URL }); + +const profile = actor({ + state: { cachedName: "" }, + + createVars: async (c) => { + const { rows } = await pool.query("SELECT * FROM users WHERE id = $1", [c.key[0]]); + return { user: rows[0] }; + }, + + actions: { + updateEmail: async (c, email: string) => { + await pool.query("UPDATE users SET email = $1 WHERE id = $2", [email, c.key[0]]); + } + } +}); +``` + +When the actor owns its data, prefer [durable state](#durable-state) or [SQLite](#embedded-sqlite), which need no external infrastructure. + +### Cleanup + +`vars` is dropped when the actor stops, but per-actor resources like timers, subscriptions, and dedicated connections aren't cleaned up for you. Release them in `onSleep` and `onDestroy`. A shared pool stays open for the whole process, so don't close it per actor. + +```typescript @nocheck +const poller = actor({ + state: { ticks: 0 }, + + // Per-actor timer started on each wake + createVars: (c) => ({ timer: setInterval(() => c.state.ticks++, 5000) }), + + // Clear it before the actor sleeps or is destroyed + onSleep: (c) => clearInterval(c.vars.timer), + onDestroy: (c) => clearInterval(c.vars.timer), + + actions: { /* ... */ } +}); +``` + +## Embedded SQLite + +`c.db` is a SQLite database scoped to each actor and stored on disk. Use it for queryable, relational, or larger-than-memory data. Because compute and storage live together, queries run locally with no network round trips. + +A common pattern is to treat SQLite as the source of truth and keep a working copy in `c.vars`: load rows in `createVars`, serve reads from memory, and write changes back to `c.db`. + +```typescript @nocheck +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +const leaderboard = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS scores ( + player TEXT PRIMARY KEY, + score INTEGER NOT NULL + ); + `); + }, + }), + + // Load the table into memory once per start + createVars: async (c) => { + const rows = (await c.db.execute("SELECT player, score FROM scores")) as { + player: string; + score: number; + }[]; + return { scores: new Map(rows.map((r) => [r.player, r.score])) }; + }, + + actions: { + top: (c) => [...c.vars.scores].sort((a, b) => b[1] - a[1]).slice(0, 10), + + record: async (c, player: string, score: number) => { + c.vars.scores.set(player, score); + // Write through to SQLite + await c.db.execute( + "INSERT INTO scores (player, score) VALUES (?, ?) ON CONFLICT(player) DO UPDATE SET score = ?", + player, score, score, + ); + }, + }, +}); +``` + +For the full query API, schema migrations, transactions, and the Drizzle ORM, see: + +- [SQLite](/docs/actors/sqlite): raw SQL against the embedded per-actor database. +- [SQLite + Drizzle](/docs/actors/sqlite-drizzle): typed schema and query APIs. + +## Debugging + +- `GET /inspector/state` returns the actor's current state and `isStateEnabled`. +- `PATCH /inspector/state` lets you set state directly while debugging. +- In non-dev mode, inspector endpoints require authorization. + +## API Reference + +- [`CreateContext`](/typedoc/types/rivetkit.mod.CreateContext.html) - Context available during actor state creation +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - Context available throughout actor lifecycle +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining actors with state + +_Source doc path: /docs/actors/state_ diff --git a/.agents/skills/ai-agent/reference/actors/statuses.md b/.agents/skills/ai-agent/reference/actors/statuses.md new file mode 100644 index 0000000..cccf52a --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/statuses.md @@ -0,0 +1,36 @@ +# Actor Statuses + +> Source: `src/content/docs/actors/statuses.mdx` +> Canonical URL: https://rivet.dev/docs/actors/statuses +> Description: Understand the lifecycle statuses of Rivet Actors, what they mean, how they appear in the API, and how to troubleshoot common issues. + +--- +## Statuses + +These are the statuses you can see in the dashboard for each actor. + +| Status | Description | +|---|---| +| **Starting** | The actor has been created but has not yet become connectable. | +| **Running** | The actor is live and accepting connections. | +| **Destroyed** | The actor has been gracefully destroyed. | +| **Crashed** | The actor failed to start or encountered a fatal error. See [Troubleshooting](/docs/actors/troubleshooting#actor-status-is-crashed) for common failure reasons. | +| **Sleeping** | The actor has been put to sleep from inactivity. It will be woken up automatically when a new request arrives. | +| **Pending** | The actor is waiting to be allocated to a runner. This happens when no runner is available to handle the actor. See [Troubleshooting](/docs/actors/troubleshooting#actor-status-is-pending) for common causes. | +| **Crash Loop Backoff** | The actor failed to allocate and is waiting to retry with a backoff. This typically means repeated allocation failures. The backoff prevents overloading your infrastructure in the case of a widespread misconfiguration in your backend. See [Troubleshooting](/docs/actors/troubleshooting#actor-status-is-crashed) for common failure reasons. | + +## API Representation + +The actor object returned by the full engine API (used by the dashboard) includes the following timestamp fields used to derive status: + +| Field | Description | +|---|---| +| `createTs` | When the actor was first created. Always present. | +| `connectableTs` | When the actor became connectable. Null if not yet running. | +| `destroyTs` | When the actor was destroyed. | +| `sleepTs` | When the actor entered a sleeping state. | +| `pendingAllocationTs` | When the actor started waiting for an allocation. | +| `rescheduleTs` | When the actor will retry allocation after a failure. | +| `error` | Error details if the actor failed. | + +_Source doc path: /docs/actors/statuses_ diff --git a/.agents/skills/ai-agent/reference/actors/testing.md b/.agents/skills/ai-agent/reference/actors/testing.md new file mode 100644 index 0000000..5afe658 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/testing.md @@ -0,0 +1,51 @@ +# Testing + +> Source: `src/content/docs/actors/testing.mdx` +> Canonical URL: https://rivet.dev/docs/actors/testing +> Description: Rivet provides a straightforward testing framework to build reliable and maintainable applications. This guide covers how to write effective tests for your actor-based services. + +--- +## Setup + +To set up testing with Rivet: + +```bash +# Install Vitest +npm install -D vitest + +# Run tests +npm test +``` + +## Basic Testing Setup + +Rivet includes a test helper called `setupTest` that starts your registry in test mode and returns a client connected to it. This allows for fast, isolated tests without external dependencies. + +## Testing Actor State + +State persists within each test, allowing you to verify that your actor correctly maintains state between operations. + +## Testing Events + +For actors that emit events, you can verify events are correctly triggered by subscribing to them: + +## Testing Schedules + +Rivet's schedule functionality can be tested by scheduling work and waiting for it to run: + +Use a short real-time delay to wait for scheduled work to run. `setupTest` does not install fake timers, so if you want to use `vi.useFakeTimers()` you must enable it yourself and confirm it works with your selected runtime. + +## Best Practices + +1. **Isolate tests**: Each test should run independently, avoiding shared state. +2. **Test edge cases**: Verify how your actor handles invalid inputs, concurrent operations, and error conditions. +3. **Test scheduled operations**: Use short real-time delays to wait for scheduled work to run. +4. **Use realistic data**: Test with data that resembles production scenarios. + +`setupTest` starts the registry and disposes the returned client when the test finishes, so you can focus on writing effective tests for your business logic. + +## API Reference + +- [`setupTest`](/typedoc/functions/rivetkit.test_mod.setupTest.html) - Test setup helper function + +_Source doc path: /docs/actors/testing_ diff --git a/.agents/skills/ai-agent/reference/actors/troubleshooting.md b/.agents/skills/ai-agent/reference/actors/troubleshooting.md new file mode 100644 index 0000000..65b234d --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/troubleshooting.md @@ -0,0 +1,154 @@ +# Troubleshooting + +> Source: `src/content/docs/actors/troubleshooting.mdx` +> Canonical URL: https://rivet.dev/docs/actors/troubleshooting +> Description: Common issues with Rivet Actors and how to resolve them. + +--- +## Common Steps + +Before diving into specific errors, try these general troubleshooting steps: + +- Check your server logs for `level=ERROR` or `level=WARN` messages. +- Check if any of your backend processes have crashed or restarted unexpectedly. +- If you need more diagnostics, set `RIVET_LOG_LEVEL=DEBUG` for verbose logging. See [Logging](/docs/general/logging) for more options. + +## Reporting Issues + +If you're stuck, reach out on [Discord](https://rivet.dev/discord) or file an issue on [GitHub](https://github.com/rivet-dev/rivet/issues). + +When reporting, please include: + +- **Symptoms** + - Whether this is happening in local dev, deployed, or both + - The error you're seeing (screenshot or error message) + - Relevant source code related to the issue +- **What you've tried to solve it** +- **Environment** + - RivetKit version + - Runtime (Node, Bun, etc.) including version + - If applicable, provider in use (e.g. Vercel, Railway, Cloudflare) + - If applicable, HTTP router in use (e.g. Hono, Express, Elysia) + +## Actor status is crashed + +See [Actor Statuses](/docs/actors/statuses) for more about this status. + +The dashboard will show the specific failure reason. Common errors include: + +### `crashed` + +The actor's `run` handler threw an unhandled exception or exited unexpectedly. Check your actor logs for the error message and stack trace. + +### `no_capacity` + +No server was available to run your actor. The cause depends on your [runtime mode](/docs/general/runtime-modes): + +**Serverless**: + +- Your provider configuration does not have the region enabled that the actor is trying to run in. This is uncommon and usually only happens if an actor was created and then the provider config was updated to remove the region. +- There is an issue connecting to your backend. If the engine is hitting `/api/rivet/start` and failing, check your backend logs for errors. + +**Runners**: + +- You don't have enough runners online. Check your runner list in the dashboard to verify runners are visible and connected. +- Your runners are full. Each runner has a limited number of actor slots (configured via `RIVET_TOTAL_SLOTS`, default: 100,000). Check the dashboard to see if your runners have available capacity and scale up if needed. + +### `runner_no_response` + +The server running your actor did not respond in time. This can happen if your server is overloaded or experienced a network issue. Try restarting your server or checking its health. + +### `runner_connection_lost` + +The server running your actor lost its connection to Rivet. This is usually caused by a network interruption or your server restarting. + +### `runner_draining_timeout` + +Your server is shutting down and the actor did not finish in time. Consider handling graceful shutdown in your actor or increasing your shutdown timeout. + +### `concurrent_actor_limit_reached` + +The actor could not be allocated because the concurrent actor limit was reached. Reduce the number of concurrently running actors or increase your limit. + +### `no_envoys` + +No server was available to run your actor. This is equivalent to `no_capacity` on the current allocation path. See the `no_capacity` section above for the causes and fixes for your [runtime mode](/docs/general/runtime-modes). + +### `envoy_no_response` + +The server running your actor did not respond in time. This can happen if your server is overloaded or experienced a network issue. Try restarting your server or checking its health. + +### `envoy_connection_lost` + +The server running your actor lost its connection to Rivet. This is usually caused by a network interruption or your server restarting. + +### `serverless_http_error` + +Your serverless endpoint returned an HTTP error. Common causes: + +- Your backend is returning an error before the actor can start. Check your server logs. +- Your endpoint is behind authentication or a firewall that is blocking Rivet's requests. +- Your serverless function crashed during startup. Check your platform's function logs (e.g. Vercel, Cloudflare). + +### `serverless_connection_error` + +Rivet was unable to connect to your serverless endpoint. Check that: + +- Your backend is deployed and the endpoint URL is correct. +- Your server is publicly reachable from the internet. +- There are no DNS or firewall issues blocking the connection. + +### `serverless_stream_ended_early` + +The connection to your serverless endpoint was terminated before the actor finished. This usually means your serverless function hit its execution time limit. Ensure that your Rivet provider's request lifespan is configured to match the max duration of your serverless platform. + +### `serverless_invalid_sse_payload` + +Rivet received an unexpected response from your serverless endpoint. This typically means something is intercepting or modifying the request before it reaches your RivetKit handler. Check that: + +- Your server routes requests to `registry.start()`, `registry.serve()`, or `registry.handler()` correctly. +- No middleware is modifying the request or response body. + +### `internal_error` + +An unexpected error occurred within Rivet. If this persists, please [contact support](https://rivet.dev/docs). + +## Actors crashing immediately on startup + +If your actors are being created and then immediately destroyed or crashing, there is likely an error being thrown in your `createState` or `onCreate` lifecycle hooks. These hooks run during actor initialization before the actor is marked as ready. + +Check your server logs for the error message and stack trace. Common causes include: + +- An exception thrown in `createState` (e.g. invalid input, failed validation, or a runtime error when computing initial state) +- An exception thrown in `onCreate` (e.g. a failing external API call, missing configuration, or invalid setup logic) + +Fix the error in the relevant lifecycle hook and redeploy. + +## Actors not upgrading to new code + +If your actors are still running old code after deploying a new version, your [versioning](/docs/actors/versions) is likely not configured correctly. + +Without versioning, Rivet has no way to distinguish old deployments from new ones. The behavior depends on your [runtime mode](/docs/general/runtime-modes): + +- **Serverless**: Old requests may still be open from the previous deployment, so actors continue running on the old version's connection until those requests close. +- **Runners**: The old runner container is still running and will continue accepting new actors. New actors may be scheduled on the old runner instead of the new one. + +To fix this, configure a version number in your [registry configuration](/docs/general/registry-configuration). When a new version is deployed, Rivet will allocate new actors to the latest version and optionally drain old actors to migrate them. + +## Actor status is pending + +See [Actor Statuses](/docs/actors/statuses) for more about this status. + +An actor stays in "pending" status when Rivet is waiting for a server to accept it. The cause depends on your [runtime mode](/docs/general/runtime-modes): + +**Serverless**: + +- A region may have been removed from your provider configuration while an existing actor still lives in that region. The actor has no available server to start on because no provider serves that region anymore. Re-add the region to your provider config or destroy the affected actors. +- Check your backend logs for errors on the `/api/rivet/start` endpoint. + +**Runners**: + +- You don't have enough runners online. Check the dashboard to verify your runners are connected. +- Your runners may be at capacity. Check the dashboard to see if runners have available actor slots and scale up if needed. + +_Source doc path: /docs/actors/troubleshooting_ diff --git a/.agents/skills/ai-agent/reference/actors/types.md b/.agents/skills/ai-agent/reference/actors/types.md new file mode 100644 index 0000000..3e8f9b0 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/types.md @@ -0,0 +1,46 @@ +# Types + +> Source: `src/content/docs/actors/types.mdx` +> Canonical URL: https://rivet.dev/docs/actors/types +> Description: TypeScript types for working with Rivet Actors. This page covers context types used in lifecycle hooks and actions, as well as helper types for extracting types from actor definitions. + +--- +## Context Types + +Context types define what properties and methods are available in different parts of the actor lifecycle. + +### Extracting Context Types + +When writing helper functions that work with actor contexts, use context extractor types like `CreateContextOf` or `ActionContextOf` to extract the appropriate context type from your actor definition. + +### All Context Types + +Each lifecycle hook and handler has a corresponding `*ContextOf` type, exported from `"rivetkit"`. Pass `typeof myActor` as the type parameter. + +| Hook / Handler | Context Type | +|---|---| +| `createState` | `CreateContextOf` | +| `onCreate` | `CreateContextOf` | +| `createVars` | `CreateVarsContextOf` | +| `createConnState` | `CreateConnStateContextOf` | +| `onBeforeConnect` | `BeforeConnectContextOf` | +| `onConnect` | `ConnectContextOf` | +| `onDisconnect` | `DisconnectContextOf` | +| `onDestroy` | `DestroyContextOf` | +| `onMigrate` | `MigrateContextOf` | +| `onWake` | `WakeContextOf` | +| `onSleep` | `SleepContextOf` | +| `onStateChange` | `StateChangeContextOf` | +| `onBeforeActionResponse` | `BeforeActionResponseContextOf` | +| `actions.*` | `ActionContextOf` | +| `run` | `RunContextOf` | +| `workflow` orchestration helpers (root, `loop`, `try`, `race`, `join` branches) | `WorkflowContextOf` | +| `workflow` `step` / `tryStep` run + rollback helpers | `WorkflowStepContextOf` | +| `onRequest` | `RequestContextOf` | +| `onWebSocket` | `WebSocketContextOf` | + +`ActorContextOf`, `ConnContextOf`, and `ConnInitContextOf` are general-purpose base context types useful for helper functions that don't correspond to a specific hook. + +Workflow context extractors are exported from both `"rivetkit"` and `"rivetkit/workflow"`. + +_Source doc path: /docs/actors/types_ diff --git a/.agents/skills/ai-agent/reference/actors/versions.md b/.agents/skills/ai-agent/reference/actors/versions.md new file mode 100644 index 0000000..1b45129 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/versions.md @@ -0,0 +1,241 @@ +# Versions & Upgrades + +> Source: `src/content/docs/actors/versions.mdx` +> Canonical URL: https://rivet.dev/docs/actors/versions +> Description: When you deploy new code, Rivet ensures actors are upgraded seamlessly without downtime. + +--- +## How Versions Work + +Each runner has a **version number**. When you deploy new code with a new version, Rivet handles the transition automatically: + +- **New actors go to the newest version**: When allocating actors, Rivet always prefers runners with the highest version number +- **Multiple versions can coexist**: Old actors continue running on old versions while new actors are created on the new version +- **Drain old actors**: When enabled, a runner connecting with a newer version number will gracefully stop old actors to be rescheduled to the new version + +Versions are not configured by default. See [Registry Configuration](/docs/general/registry-configuration) to learn how to configure the runner version. + +`RIVET_ENVOY_VERSION` is only needed when self-hosting or using a custom runner. Rivet Compute handles versioning automatically. + +### Example Scenario + +### Drain Enabled + +When a new version is deployed, existing actors are gracefully stopped on the old runner and rescheduled onto the new version. + +```mermaid +sequenceDiagram + participant R1 as Runner v1 + participant R2 as Runner v2 + + Note over R1: Currently running + Note over R2: Deployed + R2->>R1: Drain old actors + R1->>R2: Reschedule actors + Note over R1: Shut down when all actors stopped +``` + +### Drain Disabled + +When a new version is deployed, both versions coexist. New actors are created on the new version while existing actors continue running on the old version until. + +```mermaid +sequenceDiagram + participant R1 as Runner v1 + participant R2 as Runner v2 + + Note over R1: Currently running + Note over R2: Deployed + Note over R1: Actor 1 sleeps from inactivity + Note over R2: Actor 1 wakes up when prompted +``` + +## Configuration + +### Setting the Version + +Configure the runner version using an environment variable or programmatically: + +```bash {{"title": "Environment Variable"}} +RIVET_ENVOY_VERSION=2 +``` + +The version **must** be set at build time, not at runtime. Do not use `Date.now()` or similar runtime values in your registry setup code. This would assign a different version every time the server starts, causing actors to be drained and rescheduled on every restart instead of only on new deployments. + +### Example Configurations + +We recommend injecting a build-time value that increments with every deployment. Here are concrete examples for common setups: + +### Dockerfile + +Generate the version at build time and bake it into the image as an environment variable: + +```bash @nocheck +docker build --build-arg RIVET_ENVOY_VERSION=$(date +%s) . +``` + +```dockerfile @nocheck +FROM node:20-slim +ARG RIVET_ENVOY_VERSION +ENV RIVET_ENVOY_VERSION=$RIVET_ENVOY_VERSION +WORKDIR /app +COPY . . +RUN npm install && npm run build +CMD ["node", "dist/server.js"] +``` + +All containers from this image will share the same version. + +### Next.js + +Set the version in `next.config.ts`. Next.js evaluates this file once at build time and inlines the value into the bundle: + +```typescript @nocheck +import type { NextConfig } from "next"; + +const nextConfig: NextConfig = { + env: { + RIVET_ENVOY_VERSION: String(Math.floor(Date.now() / 1000)), + }, +}; + +export default nextConfig; +``` + +### Vite + +Use `define` in your Vite config. This is evaluated once at build time and inlined into the bundle: + +```typescript @nocheck +import { defineConfig } from "vite"; + +export default defineConfig({ + define: { + "process.env.RIVET_ENVOY_VERSION": JSON.stringify( + String(Math.floor(Date.now() / 1000)) + ), + }, +}); +``` + +### CI/CD + +Set the version from your CI pipeline: + +```yaml @nocheck +# GitHub Actions +env: + RIVET_ENVOY_VERSION: ${{ github.run_number }} +``` + +```bash @nocheck +# Railway / Render / generic CI +export RIVET_ENVOY_VERSION=$(date +%s) +``` + +```bash @nocheck +# Git commit count +export RIVET_ENVOY_VERSION=$(git rev-list --count HEAD) +``` + +### Build Script + +Generate a version file during your build step and import it: + +```json @nocheck +{ + "scripts": { + "build": "echo \"export const BUILD_VERSION = $(date +%s);\" > src/build-version.ts && tsc" + } +} +``` + +```typescript @nocheck +import { actor, setup } from "rivetkit"; +import { BUILD_VERSION } from "./build-version"; + +const myActor = actor({ state: {}, actions: {} }); + +const registry = setup({ + use: { myActor }, + envoy: { + version: BUILD_VERSION, + }, +}); +``` + +### Drain on Version Upgrade + +The `drainOnVersionUpgrade` option controls whether old actors are stopped when a new version is deployed. This is configured in the Rivet dashboard under your runner configuration. See [Pool Configuration](/docs/general/pool-configuration) for the full set of pool options, including how to rate-limit actor eviction during the drain. + +| Value | Behavior | +|-------|----------| +| `false` | Old actors continue running. New actors go to new version. Versions coexist. | +| `true` (default) | Old actors receive stop signal and have 30m to finish gracefully. | + +## Upgrading Actor State + +When you deploy a new version, existing actors may need to handle schema changes in their persisted data. + +### SQLite (recommended for complex schemas) + +**Drizzle (recommended)** + +Use [Drizzle](/docs/actors/sqlite-drizzle) for typed schemas with generated migrations. Drizzle generates versioned `.sql` migration files from your TypeScript schema and applies them in order automatically. This is the recommended approach when your schema evolves frequently. + +**Raw SQL** + +For actors using [raw SQLite](/docs/actors/sqlite), migrations run automatically via the `onMigrate` hook on every actor start. RivetKit wraps the hook in a SQLite savepoint, so the migration is fully atomic. Use SQLite's `user_version` pragma to track which migrations have run: + +### In-memory state (`c.state`) + +If you use `c.state` for persistence, you are responsible for handling schema changes yourself. If you add, remove, or rename fields between versions, your code must handle the old shape gracefully. + +**Manual defaults in `onWake`** + +Apply defaults for missing fields: + +**Zod schema coercion** + +Use [Zod](https://zod.dev/) to parse persisted state on wake. Zod's `.default()` fills in missing fields automatically, so old actor state is coerced to the current schema: + +For anything beyond simple defaults, consider moving to [SQLite](/docs/actors/sqlite) where you get proper migration tooling. + +## Advanced + +### How Version Upgrade Detection Works + +When `drainOnVersionUpgrade` is enabled, Rivet uses two mechanisms to detect version changes: + +- **New runner connection**: When a runner connects with a newer version number, the engine immediately drains all older runners with the same name. This is the primary mechanism for [runner mode](/docs/general/runtime-modes) deployments. +- **Metadata polling** (serverless only): In [serverless mode](/docs/general/runtime-modes), runners periodically poll the engine to check for newer versions and self-drain if one is found. This ensures old runners drain even if no new requests trigger a runner connection. + +### SIGTERM Handling + +When a runner process receives SIGTERM, it gracefully stops all actors before exiting: + +- Each actor's `onSleep` hook is called, giving it time to save state +- Actors are rescheduled to other available runners +- The runner waits up to **30 minutes** for all actors to finish stopping +- If the process is force-killed before actors finish (e.g. SIGKILL), actors are rescheduled with a crash backoff penalty instead of a clean handoff + +Actors have a maximum of 30 minutes to clean up during shutdown. Ensure your platform's drain grace period is at most 30 minutes. + +### Shutdown Timeouts + +Several timeouts control how long each part of the shutdown process can take: + +| Timeout | Default | Description | Configuration | +|---------|---------|-------------|---------------| +| `actor_stop_threshold` | 30m | Engine-side limit on how long each actor has to stop before being marked lost | [Engine config](/docs/self-hosting/configuration) (`pegboard.actor_stop_threshold`) | +| `sleepGracePeriod` | 15s | Total graceful sleep budget for `onSleep`, `waitUntil`, `keepAwake`, and async raw WebSocket handlers | [Actor options](/docs/actors/lifecycle#options) | +| `runner_lost_threshold` | 15s | Fallback detection if the runner dies without graceful shutdown | [Engine config](/docs/self-hosting/configuration) (`pegboard.runner_lost_threshold`) | + +Rivet has a max shutdown grace period of 30 minutes that cannot be configured. + +## Related + +- [Runtime Modes](/docs/general/runtime-modes): Serverless vs runner deployment modes +- [Lifecycle](/docs/actors/lifecycle): Actor lifecycle hooks including `onSleep` + +_Source doc path: /docs/actors/versions_ diff --git a/.agents/skills/ai-agent/reference/actors/websocket-handler.md b/.agents/skills/ai-agent/reference/actors/websocket-handler.md new file mode 100644 index 0000000..f94499d --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/websocket-handler.md @@ -0,0 +1,201 @@ +# Low-Level WebSocket Handler + +> Source: `src/content/docs/actors/websocket-handler.mdx` +> Canonical URL: https://rivet.dev/docs/actors/websocket-handler +> Description: Actors can handle WebSocket connections through the `onWebSocket` handler. + +--- +For most use cases, [actions](/docs/actors/actions) and [events](/docs/actors/events) provide high-level connection handling powered by WebSockets that's easier to work with than low-level WebSockets. However, low-level handlers are required when implementing custom use cases. + +## Handling WebSocket Connections + +The `onWebSocket` handler manages low-level WebSocket connections. It receives the actor context and a `WebSocket` object. + +See also the [raw WebSocket handler example](https://github.com/rivet-dev/rivet/tree/main/examples/raw-websocket-handler). + +## Connecting To Actors + +### Via RivetKit Client + +Use the `.webSocket()` method on an actor handle to open a WebSocket connection to the actor's `onWebSocket` handler. This can be executed from either your frontend or backend. + +```typescript index.ts @hide @nocheck +import { actor, setup } from "rivetkit"; + +export const chat = actor({ + state: { messages: [] as string[] }, + onWebSocket: (c, websocket) => { + websocket.addEventListener("message", (event) => { + c.state.messages.push(event.data as string); + }); + }, + actions: {} +}); + +export const registry = setup({ use: { chat } }); +registry.start(); +``` + +```typescript client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +const actor = client.chat.getOrCreate(["my-chat"]); + +// Open WebSocket connection +const ws = await actor.webSocket("/"); + +// Listen for messages +ws.addEventListener("message", (event) => { + const message = JSON.parse(event.data as string); + console.log("Received:", message); +}); + +// Send messages +ws.send(JSON.stringify({ type: "chat", text: "Hello!" })); +``` + +The `.webSocket()` method returns a standard WebSocket. + +### Via getGatewayUrl + +Use `.getGatewayUrl()` to get the raw gateway URL for the actor. This is useful when you need to use the URL with external tools or custom WebSocket clients. + +```typescript index.ts @hide @nocheck +import { actor, setup } from "rivetkit"; + +export const chat = actor({ + state: { messages: [] as string[] }, + onWebSocket: (c, websocket) => { + websocket.addEventListener("message", (event) => { + c.state.messages.push(event.data as string); + }); + }, + actions: {} +}); + +export const registry = setup({ use: { chat } }); +registry.start(); +``` + +```typescript client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +const actor = client.chat.getOrCreate(["my-chat"]); + +// Get the raw gateway URL +const gatewayUrl = await actor.getGatewayUrl(); +// gatewayUrl = "https://...rivet.dev/..." + +// Convert to WebSocket URL and connect +const wsUrl = gatewayUrl.replace("http://", "ws://").replace("https://", "wss://"); +const ws = new WebSocket(`${wsUrl}/websocket/`); + +ws.addEventListener("message", (event) => { + const message = JSON.parse(event.data as string); + console.log("Received:", message); +}); + +ws.addEventListener("open", () => { + ws.send(JSON.stringify({ type: "chat", text: "Hello!" })); +}); +``` + +### Via HTTP API + +This handler can be accessed with raw WebSockets using `wss://api.rivet.dev/gateway/{actorId}@{token}/websocket/{...path}`. + +For example, to connect to the chat actor above: + +```typescript +// Replace with your actor ID and token +const actorId = "your-actor-id"; +const token = "your-token"; + +const ws = new WebSocket( + `wss://api.rivet.dev/gateway/${actorId}@${token}/websocket/` +); + +ws.addEventListener("message", (event) => { + const message = JSON.parse(event.data as string); + console.log("Received:", message); +}); + +ws.addEventListener("open", () => { + ws.send(JSON.stringify({ type: "chat", text: "Hello!" })); +}); +``` + +```bash +wscat -c "wss://api.rivet.dev/gateway/{actorId}@{token}/websocket/" +``` + +The path after `/websocket/` is passed to your `onWebSocket` handler and can be used to route to different functionality within your actor. For example, to connect with a custom path `/admin`: + +```typescript +// Replace with your actor ID and token +const actorId = "your-actor-id"; +const token = "your-token"; + +const ws = new WebSocket( + `wss://api.rivet.dev/gateway/${actorId}@${token}/websocket/admin` +); +``` + +```bash +wscat -c "wss://api.rivet.dev/gateway/{actorId}@{token}/websocket/admin" +``` + +See the [HTTP API reference](/docs/actors/http-api) for more information on WebSocket routing and authentication. + +### Via Proxying Connections + +You can proxy WebSocket connections from your own server to actor handlers using the RivetKit client. This is useful when you need to add custom authentication or connection management before forwarding to actors. + +See also the [raw WebSocket handler with proxy example](https://github.com/rivet-dev/rivet/tree/main/examples/raw-websocket-handler-proxy). + +## Connection & Lifecycle Hooks + +`onWebSocket` will trigger the `onBeforeConnect`, `onConnect`, and `onDisconnect` hooks. Read more about [lifecycle hooks](/docs/actors/lifecycle). + +Open WebSockets will be listed in `c.conns`. `conn.send` and `c.broadcast` have no effect on low-level WebSocket connections. Read more about [connections](/docs/actors/connections). + +## WinterTC Compliance + +The `onWebSocket` handler uses standard WebSocket APIs and will work with existing libraries expecting WinterTC-compliant WebSocket objects. + +## Advanced + +## WebSocket Hibernation + +WebSocket hibernation allows actors to go to sleep while keeping WebSocket connections alive. Actors automatically wake up when a message is received or the connection closes. + +Enable hibernation by setting `canHibernateWebSocket: true`. You can also pass a function `(request) => boolean` for conditional control. + +Since `open` only fires once when the client first connects, use `c.conn.state` to store per-connection data that persists across sleep cycles. See [connections](/docs/actors/connections) for more details. + +### Accessing the Request + +The underlying HTTP request is available via `c.request`. This is useful for accessing the path or query parameters. + +### Skip Ready Wait + +Connections are normally held at the gateway until the actor is ready. Pass `skipReadyWait: true` on `handle.webSocket()` to connect immediately, including while the actor is still starting or in the [sleep grace period](/docs/actors/lifecycle#shutdown-sequence). See [Skip Ready Wait](/docs/clients/javascript#skip-ready-wait) for details. + +### Async Handlers + +The `onWebSocket` handler can be async, allowing you to perform async code before setting up event listeners: + +## API Reference + +- [`WebSocketContext`](/typedoc/interfaces/rivetkit.mod.WebSocketContext.html) - Context for WebSocket handlers +- [`UniversalWebSocket`](/typedoc/interfaces/rivetkit.mod.UniversalWebSocket.html) - Universal WebSocket interface +- [`handleRawWebSocketHandler`](/typedoc/functions/rivetkit.mod.handleRawWebSocketHandler.html) - Function to handle raw WebSocket +- [`UpgradeWebSocketArgs`](/typedoc/interfaces/rivetkit.mod.UpgradeWebSocketArgs.html) - Arguments for WebSocket upgrade + +_Source doc path: /docs/actors/websocket-handler_ diff --git a/.agents/skills/ai-agent/reference/actors/workflows.md b/.agents/skills/ai-agent/reference/actors/workflows.md new file mode 100644 index 0000000..9c59975 --- /dev/null +++ b/.agents/skills/ai-agent/reference/actors/workflows.md @@ -0,0 +1,228 @@ +# Workflows + +> Source: `src/content/docs/actors/workflows.mdx` +> Canonical URL: https://rivet.dev/docs/actors/workflows +> Description: Build durable, replayable run loops in Rivet Actors with steps, queue waits, timers, and rollback. + +--- +Use workflows for durable, multi-step execution with replay safety. + +## What are workflows? + +A workflow is a durable, replayable run handler for a Rivet Actor. + +- Survives restarts: workflow progress is saved automatically. +- Re-runs safely: replay follows the same recorded steps. +- Event-driven: workflows can pause for queue messages, then continue. + +## Getting started + +### Simple workflow + +Use this when you need a short multi-step sequence. + +### Loops + +This is the recommended workflow shape for most actor workloads. + +- Use a queue wait inside the loop to receive the next unit of work. +- Keep actor state changes in a single workflow loop. +- This gives you one durable workflow that manages all actor progress. + +### Setup & teardown + +Use this when the workflow should initialize resources, process queued commands, then clean up. + +## Features + +### Queue + +Use this for fire-and-forget commands where the client does not need a reply. + +Use the `Loops` example above as the baseline pattern. + +### Request/response (using queue) + +Use this when the caller needs a response from queued processing. + +### Timers + +Use queue messages as the trigger source, then sleep durably inside the workflow. + +### Join + +Use `join` when several independent tasks can run in parallel. + +### Race + +Use `race` when you need first-winner behavior. + +### Timeouts + +Use step timeouts and retries for slow or flaky dependencies. + +Step timeouts are critical by default and fail immediately. Set `retryOnTimeout: true` if a timeout should retry like any other error using `maxRetries`. + +Workflows use roll-forward semantics everywhere. When a step throws, any `state` or `vars` mutations it made before failing are never rolled back, whether the step retries or the failure is caught by `tryStep` or `try`. The next attempt observes whatever the failed attempt already wrote, so write steps idempotently: check before you increment, or move the mutation after the fallible work. + +### Handling terminal failures as data + +Use `tryStep` when a step failure should produce data instead of failing the whole workflow. + +Use `try` when you want to recover from terminal `step`, `join`, or `race` failures inside a named block. + +```ts +async function runPaymentFlow(ctx: any) { + return await ctx.try("payment-flow", async (blockCtx: any) => { + const auth = await blockCtx.step("authorize", async (blockCtx) => + authorizeOrder("order-123"), + ); + const capture = await blockCtx.step("capture", async (blockCtx) => + captureOrder("order-123"), + ); + return { auth, capture }; + }); +} + +async function authorizeOrder(orderId: string): Promise { + return `auth-${orderId}`; +} + +async function captureOrder(orderId: string): Promise { + return `capture-${orderId}`; +} +``` + +- `tryStep` and `try` only catch terminal failures. Retry backoff, sleeps, queue waits, eviction, and history divergence still rethrow. +- Catching a failure does not undo it. `state` and `vars` mutations made before the failure remain visible after `tryStep` or `try` returns, so use explicit compensating steps when a caught failure needs cleanup. +- `RollbackError` is not caught by default. Pass `catch: ["rollback"]` when you want rollback failures returned as data. + +### Error hooks + +Use `onError` when you want a best-effort notification for workflow failures. + +- Step failures include the attempt number, retry counts, whether the step will retry, and the next retry delay. +- Workflow failures also include terminal errors outside steps, such as rollback failures or code/history mismatches. +- The hook is observational. It is not part of workflow replay, so use it for logging, metrics, or updating non-critical actor state. +- This is also a good place to forward workflow failures to Sentry or another error reporting pipeline. + +### Rollback + +Use rollback checkpoints before steps that have compensating actions. + +## Patterns + +### Store workflow progress in state + broadcast + +Store progress in `state` so replay and recovery always restore it. Broadcast state changes so clients can render progress in realtime. + +### Cron (queue-driven) + +Rivet scheduling triggers actions. For cron-like workflows, use a small scheduled action as a bridge that enqueues work, then process that work in the workflow loop. + +These are common workflow shapes used in production systems. + +### Queue-driven worker + +Use this when external systems enqueue work and the actor should process each item durably. + +### Setup & teardown + +Use this when you need one-time initialization before a long-lived loop, plus cleanup when the actor stops sleeping or is destroyed. + +### Human approval gate + +Use this when an operation must pause for a user or system decision before continuing. + +### Fan-out / fan-in (join) + +Use this when independent work items can run in parallel and you need a single merged result. + +### Batch drainer + +Use this when throughput matters and handling one message at a time is too expensive. + +### Coordinator -> worker RPC + +Use this when one actor orchestrates work by calling actions on other actors. + +### Request/response over queue (async RPC) + +Use this when you want decoupled actor-to-actor communication with durable waits and explicit completion. + +### Scatter-gather across actors + +Use this when multiple actors can process independent parts of a request in parallel, then return a merged response. + +### Timeout + fallback actor + +Use this when a primary actor call might be slow or unavailable and you need a deterministic fallback path. + +### Cross-actor saga (compensating actions) + +Use this when a workflow spans multiple actors and each side effect may need compensation. + +### Signal-driven control loop + +Use this when workflow progress should be triggered by commands/events instead of fixed polling intervals. + +### Poll + backoff loop + +Use this when an external dependency has variable availability and retries should slow down after failures. + +### Child worker orchestration + +Use this when one workflow coordinates many child workers (actors or worker workflows) and manages their lifecycle. + +### Bounded drain + concurrency cap + +Use this when inbound work can spike and you need predictable per-iteration limits. + +### Versioned workflow evolution + +Use this when workflow structure changes across deployments and old histories must still replay. + +### Version gates with `getVersion` + +Use `ctx.getVersion(name, latest)` to branch behavior when you change a workflow's logic while old instances are still in flight. It returns the version this instance is pinned to at that point: + +- A fresh instance resolves to `latest`. +- An instance that already executed past this point under older code resolves to `1` (the implicit floor). + +The resolved version is recorded in history, so replays are deterministic and each instance stays on the branch it started on. Inside a loop, every iteration resolves independently, so in-flight iterations finish on the old branch while new iterations pick up `latest`. + +`latest` must be an integer `>= 1`, and the gate name must be unique within its scope like any other entry. Once every old instance has drained, retire the gate by replacing the call with `ctx.removed(name, "version_check")`. + +### Checkpoint-friendly loop design + +Use this when you need reliable replay and resume semantics across crashes and restarts. + +## Migrations + +- Keep workflow entry names stable once deployed. +- If an old entry was removed or renamed, call `ctx.removed(name, originalType)`. +- To change behavior at a point while old instances are still running, gate it with `ctx.getVersion(name, latest)` (see [Version gates](#version-gates-with-getversion)). +- This keeps replay compatible across deployments. + +## Step-only access to actor APIs + +`state`, `vars`, `db`, `client()`, and connection/event APIs are only valid inside `ctx.step(...)` callbacks. + +Use non-step workflow code for orchestration only: queue waits, sleeps, loops, joins, races, and rollback boundaries. Keep actor-local side effects in steps. + +## Debugging + +- `GET /inspector/workflow-history` returns workflow history status for an actor. +- Response includes `isWorkflowEnabled` and `history`. +- In non-dev mode, inspector endpoints require authorization. + +## Recommendations + +- Prefer queue-driven loops for long-lived workflows. +- Structure long-lived workflows with setup and teardown around the main loop. +- Keep actor state changes and side effects inside steps. +- Store workflow progress in `state` and broadcast updates as progress changes. +- Use timeouts and rollback for external side effects. +- Write step bodies idempotently. `state` and `vars` mutations from a failed attempt are never rolled back, whether the step retries or `tryStep`/`try` catches the failure. + +_Source doc path: /docs/actors/workflows_ diff --git a/.agents/skills/ai-agent/reference/cli.md b/.agents/skills/ai-agent/reference/cli.md new file mode 100644 index 0000000..34880ea --- /dev/null +++ b/.agents/skills/ai-agent/reference/cli.md @@ -0,0 +1,103 @@ +# CLI + +> Source: `src/content/docs/cli.mdx` +> Canonical URL: https://rivet.dev/docs/cli +> Description: Reference for the optional rivet CLI: deploy to Rivet Compute and run local dev for serverless platforms. + +--- +The `rivet` CLI (`@rivetkit/cli`) is optional. You only need it for: + +| Use case | Command | +| --- | --- | +| Deploy to Rivet Compute | `rivet deploy` | +| Local dev for serverless platforms (Cloudflare, Supabase) | `rivet dev --provider ` | + +Run it with your package runner: + +```bash +npx @rivetkit/cli +``` + +| Command | Description | +| --- | --- | +| `rivet dev` | Run a local engine and your handler's dev server. | +| `rivet deploy` | Build and deploy the project to Rivet Cloud. | +| `rivet engine` | Run the bundled `rivet-engine` binary directly. | +| `rivet setup-ci` | Install the GitHub Actions deploy workflow. | + +## `rivet dev` + +Starts a local engine, spawns your dev server, and registers the serverless runner pointing at it. The engine keeps running across restarts; Ctrl-C stops only the dev server. + +```bash +rivet dev [--provider ] [--port N] [--fn-name NAME] [--url URL] [-- ...] +``` + +`--provider` selects how the dev server is launched. Anything after `--` is appended to the preset command (or is the command to run when no provider is set). + +| `--provider` | Spawns | Port | +| --- | --- | --- | +| _(omitted)_ | your `-- ` (needs `--port`) | from `--port` | +| `serverless` | your `-- ` (gets `PORT`) | auto | +| `cloudflare` | `wrangler dev` | `8787` | +| `supabase` | `supabase functions serve` | `54321` | +| `none` | nothing (engine only) | — | + +For `cloudflare`, the CLI also passes the engine endpoint as `--var RIVET_ENDPOINT:...`, so the Worker connects back with no `wrangler.toml` config. + +| Flag | Description | +| --- | --- | +| `--port` | Handler port. Required without a provider unless `--url` is set. | +| `--fn-name` | Supabase function name (default `rivet`). | +| `--url` | Explicit handler URL, overriding port and path. | +| `--engine-binary` | Path to a `rivet-engine` binary. | + +## `rivet deploy` + +Builds and pushes your project's Docker image and upserts the managed pool, printing the dashboard URL. See [Deploying to Rivet Compute](/docs/deploy/rivet-compute). + +```bash +rivet deploy --token cloud_api_xxxxx +``` + +The token is saved to `~/.rivet/credentials` (also read from `RIVET_CLOUD_TOKEN`), so later deploys can omit it. + +| Flag | Default | Description | +| --- | --- | --- | +| `--token` | env / credentials | Rivet Cloud API token. | +| `--namespace` | `production` | Cloud namespace. | +| `--project` / `--org` | from token | Override project/org. | +| `--dockerfile` | `Dockerfile` | Dockerfile to build. | +| `--build-context` | `.` | Docker build context. | +| `--env KEY=VAL` | — | Environment override, repeatable. | +| `--image` | project slug | Image repository name. | +| `--tag` | git short SHA | Image tag. | + +## `rivet engine` + +Runs the bundled `rivet-engine` binary directly, against the same local database and ports as `rivet dev`. Arguments are forwarded verbatim. + +```bash +rivet engine nuke # wipe local engine state +rivet engine wf list # inspect workflows +``` + +## `rivet setup-ci` + +Installs `.github/workflows/rivet-deploy.yml`, which deploys to Rivet Cloud on push and pull request. Add `--force` to overwrite. Then set the token secret: + +```bash +gh secret set RIVET_CLOUD_TOKEN +``` + +## Engine binary resolution + +`rivet dev` and `rivet engine` resolve the `rivet-engine` binary from, in order: `--engine-binary`, `RIVET_ENGINE_BINARY_PATH`, a binary bundled next to the CLI, a local `target/{debug,release}` build, then an auto-downloaded release. Set `RIVETKIT_ENGINE_AUTO_DOWNLOAD=0` to require a local binary. + +## Related + +- [Deploying to Rivet Compute](/docs/deploy/rivet-compute) +- [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) +- [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) + +_Source doc path: /docs/cli_ diff --git a/.agents/skills/ai-agent/reference/clients/javascript.md b/.agents/skills/ai-agent/reference/clients/javascript.md new file mode 100644 index 0000000..689d79b --- /dev/null +++ b/.agents/skills/ai-agent/reference/clients/javascript.md @@ -0,0 +1,120 @@ +# Node.js & Bun + +> Source: `src/content/docs/clients/javascript.mdx` +> Canonical URL: https://rivet.dev/docs/clients/javascript +> Description: Connect JavaScript apps to Rivet Actors. + +--- +## Getting Started + +See the [backend quickstart guide](/docs/actors/quickstart/backend) for getting started. + +## Minimal Client + +## Stateless vs Stateful + +## Getting Actors + +## Connection Parameters + +Use `params` for static connection parameters. Use `getParams` when the value can change between connection attempts, such as refreshing a JWT before each `.connect()` or reconnect. + +## Subscribing to Events + +## Connection Lifecycle + +## Low-Level HTTP & WebSocket + +For actors that implement `onRequest` or `onWebSocket`, call them directly: + +```ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("history"); +const history = await response.json(); + +const ws = await handle.webSocket("stream"); +ws.addEventListener("message", (event) => { + console.log("message:", event.data); +}); +ws.send("hello"); +``` + +## Calling from Backend + +## Error Handling + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`createClient()` automatically reads: + +- `RIVET_ENDPOINT` (endpoint) +- `RIVET_NAMESPACE` +- `RIVET_TOKEN` +- `RIVET_RUNNER` + +Defaults to `http://localhost:6420` when unset. RivetKit runs on port 6420 by default. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, use your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## Advanced + +### Skip Ready Wait + +Requests are normally held at the gateway until the actor is ready to accept traffic. An actor is not ready while it's still starting (before `onWake` finishes) or while it's in the [sleep grace period](/docs/actors/lifecycle#shutdown-sequence) (running `onSleep`, `waitUntil`, and pending disconnects). + +Pass `skipReadyWait: true` on the [low-level HTTP and WebSocket APIs](#low-level-http--websocket) to deliver immediately and reach the actor's `onRequest` / `onWebSocket` handler in either window: + +```ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("/healthz", { + skipReadyWait: true, +}); + +const ws = await handle.webSocket("probe", undefined, { + skipReadyWait: true, +}); +``` + +Requests can still return transient lifecycle or gateway errors. Retry once the actor is available again. + +- `actor.stopping`: the actor has fully stopped, i.e. the sleep grace period has ended but it has not yet restarted. +- `guard.actor_stopped_while_waiting`: the request reached the actor tunnel, but the actor stopped before the gateway received a response. +- `guard.tunnel_request_aborted`: the actor tunnel aborted the request before a response started. +- `guard.tunnel_message_timeout`: the gateway dropped the in-flight tunnel request after its tunnel message timeout. +- `guard.tunnel_response_closed`: the actor tunnel closed before sending a response. +- `guard.gateway_response_start_timeout`: the gateway timed out waiting for the actor response to start. + +## API Reference + +**Package:** [rivetkit](https://www.npmjs.com/package/rivetkit) + +See the [RivetKit client overview](/docs/clients). + +- [`createClient`](/typedoc/functions/rivetkit.client_mod.createClient.html) - Create a client +- [`Client`](/typedoc/types/rivetkit.mod.Client.html) - Client type + +_Source doc path: /docs/clients/javascript_ diff --git a/.agents/skills/ai-agent/reference/clients/react.md b/.agents/skills/ai-agent/reference/clients/react.md new file mode 100644 index 0000000..9b976e2 --- /dev/null +++ b/.agents/skills/ai-agent/reference/clients/react.md @@ -0,0 +1,88 @@ +# React + +> Source: `src/content/docs/clients/react.mdx` +> Canonical URL: https://rivet.dev/docs/clients/react +> Description: Connect React apps to Rivet Actors. + +--- +## Getting Started + +See the [React quickstart guide](/docs/actors/quickstart/react) for getting started. + +## Install + +## Minimal Client + +## Stateless vs Stateful + +## Getting Actors + +## Connection Parameters + +## Subscribing to Events + +## Connection Lifecycle + +## Low-Level HTTP & WebSocket + +Use the JavaScript client for raw HTTP and WebSocket access: + +```tsx @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("history"); +const history = await response.json(); + +const ws = await handle.webSocket("stream"); +ws.addEventListener("message", (event) => { + console.log("message:", event.data); +}); +ws.send("hello"); +``` + +## Calling from Backend + +Use the JavaScript client on your backend (Node.js/Bun). See the [JavaScript client docs](/docs/clients/javascript). + +## Error Handling + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`createRivetKit()` (and the underlying `createClient()` instance) automatically read: + +- `RIVET_ENDPOINT` +- `RIVET_NAMESPACE` +- `RIVET_TOKEN` +- `RIVET_RUNNER` + +Defaults to `http://localhost:6420` when unset. RivetKit runs on port 6420 by default. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, use your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## API Reference + +**Package:** [@rivetkit/react](https://www.npmjs.com/package/@rivetkit/react) + +- [`createRivetKit`](/docs/clients/react) - Create hooks for React +- [`useActor`](/docs/clients/react) - Hook for actor instances + +_Source doc path: /docs/clients/react_ diff --git a/.agents/skills/ai-agent/reference/clients/rust.md b/.agents/skills/ai-agent/reference/clients/rust.md new file mode 100644 index 0000000..32bebfc --- /dev/null +++ b/.agents/skills/ai-agent/reference/clients/rust.md @@ -0,0 +1,367 @@ +# Rust (Beta) + +> Source: `src/content/docs/clients/rust.mdx` +> Canonical URL: https://rivet.dev/docs/clients/rust +> Description: Connect Rust apps to Rivet Actors. + +--- +Rust support is in beta. The supported public Rust API is `rivetkit` and `rivetkit::client`; lower-level crates are internal implementation details and do not carry a stability guarantee. See the full API reference on [docs.rs/rivetkit](https://docs.rs/rivetkit), or the runnable [`hello-world-rust`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-rust) example. + +## Getting Started + +See the [Rust quickstart guide](/docs/actors/quickstart/rust) for getting started. + +## Install + +Add the `rivetkit` crate and its companions: + +```sh +cargo add rivetkit anyhow async-trait +cargo add serde --features derive +cargo add tokio --features full +``` + +The Rust client is strongly typed. It shares the same action and event types as your actor, so define your actor in `src/lib.rs` and import those types from both your server and your client. There is no need to redefine the actor on the client. See [Define Your Actor](/docs/actors/quickstart/rust#define-your-actor) in the quickstart for the actor definition this page builds on. + +## Minimal Client + +```rust @nocheck +use counter::{Counter, Increment}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + let count = counter.send(Increment { amount: 1 }).await?; + println!("New count: {count}"); + + Ok(()) +} +``` + +`counter` here is your crate name (the package `name` in `Cargo.toml`, with dashes as underscores). `Counter` and `Increment` are the types you defined alongside your actor. + +## Stateless vs Stateful + +```rust @nocheck +use counter::{Counter, Increment, NewCount}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + + // Stateless: each call is independent + counter.send(Increment { amount: 1 }).await?; + + // Stateful: keep a connection open for realtime events + let connection = counter.connect(); + connection + .on::(|event| println!("count: {}", event.count)) + .await; + connection.send(Increment { amount: 1 }).await?; + + connection.disconnect().await; + Ok(()) +} +``` + +A stateless call on the handle opens a short-lived request per action. A connection keeps a WebSocket open so you can receive events and reuse it across calls. + +## Getting Actors + +```rust @nocheck +use counter::Counter; +use rivetkit::{ + client::{Client, ClientConfig, GetOrCreateOptions}, + prelude::*, + TypedClientExt, +}; +use serde_json::json; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + // Get or create an actor + let room = client.get_or_create_typed_default::("counter", ["room-42"])?; + + // Get an existing actor handle (fails when used if the actor does not exist) + let existing = client.get_typed_default::("counter", ["room-42"])?; + + // Create a new actor with input + let created = client.get_or_create_typed::( + "counter", + ["game-1"], + GetOrCreateOptions { + create_with_input: Some(json!({ "mode": "ranked" })), + ..Default::default() + }, + )?; + + // Get an actor handle by ID + let by_id = client.get_for_id("counter", "actor-id", Default::default())?; + + // Resolve the actor ID + let resolved_id = room.inner().resolve().await?; + println!("Resolved ID: {resolved_id}"); + + Ok(()) +} +``` + +`get_typed_default` / `get_or_create_typed_default` use default options. The non-default variants (`get_typed` / `get_or_create_typed`) take `GetOptions` / `GetOrCreateOptions` for connection parameters, input, and region. + +## Connection Parameters + +Pass connection parameters through the handle options. They are delivered to the actor's `create_conn_state` callback: + +```rust @nocheck +use counter::Counter; +use rivetkit::{ + client::{Client, ClientConfig, GetOrCreateOptions}, + prelude::*, + TypedClientExt, +}; +use serde_json::json; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + let chat = client.get_or_create_typed::( + "counter", + ["general"], + GetOrCreateOptions { + params: Some(json!({ "authToken": "jwt-token-here" })), + ..Default::default() + }, + )?; + + let connection = chat.connect(); + connection.disconnect().await; + Ok(()) +} +``` + +## Subscribing to Events + +`on` registers a typed callback for an event and returns once the subscription is registered: + +```rust @nocheck +use counter::{Counter, NewCount}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let connection = client + .get_or_create_typed_default::("counter", ["general"])? + .connect(); + + connection + .on::(|event| println!("count changed: {}", event.count)) + .await; + + Ok(()) +} +``` + +Event callbacks are synchronous and run for every matching event. The actor's emitted event type (here `NewCount`) is decoded into the typed value for you. + +## Connection Lifecycle + +The lower-level connection exposes lifecycle callbacks and the current status. Reach it with `connection.inner()`: + +```rust @nocheck +use counter::Counter; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let connection = client + .get_or_create_typed_default::("counter", ["general"])? + .connect(); + let inner = connection.inner().clone(); + + inner.on_open(|| println!("connected")).await; + inner.on_close(|| println!("disconnected")).await; + inner.on_error(|message| eprintln!("error: {message}")).await; + inner + .on_status_change(|status| println!("status: {status:?}")) + .await; + + println!("current status: {:?}", inner.conn_status()); + + connection.disconnect().await; + Ok(()) +} +``` + +`ConnectionStatus` is one of `Idle`, `Connecting`, `Connected`, or `Disconnected`. Connections reconnect automatically with backoff until you call `disconnect`. + +## Low-Level HTTP & WebSocket + +For actors that implement `on_request` or `on_websocket`, call them directly on the untyped handle (`handle.inner()`). `fetch` returns a `reqwest::Response`, and `web_socket` returns a `tokio_tungstenite` stream. This example also needs a few extra crates: + +```sh +cargo add futures-util tokio-tungstenite +cargo add reqwest --features json +``` + +```rust @nocheck +use counter::Counter; +use futures_util::{SinkExt, StreamExt}; +use reqwest::{header::HeaderMap, Method}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; +use tokio_tungstenite::tungstenite::Message; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let handle = client.get_or_create_typed_default::("counter", ["general"])?; + + // Raw HTTP request + let response = handle + .inner() + .fetch("history", Method::GET, HeaderMap::new(), None) + .await?; + let history: Vec = response.json().await?; + println!("history: {history:?}"); + + // Raw WebSocket connection + let mut ws = handle.inner().web_socket("stream", None).await?; + ws.send(Message::text("hello")).await?; + if let Some(message) = ws.next().await { + println!("received: {:?}", message?); + } + + Ok(()) +} +``` + +## Calling from Backend + +The client is a normal Tokio type, so you can hold it in your backend (Axum, Actix, etc.) and call actors from request handlers. The client is `Clone` and cheap to share: + +```rust @nocheck +use counter::{Counter, Increment}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +async fn increment(client: Client) -> Result { + let counter = client.get_or_create_typed_default::("counter", ["server-counter"])?; + let count = counter.send(Increment { amount: 1 }).await?; + Ok(count) +} +``` + +## Error Handling + +Action and connection calls return `anyhow::Result`. Actor-side errors surface as an `anyhow::Error` carrying the error group, code, message, and metadata: + +```rust @nocheck +use counter::{Counter, Increment}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + + match counter.send(Increment { amount: 1 }).await { + Ok(count) => println!("count: {count}"), + Err(error) => eprintln!("action failed: {error:#}"), + } + + Ok(()) +} +``` + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```rust @nocheck +use counter::Counter; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + // Compound key: [org, room] + let room = client.get_or_create_typed_default::("counter", ["org-acme", "general"])?; + let actor_id = room.inner().resolve().await?; + println!("Actor ID: {actor_id}"); + + Ok(()) +} +``` + +Keys accept arrays of `&str` or `String` (`["org-acme", "general"]`). Don't build keys with string interpolation like `format!("org:{user_id}")` when `user_id` contains user data. Use arrays instead to prevent key injection attacks. + +### Configuration + +`ClientConfig::new(endpoint)` is a builder. The endpoint is always required; there is no default. Common options: + +```rust @nocheck +use rivetkit::client::ClientConfig; + +let config = ClientConfig::new("http://localhost:6420") + .namespace("default") + .token("pk_...") + .pool_name("my-pool") + .header("x-custom", "value"); +``` + +- `namespace` - target namespace (defaults to the engine's configured namespace). +- `token` - authentication token for the engine. +- `pool_name` - runner pool to target. +- `header` / `headers` - extra HTTP headers sent with each request. +- `max_input_size` - cap on encoded action input size. + +For serverless deployments, set the endpoint to your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints) for details. + +## API Reference + +See the full client API documentation on [docs.rs/rivetkit-client](https://docs.rs/rivetkit-client/latest/rivetkit_client/). + +_Source doc path: /docs/clients/rust_ diff --git a/.agents/skills/ai-agent/reference/clients/swift.md b/.agents/skills/ai-agent/reference/clients/swift.md new file mode 100644 index 0000000..c760645 --- /dev/null +++ b/.agents/skills/ai-agent/reference/clients/swift.md @@ -0,0 +1,454 @@ +# Swift + +> Source: `src/content/docs/clients/swift.mdx` +> Canonical URL: https://rivet.dev/docs/clients/swift +> Description: Connect Swift apps to Rivet Actors. + +--- +## Install + +Add the Swift package dependency and import `RivetKitClient`: + +```swift +// Package.swift +dependencies: [ + .package(url: "https://github.com/rivet-dev/rivetkit-swift", from: "2.0.0") +] + +targets: [ + .target( + name: "MyApp", + dependencies: [ + .product(name: "RivetKitClient", package: "rivetkit-swift") + ] + ) +] +``` + +## Minimal Client + +### Endpoint URL + +```swift +import RivetKitClient + +let config = try ClientConfig( + endpoint: "https://my-namespace:pk_...@api.rivet.dev" +) +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["my-counter"]) +let count: Int = try await handle.action("increment", 1, as: Int.self) +``` + +### Explicit Fields + +```swift +import RivetKitClient + +let config = try ClientConfig( + endpoint: "https://api.rivet.dev", + namespace: "my-namespace", + token: "pk_..." +) +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["my-counter"]) +let count: Int = try await handle.action("increment", 1, as: Int.self) +``` + +## Stateless vs Stateful + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["my-counter"]) + +// Stateless: each call is independent +let current: Int = try await handle.action("getCount", as: Int.self) +print("Current count: \(current)") + +// Stateful: keep a connection open for realtime events +let conn = handle.connect() + +// Subscribe to events using AsyncStream +let eventTask = Task { + for await count in await conn.events("count", as: Int.self) { + print("Event: \(count)") + } +} + +_ = try await conn.action("increment", 1, as: Int.self) + +eventTask.cancel() +await conn.dispose() +await client.dispose() +``` + +## Getting Actors + +```swift +import RivetKitClient + +struct GameInput: Encodable { + let mode: String +} + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +// Get or create an actor +let room = client.getOrCreate("chatRoom", ["room-42"]) + +// Get an existing actor (fails if not found) +let existing = client.get("chatRoom", ["room-42"]) + +// Create a new actor with input +let created = try await client.create( + "game", + ["game-1"], + options: CreateOptions(input: GameInput(mode: "ranked")) +) + +// Get actor by ID +let byId = client.getForId("chatRoom", "actor-id") + +// Resolve actor ID +let resolvedId = try await room.resolve() +print("Resolved ID: \(resolvedId)") + +await client.dispose() +``` + +Actions support positional overloads for 0–5 args: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("counter", ["my-counter"]) + +let count: Int = try await handle.action("getCount") +let updated: String = try await handle.action("rename", "new-name") +let ok: Bool = try await handle.action("setScore", "user-1", 42) + +print("Count: \(count), Updated: \(updated), OK: \(ok)") +await client.dispose() +``` + +If you need more than 5 arguments, use the raw JSON fallback: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("counter", ["my-counter"]) + +let args: [JSONValue] = [ + .string("user-1"), + .number(.int(42)), + .string("extra"), + .string("more"), + .string("args"), + .string("here") +] +let ok: Bool = try await handle.action("setScore", args: args, as: Bool.self) +print("OK: \(ok)") + +await client.dispose() +``` + +## Connection Parameters + +```swift +import RivetKitClient + +struct ConnParams: Encodable { + let authToken: String +} + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +let chat = client.getOrCreate( + "chatRoom", + ["general"], + options: GetOrCreateOptions(params: ConnParams(authToken: "jwt-token-here")) +) + +let conn = chat.connect() + +// Use the connection... +for await status in await conn.statusChanges() { + print("Status: \(status.rawValue)") + if status == .connected { + break + } +} + +await conn.dispose() +await client.dispose() +``` + +## Subscribing to Events + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let conn = client.getOrCreate("chatRoom", ["general"]).connect() + +// Subscribe to events using AsyncStream +let messageTask = Task { + for await (from, body) in await conn.events("message", as: (String, String).self) { + print("\(from): \(body)") + } +} + +// For one-time events, break after receiving +let gameOverTask = Task { + for await _ in await conn.events("gameOver", as: Void.self) { + print("done") + break + } +} + +// Let it run for a bit +try await Task.sleep(for: .seconds(5)) + +// Cancel when done +messageTask.cancel() +gameOverTask.cancel() +await conn.dispose() +await client.dispose() +``` + +Event streams support 0–5 typed arguments. If you need raw values or more than 5 arguments, use `JSONValue`: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let conn = client.getOrCreate("chatRoom", ["general"]).connect() + +let rawTask = Task { + for await args in await conn.events("message") { + print(args) + } +} + +try await Task.sleep(for: .seconds(5)) +rawTask.cancel() +await conn.dispose() +await client.dispose() +``` + +## Connection Lifecycle + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let conn = client.getOrCreate("chatRoom", ["general"]).connect() + +// Monitor status changes (immediately yields current status) +let statusTask = Task { + for await status in await conn.statusChanges() { + print("status: \(status.rawValue)") + } +} + +// Monitor errors +let errorTask = Task { + for await error in await conn.errors() { + print("error: \(error.group).\(error.code)") + } +} + +// Monitor open/close events +let openTask = Task { + for await _ in await conn.opens() { + print("connected") + } +} + +let closeTask = Task { + for await _ in await conn.closes() { + print("disconnected") + } +} + +// Check current status +let current = await conn.currentStatus +print("Current status: \(current.rawValue)") + +// Let it run for a bit +try await Task.sleep(for: .seconds(5)) + +// Cleanup +statusTask.cancel() +errorTask.cancel() +openTask.cancel() +closeTask.cancel() +await conn.dispose() +await client.dispose() +``` + +## Low-Level HTTP & WebSocket + +For actors that implement `onRequest` or `onWebSocket`, you can call them directly: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("chatRoom", ["general"]) + +// Raw HTTP request +let response = try await handle.fetch("history") +let history: [String] = try response.json([String].self) +print("History: \(history)") + +// Raw WebSocket connection +let websocket = try await handle.websocket(path: "stream") +try await websocket.send(text: "hello") +let message = try await websocket.receive() +print("Received: \(message)") + +await client.dispose() +``` + +## Calling from Backend + +Use the same client in server-side Swift (Vapor, Hummingbird, etc.): + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["server-counter"]) +let count: Int = try await handle.action("increment", 1, as: Int.self) +print("Count: \(count)") + +await client.dispose() +``` + +## Error Handling + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +do { + _ = try await client.getOrCreate("user", ["user-123"]) + .action("updateUsername", "ab", as: String.self) +} catch let error as ActorError { + print("Error code: \(error.code)") + print("Metadata: \(String(describing: error.metadata))") +} + +await client.dispose() +``` + +If you need an untyped response, you can decode to `JSONValue`: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("data", ["raw"]) + +let value: JSONValue = try await handle.action("getRawPayload") +print("Raw value: \(value)") + +await client.dispose() +``` + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +// Use compound keys for hierarchical addressing +let room = client.getOrCreate("chatRoom", ["org-acme", "general"]) +let actorId = try await room.resolve() +print("Actor ID: \(actorId)") + +await client.dispose() +``` + +Don't build keys with string interpolation like `"org:\(userId)"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`ClientConfig` reads optional values from environment variables: + +- `RIVET_NAMESPACE` - Namespace (can also be in endpoint URL) +- `RIVET_TOKEN` - Authentication token (can also be in endpoint URL) +- `RIVET_RUNNER` - Runner name (defaults to `"default"`) + +The `endpoint` parameter is always required. There is no default endpoint. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, set the endpoint to your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## API Reference + +### Client +- `RivetKitClient(config:)` - Create a client with a config +- `ClientConfig` - Configure endpoint, namespace, and token +- `client.get()` / `getOrCreate()` / `getForId()` / `create()` - Get actor handles +- `client.dispose()` - Dispose the client and all connections + +### ActorHandle +- `handle.action(name, args..., as:)` - Stateless action call +- `handle.connect()` - Create a stateful connection +- `handle.resolve()` - Get the actor ID +- `handle.getGatewayUrl()` - Get the raw gateway URL +- `handle.fetch(path, request:)` - Raw HTTP request +- `handle.websocket(path:)` - Raw WebSocket connection + +### ActorConnection +- `conn.action(name, args..., as:)` - Action call over WebSocket +- `conn.events(name, as:)` - AsyncStream of typed events +- `conn.statusChanges()` - AsyncStream of status changes +- `conn.errors()` - AsyncStream of connection errors +- `conn.opens()` - AsyncStream that yields on connection open +- `conn.closes()` - AsyncStream that yields on connection close +- `conn.currentStatus` - Current connection status +- `conn.dispose()` - Close the connection + +### Types +- `ActorConnStatus` - Connection status enum (`.idle`, `.connecting`, `.connected`, `.disconnected`, `.disposed`) +- `ActorError` - Typed actor errors with `group`, `code`, `message`, `metadata` +- `JSONValue` - Raw JSON value for untyped responses + +_Source doc path: /docs/clients/swift_ diff --git a/.agents/skills/ai-agent/reference/clients/swiftui.md b/.agents/skills/ai-agent/reference/clients/swiftui.md new file mode 100644 index 0000000..4ae65d8 --- /dev/null +++ b/.agents/skills/ai-agent/reference/clients/swiftui.md @@ -0,0 +1,359 @@ +# SwiftUI + +> Source: `src/content/docs/clients/swiftui.mdx` +> Canonical URL: https://rivet.dev/docs/clients/swiftui +> Description: Build SwiftUI apps with Rivet Actors. + +--- +## Install + +Add the Swift package dependency and import `RivetKitSwiftUI`: + +```swift +// Package.swift +dependencies: [ + .package(url: "https://github.com/rivet-dev/rivetkit-swift", from: "2.0.0") +] + +targets: [ + .target( + name: "MyApp", + dependencies: [ + .product(name: "RivetKitSwiftUI", package: "rivetkit-swift") + ] + ) +] +``` + +`RivetKitSwiftUI` re-exports `RivetKitClient` and `SwiftUI`, so a single import covers both. + +## Minimal Client + +```swift HelloWorldApp.swift +import RivetKitSwiftUI +import SwiftUI + +@main +struct HelloWorldApp: App { + var body: some Scene { + WindowGroup { + ContentView() + .rivetKit(endpoint: "https://my-namespace:pk_...@api.rivet.dev") + } + } +} +``` + +```swift ContentView.swift +import RivetKitSwiftUI +import SwiftUI + +struct ContentView: View { + @Actor("counter", key: ["my-counter"]) private var counter + @State private var count = 0 + + var body: some View { + VStack(spacing: 16) { + Text("\(count)") + .font(.system(size: 64, weight: .bold, design: .rounded)) + + Button("Increment") { + counter.send("increment", 1) + } + .disabled(!counter.isConnected) + } + .task { + count = (try? await counter.action("getCount")) ?? 0 + } + .onActorEvent(counter, "newCount") { (newCount: Int) in + count = newCount + } + } +} +``` + +## Actor Options + +The `@Actor` property wrapper always uses get-or-create semantics and accepts: + +- `name` (required) +- `key` as `String` or `[String]` (required) +- `params` (optional connection parameters) +- `createWithInput` (optional creation input) +- `createInRegion` (optional creation hint) +- `enabled` (toggle connection lifecycle) + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct ConnParams: Encodable { + let authToken: String +} + +struct ChatView: View { + @Actor( + "chatRoom", + key: ["general"], + params: ConnParams(authToken: "jwt-token"), + enabled: true + ) private var chat + + var body: some View { + Text("Chat: \(chat.connStatus.rawValue)") + } +} +``` + +## Actions + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct CounterView: View { + @Actor("counter", key: ["my-counter"]) private var counter + @State private var count = 0 + @State private var name = "" + + var body: some View { + VStack { + Text("Count: \(count)") + Text("Name: \(name)") + + Button("Fetch") { + Task { + count = try await counter.action("getCount") + name = try await counter.action("rename", "new-name") + } + } + + Button("Increment") { + counter.send("increment", 1) + } + } + } +} +``` + +## Subscribing to Events + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct GameView: View { + @Actor("game", key: ["game-1"]) private var game + @State private var count = 0 + @State private var isGameOver = false + + var body: some View { + VStack { + Text("Count: \(count)") + if isGameOver { + Text("Game Over!") + } + } + .onActorEvent(game, "newCount") { (newCount: Int) in + count = newCount + } + .onActorEvent(game, "gameOver") { + isGameOver = true + } + } +} +``` + +## Async Event Streams + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct ChatView: View { + @Actor("chatRoom", key: ["general"]) private var chat + @State private var messages: [String] = [] + + var body: some View { + List(messages, id: \.self) { message in + Text(message) + } + .task { + for await message in chat.events("message", as: String.self) { + messages.append(message) + } + } + } +} +``` + +## Connection Status + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct StatusView: View { + @Actor("counter", key: ["my-counter"]) private var counter + @State private var count = 0 + + var body: some View { + VStack { + Text("Status: \(counter.connStatus.rawValue)") + + if counter.connStatus == .connected { + Text("Connected!") + .foregroundStyle(.green) + } + + Button("Fetch via Handle") { + Task { + if let handle = counter.handle { + count = try await handle.action("getCount", as: Int.self) + } + } + } + .disabled(!counter.isConnected) + } + } +} +``` + +## Error Handling + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct UserView: View { + @Actor("user", key: ["user-123"]) private var user + @State private var errorMessage: String? + @State private var username = "" + + var body: some View { + VStack { + TextField("Username", text: $username) + + Button("Update Username") { + Task { + do { + let _: String = try await user.action("updateUsername", username) + } catch let error as ActorError { + errorMessage = "\(error.code): \(String(describing: error.metadata))" + } + } + } + + if let errorMessage { + Text(errorMessage) + .foregroundStyle(.red) + } + } + .onActorError(user) { error in + errorMessage = "\(error.group).\(error.code): \(error.message)" + } + } +} +``` + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct OrgChatView: View { + @Actor("chatRoom", key: ["org-acme", "general"]) private var room + + var body: some View { + Text("Room: \(room.connStatus.rawValue)") + } +} +``` + +Don't build keys with string interpolation like `"org:\(userId)"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Configuration + +Call `.rivetKit(endpoint:)` or `.rivetKit(client:)` once at the root of your view tree: + +```swift +// With endpoint string (recommended for most apps) +@main +struct MyApp: App { + var body: some Scene { + WindowGroup { + ContentView() + .rivetKit(endpoint: "https://my-namespace:pk_...@api.rivet.dev") + } + } +} + +// With custom client (for advanced configuration) +@main +struct MyApp: App { + private let client = RivetKitClient( + config: try! ClientConfig(endpoint: "https://api.rivet.dev", token: "pk_...") + ) + + var body: some Scene { + WindowGroup { + ContentView() + .rivetKit(client: client) + } + } +} +``` + +When using `.rivetKit(endpoint:)`, the client is created once and cached per endpoint. When using `.rivetKit(client:)`, store the client as a property on `App` (not inside `body`) since SwiftUI can call `body` multiple times. + +### Environment Variables + +`ClientConfig` reads optional values from environment variables: + +- `RIVET_NAMESPACE` - Namespace (can also be in endpoint URL) +- `RIVET_TOKEN` - Authentication token (can also be in endpoint URL) +- `RIVET_RUNNER` - Runner name (defaults to `"default"`) + +The endpoint is always required. There is no default endpoint. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, set the endpoint to your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## API Reference + +### Property Wrapper +- `@Actor(name, key:, params:, createWithInput:, createInRegion:, enabled:)` - SwiftUI property wrapper for actor connections + +### View Modifiers +- `.rivetKit(endpoint:)` - Configure client with an endpoint URL (creates cached client) +- `.rivetKit(client:)` - Configure client with a custom instance +- `.onActorEvent(actor, event) { ... }` - Subscribe to actor events (supports 0–5 typed args) +- `.onActorError(actor) { error in ... }` - Handle actor errors + +### ActorObservable +- `actor.action(name, args..., as:)` - Async action call +- `actor.send(name, args...)` - Fire-and-forget action +- `actor.events(name, as:)` - AsyncStream of typed events +- `actor.connStatus` - Current connection status +- `actor.isConnected` - Whether connected +- `actor.handle` - Underlying `ActorHandle` (optional) +- `actor.connection` - Underlying `ActorConnection` (optional) +- `actor.error` - Most recent error (optional) + +### Types +- `ActorConnStatus` - Connection status enum (`.idle`, `.connecting`, `.connected`, `.disconnected`, `.disposed`) +- `ActorError` - Typed actor errors with `group`, `code`, `message`, `metadata` + +_Source doc path: /docs/clients/swiftui_ diff --git a/.agents/skills/ai-agent/reference/cookbook/ai-agent.md b/.agents/skills/ai-agent/reference/cookbook/ai-agent.md new file mode 100644 index 0000000..1adb285 --- /dev/null +++ b/.agents/skills/ai-agent/reference/cookbook/ai-agent.md @@ -0,0 +1,127 @@ +# AI Agent + +> Source: `src/content/cookbook/ai-agent.mdx` +> Canonical URL: https://rivet.dev/cookbook/ai-agent +> Description: Build an AI agent backend with persistent memory: one Rivet Actor per conversation, queued message handling, and streaming LLM responses as realtime events. + +--- +Patterns for building AI agent backends with RivetKit, where each conversation is one Rivet Actor that owns its memory, its message queue, and its streaming output. + +## Starter Code + +Start with one of the working examples on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/ai-agent) and adapt it. The sections below describe the flagship `ai-agent` example unless a variant is called out explicitly. + +| Variant | Starter Code | Use When | +| --- | --- | --- | +| Queue-driven AI SDK agent | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/ai-agent) | You want a streaming chat agent where each conversation keeps its own persistent memory and processes one message at a time. | +| Sandbox coding agent | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/sandbox-coding-agent) | The agent should run a coding agent (Codex by default) inside an isolated [sandbox](/docs/actors/sandbox) via Docker, Daytona, or E2B. | +| Durable streams agent (experimental) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/experimental-durable-streams-ai-agent) | You want replayable, restart-safe prompt and response delivery through durable streams instead of actor state and events. | + +## Conversation Memory + +Use one actor per conversation, keyed by a conversation or agent id (see [Actor Keys](/docs/actors/keys)). The agent actor's persistent [state](/docs/actors/state) is the conversation memory: in the `ai-agent` example, `messages` and `status` live in JSON actor state and survive sleep and restarts with no external database. Every model call rebuilds the prompt from `c.state.messages` plus a system prompt, so memory and inference input are the same data. + +| Variant | Where Memory Lives | Persisted State Fields | +| --- | --- | --- | +| `ai-agent` | JSON actor state | `messages`, `status` | +| `sandbox-coding-agent` | JSON actor state plus the sandbox ACP session | `messages`, `status`, `sessionId` | +| `experimental-durable-streams-ai-agent` | Durable streams; the actor stores only its conversation id and a read cursor | `conversationId`, `promptStreamOffset` | + +## Message Handling + +In the `ai-agent` example, the client pushes user input onto the agent's `message` [queue](/docs/actors/queues) with `agent.connection.send("message", { text, sender })`. This is a queue push, not an action call. The actor's `run` hook (see [Lifecycle](/docs/actors/lifecycle)) consumes the queue serially with `for await (const queued of c.queue.iter())`. + +Serial queue consumption is the per-conversation concurrency guarantee: at most one in-flight model call per actor, with no extra locking. The `status` field (`thinking` while a model call is in flight) is UI signal only; the run loop is the actual lock. The loop also checks `c.aborted` inside the token stream so shutdown exits gracefully. + +| Variant | Message Ingress | Serialization Guarantee | +| --- | --- | --- | +| `ai-agent` | `message` queue pushed via `connection.send` | `run` hook pops one queued message at a time with `c.queue.iter()`. | +| `sandbox-coding-agent` | `sendMessage` [action](/docs/actors/actions), no queue | Each call awaits the sandbox round trip before broadcasting the result. | +| `experimental-durable-streams-ai-agent` | Durable prompt stream long-polled from `onWake` | `promptStreamOffset` is persisted per chunk, so restarts resume without reprocessing prompts. | + +## Streaming Responses + +The `ai-agent` actor broadcasts a `response` [event](/docs/actors/events) for every model text delta. The payload carries `messageId`, the per-token `delta`, the cumulative `content`, and a `done` flag (plus `error` on failure), so clients can either append deltas or idempotently replace the message by `messageId` using `content`. The example frontend replaces by `messageId`, which tolerates dropped events. The terminal broadcast has an empty `delta`, the full `content`, and `done: true`. + +Because the assistant message object lives in `c.state.messages` and is mutated in place during streaming, partial content persists if the actor restarts mid-stream. The example broadcasts once per AI SDK delta with no throttling; batching or throttling deltas is a recommended extension for high-traffic deployments, not something the example implements. + +Variant differences: `sandbox-coding-agent` sends a single `response` broadcast with `done: true` after the sandbox finishes (no incremental streaming), and `experimental-durable-streams-ai-agent` appends per-token chunks to a durable response stream, then broadcasts `responseComplete` or `responseError`. + +## Architecture + +| Topic | Summary | +| --- | --- | +| Topology | `agentManager["primary"]` singleton directory plus one `agent[agentId]` actor per conversation. | +| Ingress | Client pushes `AgentQueueMessage` payloads onto the agent's `message` queue with `connection.send`. | +| Streaming | One `response` broadcast per model delta, terminal broadcast with `done: true`. | +| Memory | Full transcript and status in JSON actor state; no external database. | + +The manager creates `AgentInfo` records and warms each agent through [actor-to-actor communication](/docs/actors/communicating-between-actors): `createAgent` calls `c.client()`, then `client.agent.getOrCreate([info.id])` and awaits `getStatus()` so the conversation actor exists before the client connects. The sandbox variant extends this topology with a `codingSandbox` actor that shares the agent's key (`codingSandbox.getOrCreate([c.key[0]])`), so the agent-to-sandbox mapping is implicit in the key space. + +**Actors** + +- **Key**: `agentManager["primary"]` +- **Responsibility**: Directory actor. Creates `AgentInfo` records, lists agents, and warms each agent actor via `c.client()`. +- **Actions** + - `createAgent` + - `listAgents` +- **Queues** + - None +- **State** + - JSON + - `agents` + +- **Key**: `agent[agentId]` +- **Responsibility**: One actor per conversation. Holds the full message history and status, consumes queued user messages in its `run` loop, calls the model via the AI SDK, and broadcasts streaming deltas. +- **Actions** + - `getHistory` + - `getStatus` +- **Queues** + - `message` +- **Events** + - `messageAdded` + - `status` + - `response` +- **State** + - JSON + - `messages` + - `status` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant AM as agentManager + participant A as agent + participant LLM as Model API + + C->>AM: createAgent(name) + AM->>A: getOrCreate([info.id]) + getStatus() + AM-->>C: AgentInfo + C->>A: connection.send("message", {text, sender}) + Note over A: run loop pops queue via c.queue.iter() + A-->>C: messageAdded (user message) + A-->>C: messageAdded (assistant placeholder) + A-->>C: status (thinking) + A->>LLM: streamText(system prompt + history) + loop each text delta + LLM-->>A: delta + A-->>C: response {messageId, delta, content, done: false} + end + A-->>C: response {delta: "", content, done: true} + A-->>C: status (idle) +``` + +## Security Checklist + +The examples ship without auth so they stay minimal. Apply this baseline before exposing an agent backend. + +- **API keys stay server-side**: `OPENAI_API_KEY` (or `ANTHROPIC_API_KEY`) is read by the AI SDK inside the actor process. The key never reaches the browser; clients only talk to the actor over RivetKit. The sandbox variant forwards keys into the sandbox env, never to the client. +- **Add authentication**: The examples have no auth, so anyone who reaches the server can create agents, list them, and message any agent whose key they can guess. Add `onBeforeConnect` or `createConnState` checks with scoped tokens as a recommended extension. See [Authentication](/docs/actors/authentication). +- **Validate and rate-limit queue payloads**: The example only skips bodies without a string `text`. Enforce payload size limits, schema validation, and per-connection rate limits as a recommended extension. +- **Derive sender identity server-side**: The example trusts the client-supplied `sender` field verbatim. Bind sender identity to the authenticated connection instead. +- **Cap or trim message history**: The example sends the full transcript on every model call with no cap. Trim or summarize old messages as a recommended extension so prompts and state stay bounded. +- **Set cost ceilings per conversation**: Add per-agent token budgets and quotas as a recommended extension. The sandbox variant runs real compute, so also enforce per-user sandbox quotas and restrict sandbox network egress. + +_Source doc path: /cookbook/ai-agent_ diff --git a/.agents/skills/ai-agent/reference/cookbook/chat-room.md b/.agents/skills/ai-agent/reference/cookbook/chat-room.md new file mode 100644 index 0000000..cb8dbe4 --- /dev/null +++ b/.agents/skills/ai-agent/reference/cookbook/chat-room.md @@ -0,0 +1,114 @@ +# Chat Room + +> Source: `src/content/cookbook/chat-room.mdx` +> Canonical URL: https://rivet.dev/cookbook/chat-room +> Description: Build a realtime chat room backend with Rivet Actors: one actor per room, SQLite-backed message history, and WebSocket broadcast to every connected client. + +--- +Patterns for building a chat room backend with RivetKit: room-scoped actors, persistent message history, and realtime delivery over WebSocket connections. + +## Starter Code + +Start with the working example on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room) and adapt it. The backend is a single `chatRoom` actor; the frontend is a React app using `@rivetkit/react` (see the [React quickstart](/docs/actors/quickstart/react)). + +| Topic | Summary | +| --- | --- | +| Room model | One `chatRoom` actor per room key. The frontend defaults the key to `general`; typing a different room name connects to a different actor. | +| History | SQLite `messages` table created in `db({ onMigrate })`, read back with `ORDER BY id ASC`. | +| Delivery | `sendMessage` inserts the row, then broadcasts a typed `newMessage` event to every connected client. | +| Identity | None in the example. `sender` is a plain action argument; production should bind identity to the connection. | + +## Room-Per-Actor Model + +Each room is one Rivet Actor instance, addressed by [key](/docs/actors/keys). The client calls `useActor({ name: "chatRoom", key: [roomId] })`, which gets-or-creates the actor for that room. This gives you: + +- **Isolation**: each room's history and connections are fully scoped to its key. Switching the room input re-keys the hook and connects to a different actor with separate history. +- **A single serialized writer**: all `sendMessage` calls for one room run through one actor, so message ordering is consistent without locks. The SQLite `AUTOINCREMENT` id is the canonical order, which is why `getHistory` sorts by `id` rather than by timestamp. +- **Natural scaling**: rooms spread across the cluster independently. A hot room does not slow down other rooms. + +## Message History Storage + +This example stores history in the actor's SQLite database, not in JSON state. Pick based on history size and query needs: + +| Approach | Use When | Implementation Guidance | +| --- | --- | --- | +| [SQLite](/docs/actors/sqlite) (what this example uses) | Large or long-lived history that needs ordering, caps, pagination, or search | Create the `messages` table in `db({ onMigrate })`, insert with parameterized queries (`c.db.execute("INSERT ... VALUES (?, ?, ?)", ...)`), and read with `ORDER BY id ASC`. History survives actor sleep and scales past what you want in memory. | +| [JSON state](/docs/actors/state) | Small recent history, for example the last 50 to 100 messages | Push onto a `messages` array in actor state and trim to a cap on every send. Simplest option, but the whole history lives in memory and there is no query layer, so it only fits bounded recent-history use cases. | + +## Broadcast Delivery + +New messages reach connected clients through a typed [event](/docs/actors/events): + +- The actor declares `events: { newMessage: event() }`, where `Message` is `{ sender, text, timestamp }`. +- The `sendMessage` [action](/docs/actors/actions) builds the message with a server-side `Date.now()` timestamp, inserts it into the `messages` table, then calls `c.broadcast("newMessage", message)` and returns the message to the caller. +- Each client subscribes with `useEvent("newMessage", ...)` and appends to its local list. The sender renders its own message through the same broadcast path as everyone else, so all clients stay on one code path. +- History load is connection-gated: once the connection is ready, the client calls `getHistory()` once to render the backlog, then relies on events for everything after. + +Use `c.broadcast(...)` for room-wide messages. For private or per-recipient payloads (such as DMs inside a room), send on the individual connection instead, which is a recommended extension beyond this example. + +## Typing Indicators And Presence (Extension) + +The example does not implement typing indicators, presence, or join/leave handling of any kind. There is no `createConnState`, `onConnect`, or `onDisconnect` in the code. If you need them, add them as ephemeral [connection](/docs/actors/connections) behavior: + +- **Keep it ephemeral**: store the username and typing flag in per-connection state, never in SQLite or persisted actor state. Presence is derived from live connections and should disappear with them. +- **Broadcast on change only**: emit a typing event when a user starts or stops typing, and a presence event from `onConnect` / `onDisconnect`, rather than polling or ticking. +- **Expire on the client**: clear a typing indicator after a short client-side timeout so a dropped connection never leaves a stuck "is typing" row. + +## Per-User Inbox (Extension) + +For offline delivery, DMs, unread counts, or notification fanout, add a `userInbox[userId]` actor per user. This is an extension beyond the example: + +- The room actor forwards each message to the inbox actor of every member via [actor-to-actor calls](/docs/actors/communicating-between-actors), so users who are not connected to the room still accumulate messages. +- The inbox actor owns per-user unread state and serves it when the user comes online, independent of which rooms they are in. +- DMs become a degenerate room: either a `chatRoom` keyed by the sorted pair of user ids, or direct inbox-to-inbox delivery if you do not need shared history semantics. + +## Actors + +- **Key**: `chatRoom[roomId]` +- **Responsibility**: Owns one chat room. Persists the room's message history in its SQLite database and broadcasts each new message to every connected client. +- **Actions** + - `sendMessage` + - `getHistory` +- **Queues** + - None +- **Events** + - `newMessage` +- **State** + - SQLite + - `messages` table: `id` (autoincrement primary key), `sender`, `text`, `timestamp` + +## Lifecycle + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant R as chatRoom + + A->>R: connect with key [roomId] + Note over R: every start runs onMigrate (CREATE TABLE IF NOT EXISTS messages) + A->>R: getHistory() + R-->>A: Message[] ordered by id + B->>R: connect with key [roomId] + B->>R: getHistory() + R-->>B: Message[] ordered by id + A->>R: sendMessage(sender, text) + Note over R: INSERT row with server timestamp + R-->>A: newMessage (broadcast) + R-->>B: newMessage (broadcast) + A->>R: disconnect + Note over R: history stays in SQLite for the next connection +``` + +## Security Checklist + +The example is intentionally minimal and skips all of the following. Add them before production: + +- **Auth before join**: any client can join any room by knowing its name, and `sender` is arbitrary client input on every call. Validate a token during [connection auth](/docs/actors/authentication), bind identity to [connection state](/docs/actors/connections), and check room membership before serving history. Never trust a sender name passed as an action argument. +- **Message length clamps**: the example accepts empty messages and has no length limit. Trim server-side, reject empty text, and clamp to a maximum length. +- **Per-connection rate limiting**: rate limit `sendMessage` per connection to stop spam and broadcast amplification. +- **Server-side timestamps and ids**: the example already does this correctly. `timestamp` comes from `Date.now()` inside the action and `id` from SQLite `AUTOINCREMENT`. Keep it that way; never accept client-supplied timestamps or ids. +- **History caps**: `getHistory` returns every row with no limit. Add a `LIMIT` plus pagination, and prune or archive old rows so a long-lived room cannot grow unbounded. +- **Parameterized queries**: the example already inserts with `?` placeholders. Keep all user-supplied text out of SQL string interpolation. + +_Source doc path: /cookbook/chat-room_ diff --git a/.agents/skills/ai-agent/reference/cookbook/collaborative-text-editor.md b/.agents/skills/ai-agent/reference/cookbook/collaborative-text-editor.md new file mode 100644 index 0000000..cacbc1f --- /dev/null +++ b/.agents/skills/ai-agent/reference/cookbook/collaborative-text-editor.md @@ -0,0 +1,157 @@ +# Collaborative Text Editor + +> Source: `src/content/cookbook/collaborative-text-editor.mdx` +> Canonical URL: https://rivet.dev/cookbook/collaborative-text-editor +> Description: Build a collaborative text editor backend with Yjs CRDTs and Rivet Actors: per-document actors relay sync and awareness updates and persist snapshots. + +--- +Patterns for building a Yjs server on RivetKit: CRDT document sync, presence and cursors, and snapshot persistence, with one Rivet Actor per document acting as a relay. + +## Starter Code + +Start with the working example on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/collaborative-document) and adapt it to your editor. It ships a React frontend with a plain textarea, remote cursor overlays, and a workspace document index. + +| Use Case | Starter Code | Common Examples | +| --- | --- | --- | +| Shared document editing | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/collaborative-document) | Notion-style docs, shared notes, pair-writing tools, form co-editing | + +## CRDT vs OT + +Two families of algorithms solve concurrent text editing. The choice decides what your server has to do. + +| Dimension | CRDT (Yjs) | Operational Transformation | +| --- | --- | --- | +| Conflict resolution model | Commutative merges. Updates apply in any order on any peer and converge to the same result. | Server transforms each operation against every concurrent operation. Correctness depends on a central sequencer. | +| Offline support | Strong. Clients keep editing locally and merge buffered updates on reconnect. | Weak. Long-lived divergence makes transformation chains complex and fragile. | +| Server role | Relay plus persistence. The server applies opaque updates and rebroadcasts them. It never needs to understand document semantics. | Authoritative transformer. The server must implement transformation logic for every operation type. | +| Library maturity | Yjs is mature and widely deployed, with bindings for ProseMirror, CodeMirror, Monaco, and others. | Production-grade implementations are mostly proprietary (Google Docs) or aging (ShareDB). | + +The example uses Yjs because CRDTs let the server stay a relay-style Rivet Actor. The actor applies each incoming update to a server-side `Y.Doc` so it can persist the merged state and serve late joiners, but it never transforms operations or arbitrates conflicts. Ordering does not matter because Yjs merges are commutative. + +## Document Actor Model + +| Topic | Summary | +| --- | --- | +| Topology | One `document[workspaceId, documentId]` actor per document plus one `documentList[workspaceId]` coordinator per workspace. | +| Sync model | Each client holds a local `Y.Doc`. The document actor relays incremental Yjs updates as broadcast [events](/docs/actors/events) and keeps a server-side merged copy in vars. | +| Persistence | Full merged Yjs snapshot overwritten in one binary [actor KV](/docs/actors/kv) key (`yjs:doc`) on every sync update. Document metadata lives in JSON [state](/docs/actors/state). | +| Queues | None. The example is purely [actions](/docs/actors/actions) plus broadcast events. | +| Presence | Yjs Awareness relayed through the same `applyUpdate` action. Per-connection `connState` tracks asserted awareness clientIds for disconnect cleanup. | + +The two-actor split follows the coordinator pattern from [Design Patterns](/docs/actors/design-patterns): the coordinator owns discovery and creation, and each document actor owns one document's realtime state. Multi-part [keys](/docs/actors/keys) scope both actors to a workspace. + +**Actors** + +- **Key**: `document[workspaceId, documentId]` +- **Responsibility**: Applies incoming sync and awareness updates to a server-side `Y.Doc` and `Awareness`, persists the merged Yjs snapshot to actor KV, and broadcasts updates to all connected collaborators. +- **Actions** + - `getContent` + - `applyUpdate` + - `getAwareness` +- **Queues** + - None +- **State** + - JSON metadata only: `title`, `createdAt`, `updatedAt` + - Binary KV key `yjs:doc` holding the full merged Yjs snapshot + - Ephemeral vars: the live `Y.Doc` and `Awareness`, created in `createVars` and rehydrated from KV on actor start + - Per-connection `connState`: `clientIds` of awareness clients asserted by that connection + +- **Key**: `documentList[workspaceId]` +- **Responsibility**: Coordinator for one workspace. Creates document actors through the actor-to-actor client and maintains the index of document summaries. +- **Actions** + - `createDocument` + - `listDocuments` + - `deleteDocument` +- **Queues** + - None +- **State** + - JSON + - `documents` array of `DocumentSummary` entries (`id`, `title`, `createdAt`, `updatedAt`) + +The coordinator's `createDocument` generates a UUID, then explicitly creates the document actor with `c.client()` and passes `{ title, createdAt }` as creation [input](/docs/actors/input), which the document actor's `createState` consumes. See [Communicating Between Actors](/docs/actors/communicating-between-actors) for the actor-to-actor client. + +## Update Relay + +A single `applyUpdate(update, kind, clientId?)` action handles both update kinds. Updates cross the action boundary as `number[]` byte arrays and are converted back to `Uint8Array` on each side. + +| Kind | Server Applies To | Persists | Broadcasts | +| --- | --- | --- | --- | +| `"sync"` | `c.vars.doc` via `Y.applyUpdate` with origin `"client"` | Full merged snapshot to KV key `yjs:doc`, then bumps `updatedAt` | `sync` event carrying the incremental update | +| `"awareness"` | `c.vars.awareness` via `applyAwarenessUpdate` with origin `"client"` | Nothing. Presence is ephemeral. | `awareness` event carrying the update | + +Note the asymmetry on the sync branch: the broadcast carries only the small incremental update, while the KV write stores the full merged document re-encoded with `Y.encodeStateAsUpdate`. + +Yjs origin tags are the echo guards that keep the relay loop-free: + +| Origin Tag | Set Where | Effect | +| --- | --- | --- | +| `"local"` | Client edits inside `doc.transact(..., "local")` | The client's update listener fires and sends `applyUpdate` to the actor. | +| `"client"` | Server applying an incoming update to its `Y.Doc` or `Awareness` | Marks the change as client-originated on the server copy. | +| `"remote"` | Client applying broadcast events or initial sync data | Update listeners early-return on `"remote"`, so a client never re-sends its own echo. | + +On connect or reconnect, the client calls `getContent` and `getAwareness`, then applies both results to its local `Y.Doc` and `Awareness` with origin `"remote"`. After that, every change flows through `applyUpdate` and the broadcast events. + +## Awareness And Presence + +Presence (user names, colors, cursor positions) rides on the Yjs Awareness protocol instead of actor state: + +- Clients set presence with `awareness.setLocalStateField` for the `user` and `cursor` fields. The awareness update listener encodes the change and sends `applyUpdate(update, "awareness", awareness.clientID)`. +- The actor records each asserted `clientId` in that connection's `connState.clientIds`, applies the update to the server-side `Awareness`, and broadcasts the `awareness` event to all peers. See [Connections](/docs/actors/connections) for per-connection state. +- `onDisconnect` reads the connection's `clientIds`, calls `removeAwarenessStates` on the server-side `Awareness`, and broadcasts the encoded removal so every remaining client drops the departed user's cursor. See [Lifecycle](/docs/actors/lifecycle) for the hook. + +Because the actor tracks which awareness clientIds belong to which connection, presence cleanup is automatic on disconnect with no client cooperation required. + +## Persistence And Compaction + +The example persists with a full-snapshot overwrite: on every `"sync"` update, the actor re-encodes the entire merged document with `Y.encodeStateAsUpdate` and overwrites the single binary KV key `yjs:doc`. There is no append-only update log and no separate compaction job. Compaction is implicit because `Y.encodeStateAsUpdate` emits one compact merged representation of the document, so Yjs merge semantics keep the stored blob compact on their own. + +| Property | Full-Snapshot Overwrite (the example) | +| --- | --- | +| Write cost | One full-document KV write per sync update, so every keystroke rewrites the whole blob. | +| Read cost | One binary KV read in `createVars` rehydrates the document on actor start. | +| Crash safety | The last completed `applyUpdate` is durable. No log replay needed. | +| Sweet spot | Small to medium documents where simplicity beats write amplification. | + +**Recommended extension (not in the example)**: for large documents or very high edit rates, switch to appending incremental updates to a KV update log and writing a merged snapshot only periodically (for example every N updates). Boot becomes snapshot plus log replay, and the snapshot write becomes the explicit compaction step that truncates the log. Adopt this only when full-snapshot writes become the measured bottleneck or the blob approaches KV value size limits. + +## Lifecycle + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant DL as documentList + participant D as document + + A->>DL: listDocuments() + A->>DL: createDocument(title) + DL->>D: create([workspaceId, documentId], input) + DL-->>A: DocumentSummary + A->>D: connect + B->>D: connect + Note over D: createVars rehydrates Y.Doc from KV "yjs:doc" + A->>D: getContent() + getAwareness() + D-->>A: encoded doc + awareness state + Note over A: local edit with origin "local" + A->>D: applyUpdate(update, "sync") + Note over D: apply with origin "client", overwrite KV snapshot + D-->>B: sync event (incremental update) + Note over B: apply with origin "remote", no echo + A->>D: applyUpdate(update, "awareness", clientId) + D-->>B: awareness event + B-->>D: disconnect + Note over D: onDisconnect removes B's awareness clientIds + D-->>A: awareness event (removal) +``` + +## Security Checklist + +The example ships with no authentication or authorization. Harden it with this baseline before production. None of these are implemented in the example. + +- **Authenticate before connect**: Anyone who knows or guesses a workspace ID can connect, and because `useActor` implicitly getOrCreates, connecting with a nonexistent workspace ID silently creates a blank `documentList` coordinator. Add connection auth so unauthenticated clients never reach an actor. See [Authentication](/docs/actors/authentication). +- **Per-document access control**: Validate that the authenticated user is allowed to access the specific `[workspaceId, documentId]` key, not just any document. +- **Cap and rate limit `applyUpdate`**: Update payloads are unvalidated `number[]` arrays with no size limit, and the example client sends one action per keystroke and per cursor move with zero throttling. Enforce payload size caps and per-connection rate limits on the server, and debounce on the client. +- **Do not trust client-asserted awareness clientIds**: The `clientId` argument to `applyUpdate` is client-supplied and trusted as-is. Derive or verify presence identity from connection-scoped server state instead. +- **Destroy actors and KV on delete**: `deleteDocument` only filters the entry out of the coordinator's index. The document actor and its KV snapshot are orphaned. On delete, also destroy the document actor and its storage, with a permission check on who may delete. + +_Source doc path: /cookbook/collaborative-text-editor_ diff --git a/.agents/skills/ai-agent/reference/cookbook/cron-jobs.md b/.agents/skills/ai-agent/reference/cookbook/cron-jobs.md new file mode 100644 index 0000000..12f7119 --- /dev/null +++ b/.agents/skills/ai-agent/reference/cookbook/cron-jobs.md @@ -0,0 +1,123 @@ +# Cron Jobs and Scheduled Tasks + +> Source: `src/content/cookbook/cron-jobs.mdx` +> Canonical URL: https://rivet.dev/cookbook/cron-jobs +> Description: Durable cron jobs with Rivet Actors: schedule.after and schedule.at timers survive restarts and crashes, plus re-arming recurring jobs and idempotent handlers. + +--- +Patterns for running durable cron jobs and scheduled tasks on Rivet Actors. Actor schedules are persistent timers owned by the engine, so a job keeps its deadline through actor sleep, restarts, upgrades, deploys, and crashes. + +## Starter Code + +Start from the working [Scheduling example on GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/scheduling). It implements a reminder service with one-shot timers, a React frontend, and live trigger events. + +## The Scheduling API + +The full API is documented in [Scheduling](/docs/actors/schedule). There are two methods, both available on the actor context: + +| Method | Behavior | +| --- | --- | +| `c.schedule.after(duration, actionName, ...args)` | Runs the named action after `duration` milliseconds. | +| `c.schedule.at(timestamp, actionName, ...args)` | Runs the named action at an exact epoch timestamp in milliseconds. | + +Key properties: + +- **Durable**: The schedule is persisted by the engine and the timer survives actor sleep, restart, upgrade, and crash. If the actor is asleep at the deadline, the engine wakes it to run the action. See [Lifecycle](/docs/actors/lifecycle). +- **Plain actions as callbacks**: The scheduled callback is an ordinary [action](/docs/actors/actions) on the same actor, invoked by name. Arguments after the action name are forwarded positionally, for example `c.schedule.after(delayMs, "triggerReminder", reminder.id)`. +- **No cancellation API**: Rivet does not currently support canceling a scheduled action. The pattern is a tombstone guard: remove the entry from [state](/docs/actors/state) and have the scheduled action no-op when it cannot find its entry. The example's `cancelReminder` and `triggerReminder` actions implement exactly this. + +## Recurring Jobs Via Re-Arm + +`c.schedule` is one-shot, so recurring jobs are built by having the scheduled action re-arm itself at the end of each run: + +Arm the first run from `onCreate` or a setup action; after that, the action keeps the chain alive by rescheduling itself. + +Re-arming with `after` measures the next run from the end of the current one, so the cadence drifts later by the job's runtime on every cycle. If runs must stay aligned to a fixed cadence, re-arm with `c.schedule.at(c.state.lastRunAt + DAY_MS, "runReport")` instead. + +The Scheduling example itself only uses one-shot reminders. A real re-arm implementation lives in the [idle world actor](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/idle/), where the `collectProduction` action credits production, updates `lastCollectedAt`, and calls a `scheduleCollection` helper that re-arms with `c.schedule.after(delayMs, "collectProduction", { buildingId })`. It also shows catch-up handling: if the action runs late, it computes how many whole intervals elapsed since the last run and credits them in one batch before re-arming. + +For multi-step jobs that need retries and progress tracking inside a single run, consider [Workflows](/docs/actors/workflows) instead of chaining schedules. + +## Durability Comparison + +| Approach | Timer Durability | Horizontal Scaling | Deploys And Restarts | +| --- | --- | --- | --- | +| `setTimeout` / `setInterval` | In-process memory only | Every replica arms its own timer, so jobs run once per instance | All pending timers are lost on restart or crash | +| `node-cron` and similar libraries | In-process memory only | Every instance runs the job unless you add external locking | Schedule resets on deploy; runs missed during downtime are skipped | +| External cron service | Lives outside your app | Needs a public HTTP endpoint plus its own dedupe and retry state | Survives your deploys but is separate infrastructure to operate | +| Rivet Actor scheduling | Persisted by the engine as a durable timer | Exactly one actor per key, so the timer is armed once rather than once per replica | Survives actor sleep, restart, upgrade, and crash | + +## Idempotency + +A scheduled action can fire more than you expect: a crash between doing the work and re-arming can cause the action to run again, and because schedules cannot be cancelled, an action can fire for an entry that was already removed. Design handlers so a duplicate firing is harmless: + +- **Store a run marker in state**: Keep a `lastRunAt` timestamp or a sequence number in actor state and update it inside the action. On each firing, compute elapsed time since the marker and skip or batch accordingly. The idle world actor's `collectProduction` does this with `lastCollectedAt` and whole-interval batching. +- **Tombstone guard for cancelled entries**: The example's `triggerReminder` looks the reminder up in `c.state.reminders` first and returns with a warning if it is gone, so a fire-after-cancel is a safe no-op. +- **Keep work and marker updates in the same action**: Actor state writes are persisted with the action, so updating the marker in the same handler that does the work keeps the two consistent. + +## Topology + +| Topology | Use When | Example Key | +| --- | --- | --- | +| Singleton job actor | One global job such as a nightly report or cleanup pass | `job["daily-report"]` | +| Actor per scheduled entity | Per-user or per-resource timers such as reminders, trials, or billing periods | `reminder[userId]` | + +The Scheduling example uses a single shared `reminderActor["main"]` key for demo simplicity. For production reminder systems, prefer one actor per user so timers, state, and load are isolated per entity. See [Keys](/docs/actors/keys). + +## Reminder Service Example + +| Topic | Summary | +| --- | --- | +| Scheduling | One-shot timers armed with `c.schedule.after(delayMs, "triggerReminder", reminder.id)` or `c.schedule.at(timestamp, "triggerReminder", reminder.id)`. | +| State | JSON state holding `reminders` and `completedCount`; the scheduled action mutates state when it fires. | +| Events | `triggerReminder` broadcasts a `reminderTriggered` event to all connected clients. See [Events](/docs/actors/events). | +| Cancellation | `cancelReminder` only removes the reminder from state; the scheduled action may still fire and no-ops via a state lookup guard. | + +**Actors** + +- **Key**: `reminderActor["main"]` +- **Responsibility**: Stores reminders in persistent state, arms a future self-action per reminder via `c.schedule`, marks reminders completed when the scheduled action fires, and broadcasts `reminderTriggered` to connected clients. +- **Actions** + - `scheduleReminder` + - `scheduleReminderAt` + - `triggerReminder` + - `getReminders` + - `cancelReminder` + - `getStats` +- **Queues** + - None +- **State** + - JSON + - `reminders` + - `completedCount` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant R as reminderActor + participant E as Engine + + C->>R: scheduleReminder(message, delayMs) + R->>E: schedule.after(delayMs, triggerReminder, id) + Note over E: schedule persisted + alarm armed + R-->>C: reminder + Note over R: actor sleeps + E->>R: alarm fires, actor wakes + Note over R: triggerReminder(id) runs + R-->>C: reminderTriggered event + Note over R: recurring jobs re-arm here with schedule.after +``` + +## Security Checklist + +The example is intentionally open: any client can connect to the shared `["main"]` key and schedule or cancel anything. Treat all of the following as required extensions for production: + +- **Validate schedule inputs**: Clamp `delayMs` and `timestamp` from clients. Reject negative delays, timestamps in the past, and absurdly far-future deadlines, and bound message or payload sizes. +- **Never schedule client-chosen actions**: Expose specific actions like `scheduleReminder` that internally arm a fixed callback. Do not pass a client-supplied action name or unchecked args into `c.schedule`. +- **Authenticate and scope keys**: Add connection [authentication](/docs/actors/authentication) and use per-user actor keys instead of one global key, so users cannot read or cancel each other's schedules. +- **Prune completed entries**: The example's `reminders` array grows without bound. Remove or archive completed entries so state stays small. +- **Use stable IDs**: Generate entry IDs with `crypto.randomUUID()` rather than timestamp-plus-random strings. + +_Source doc path: /cookbook/cron-jobs_ diff --git a/.agents/skills/ai-agent/reference/cookbook/live-cursors.md b/.agents/skills/ai-agent/reference/cookbook/live-cursors.md new file mode 100644 index 0000000..71c94ab --- /dev/null +++ b/.agents/skills/ai-agent/reference/cookbook/live-cursors.md @@ -0,0 +1,152 @@ +# Live Cursors and Presence + +> Source: `src/content/cookbook/live-cursors.mdx` +> Canonical URL: https://rivet.dev/cookbook/live-cursors +> Description: Live cursors and multiplayer presence with Rivet Actors: per-connection cursor state, realtime updates over events or raw WebSockets, and throttling. + +--- +Patterns for building live cursors, multiplayer presence, and realtime cursor sharing with RivetKit. One room actor fans cursor positions out to every connected client, keyed per room with [actor keys](/docs/actors/keys). + +## Starter Code + +Start with one of the two working variants on GitHub. Both implement the same collaborative cursor canvas with persistent text labels; they differ only in transport. + +| Variant | Starter Code | Transport | Presence Storage | +| --- | --- | --- | --- | +| `cursors` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/cursors) | Typed [actions](/docs/actors/actions) and [events](/docs/actors/events) over the RivetKit connection | `connState` per connection | +| `cursors-raw-websocket` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/cursors-raw-websocket) | Raw [`onWebSocket` handler](/docs/actors/websocket-handler) with a custom JSON message protocol | Socket map in `createVars` | + +Use `cursors` by default: typed actions, typed events, and automatic connection tracking cover most apps with less code. Use `cursors-raw-websocket` when you need full control of the wire format, for example a custom JSON or binary protocol, or clients that do not use the RivetKit client library. + +## Connection State vs Persistent State + +Presence is ephemeral by definition. A cursor position is only meaningful while its connection is alive, so it belongs in per-connection storage, not in persistent actor state. Persistent state is reserved for data that must survive disconnects and actor restarts. + +| Data | Where It Lives | Why | +| --- | --- | --- | +| Cursor position | `connState` (`cursors`) or the `createVars` socket map (`cursors-raw-websocket`) | Scoped to one connection and discarded with it. Stale presence cannot accumulate in storage. | +| Text labels (`textLabels`) | Persistent actor `state` in both variants | Canvas content must survive disconnects and actor restarts. | + +In the `cursors` variant, `updateCursor` writes `c.conn.state.cursor` and `getRoomState` rebuilds the presence snapshot by iterating `c.conns.values()`, so the cursor map is always derived from live connections rather than stored. See [Connections](/docs/actors/connections) for `connState` and [State](/docs/actors/state) for persistence semantics. + +## Presence Lifecycle + +- **Join**: The `cursors-raw-websocket` variant pushes an `init` message with the current `{ cursors, textLabels }` snapshot as soon as a socket connects. The `cursors` variant has no explicit join broadcast; the client calls the `getRoomState` action once after connecting to seed its local maps, and peers first see a new user on that user's first `cursorMoved` broadcast. +- **Move**: Every `updateCursor` call writes the connection's presence entry, then broadcasts `cursorMoved` to all connections, including the sender. +- **Leave**: The `cursors` variant handles leave in `onDisconnect`, broadcasting `cursorRemoved` with the connection's last cursor. The raw variant does the same from the socket `close` listener, then deletes the session from the `vars.websockets` map. Clients delete that user from their local cursor map, so stale cursors disappear the moment a tab closes. + +See [Lifecycle](/docs/actors/lifecycle) for `onDisconnect` and `createVars`. + +## Update Throttling + +Neither example throttles. Both frontends send a cursor update on every raw `mousemove` event with no debounce or interval cap. That is fine for a demo, but a fast mouse on a high-refresh display can emit hundreds of events per second per user. The patterns below are recommended production hardening on top of the starter code, not something the examples implement. + +| Layer | Pattern | Guidance | +| --- | --- | --- | +| Client (smoothness) | Throttle to 20-30Hz | Sample the latest pointer position every 33-50ms and send only that. Drop intermediate moves, but always flush the final position so cursors settle at the true location. Interpolate between received positions on the rendering side. | +| Server (enforcement) | Per-connection rate limit | Track the last accepted update timestamp per connection and drop or coalesce updates arriving faster than your cap. Client throttles are cooperative; the actor is the enforcement boundary. | + +## Actors + +- **Key**: `cursorRoom[roomId]` (the frontend defaults `roomId` to `"general"`) +- **Responsibility**: Holds per-connection cursor presence in `connState`, persists shared text labels in actor state, and broadcasts cursor and text updates to all connections. +- **Actions** + - `updateCursor` + - `updateText` + - `removeText` + - `getRoomState` +- **Events** + - `cursorMoved` + - `cursorRemoved` + - `textUpdated` + - `textRemoved` +- **Queues** + - None +- **State** + - JSON + - `textLabels` (persistent) + - `connState.cursor` per connection (ephemeral) + +- **Key**: `cursorRoom[roomId]` (resolved via `client.cursorRoom.getOrCreate(roomId)`) +- **Responsibility**: Exposes a raw WebSocket endpoint, tracks live sockets and their cursors in a `createVars` map keyed by a `sessionId` query parameter, persists text labels, and manually fans JSON frames out to every socket. +- **Actions** + - `getOrCreate` (stub returning `{ status: "ok" }`; the frontend resolves the actor ID with the client handle's `getOrCreate(roomId).resolve()`, which creates the actor without dispatching this action) + - `getRoomState` +- **Queues** + - None +- **State** + - JSON + - `textLabels` (persistent) + - `vars.websockets` map of `sessionId` to socket and cursor (in-memory, lost on restart) + +The raw variant defines no RivetKit events. Its message names are `type` fields on raw JSON frames: + +| Direction | Message `type` | Payload | +| --- | --- | --- | +| Client to server | `updateCursor` | `{ userId, x, y }` | +| Client to server | `updateText` | `{ id, userId, text, x, y }` | +| Client to server | `removeText` | `{ id }` | +| Server to client | `init` | `{ cursors, textLabels }` snapshot on connect | +| Server to client | `cursorMoved`, `textUpdated`, `textRemoved`, `cursorRemoved` | The corresponding cursor, label, or ID payload | + +## Lifecycle + +### cursors (Actions + Events) + +```mermaid +sequenceDiagram + participant A as Client A + participant R as cursorRoom + participant B as Other Clients + + A->>R: connect via useActor (cursorRoom[roomId]) + A->>R: getRoomState() + R-->>A: {cursors, textLabels} + loop every mouse move + A->>R: updateCursor(userId, x, y) + Note over R: write c.conn.state.cursor + R-->>B: cursorMoved (broadcast) + end + A->>R: updateText(id, userId, text, x, y) + Note over R: upsert persistent state.textLabels + R-->>B: textUpdated (broadcast) + Note over A: tab closes + Note over R: onDisconnect reads conn.state.cursor + R-->>B: cursorRemoved (broadcast) +``` + +### cursors-raw-websocket + +```mermaid +sequenceDiagram + participant A as Client A + participant R as cursorRoom + participant B as Other Clients + + A->>R: getOrCreate(roomId).resolve() + R-->>A: actorId + A->>R: open WebSocket /gateway/{actorId}/websocket?sessionId=... + Note over R: close 1008 if sessionId is missing + Note over R: store socket in vars.websockets + R-->>A: init {cursors, textLabels} + loop every mouse move + A->>R: {type: "updateCursor"} frame + Note over R: update session cursor in vars + R-->>B: cursorMoved frame + end + Note over A: socket closes + R-->>B: cursorRemoved frame + Note over R: delete session from vars.websockets +``` + +## Security Checklist + +Both examples ship without authentication so the presence pattern stays readable. Everything below is recommended hardening for production, not behavior the examples implement. + +- **Identity**: Bind presence identity to the connection (`c.conn.id` in the actions variant, a server-generated session ID in the raw variant). Never trust a client-supplied `userId`; in the examples it is a random client-generated string, so any client can impersonate or remove any cursor. +- **Authorization**: Authorize label mutations by owner. In the examples, `updateText` accepts arbitrary `id` and `userId` arguments and `removeText` accepts an arbitrary `id`, so any client can edit or delete any label. +- **Input validation**: Clamp `x` and `y` to canvas bounds, cap text label length, and cap the total `textLabels` count so persistent state cannot grow unbounded. +- **Rate limiting**: Enforce a per-connection cap on `updateCursor` (for example 30Hz) and on label writes, as described in [Update Throttling](#update-throttling). +- **Protocol strictness (raw variant)**: Validate message shape before use and close the socket on malformed JSON instead of logging and continuing. Reject duplicate `sessionId` values rather than silently overwriting another session's socket entry. + +_Source doc path: /cookbook/live-cursors_ diff --git a/.agents/skills/ai-agent/reference/cookbook/multiplayer-game.md b/.agents/skills/ai-agent/reference/cookbook/multiplayer-game.md new file mode 100644 index 0000000..425b113 --- /dev/null +++ b/.agents/skills/ai-agent/reference/cookbook/multiplayer-game.md @@ -0,0 +1,713 @@ +# Multiplayer Game + +> Source: `src/content/cookbook/multiplayer-game.mdx` +> Canonical URL: https://rivet.dev/cookbook/multiplayer-game +> Description: Pragmatic patterns for building multiplayer games: matchmaking, tick loops, realtime state, interest management, and validation. + +--- +Patterns for building multiplayer games with RivetKit, intended as a practical checklist you can adapt per genre. + +## Starter Code + +Start with one of the working examples on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/) and adapt it to your game. Do not start from scratch for matchmaking and lifecycle flows. + +| Game Classification | Starter Code | Common Examples | +| --- | --- | --- | +| Battle Royale | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/battle-royale/) | Fortnite, Apex Legends, PUBG, Warzone | +| Arena | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/arena/) | Call of Duty TDM/FFA, Halo Slayer, Counter-Strike casual, VALORANT unrated, Overwatch Quick Play, Rocket League | +| IO Style | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/io-style/) | Agar.io, Slither.io, surviv.io | +| Open World | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/open-world/) | Minecraft survival servers, Rust-like worlds, MMO zone/chunk worlds | +| Party | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/party/) | Fall Guys private lobbies, custom game rooms, social party sessions | +| Physics 2D | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-2d/) | Top-down physics brawlers, 2D arena games, platform fighters | +| Physics 3D | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-3d/) | Physics sandbox sessions, 3D arena games, movement playgrounds | +| Ranked | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/ranked/) | Chess ladders, competitive card games, duel arena ranked queues | +| Turn-Based | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/turn-based/) | Chess correspondence, Words With Friends, async board games | +| Idle | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/idle/) | Cookie Clicker, Idle Miner Tycoon, Adventure Capitalist | + +## Server Simulation + +### Game Loop And Tick Rates + +| Pattern | Use When | Implementation Guidance | +| --- | --- | --- | +| Fixed realtime loop | Battle Royale, Arena, IO Style, Open World, Ranked | Run in `run` with `sleep(tickMs)` and exit on `c.aborted`. | +| Action-driven updates | Party, Turn-Based | Mutate and broadcast only on actions/events rather than scheduled ticks. | +| Coarse offline progression | Any mode with idle progression | Use `c.schedule.after(...)` with coarse windows (for example 5 to 15 minutes) and apply catch-up from elapsed wall clock time. | + +### Physics + +Start with custom kinematic logic for simple games. Switch to a full physics engine when you need joints, stacked bodies, high collision density, or complex shapes (rotated polygons, capsules, convex hulls, triangle meshes). + +Pick one engine per simulation. Keep frontend-only libs out of backend simulation paths and treat server state as authoritative. + +| Dimension | Primary Engine | Fallback Engines | Example Code | +| --- | --- | --- | --- | +| 2D | `@dimforge/rapier2d` | `planck-js`, `matter-js` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-2d/) | +| 3D | `@dimforge/rapier3d` | `cannon-es`, `ammo.js` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-3d/) | + +### Spatial Indexing + +For non-physics spatial queries, use a dedicated index instead of naive `O(n^2)` checks: + +| Index Type | Recommendation | +| --- | --- | +| AABB index | For AOI, visibility, and non-collider entities, use `rbush` for dynamic sets or `flatbush` for static-ish sets. | +| Point index | For nearest-neighbor or within-radius queries, use `d3-quadtree`. | + +## Networking & State Sync + +### Netcode + +| Model | When To Use | Implementation | +| --- | --- | --- | +| Hybrid (client movement, server combat) | Shooters, action sports, ranked duels | Client owns movement and sends capped-rate position updates. Server validates for anti-cheat. Combat (projectiles, hits, damage) is fully server-authoritative. | +| Server-authoritative with interpolation | IO Style, persistent worlds | Client sends input commands. Server simulates on fixed ticks and publishes authoritative snapshots. Client interpolates between snapshots. | +| Server-authoritative (basic logic) | Turn-based, event-driven | Server validates and applies discrete actions (turns, phase transitions, votes). Client displays confirmed state. | + +### Realtime Data Model + +- **Snapshots and diffs**: Publish state as events. Send a full snapshot on join/resync, then per-tick diffs for regular updates. +- **Batch per tick**: Keep events small and typed. Batch high-frequency updates per tick. +- **Avoid UI framework state for game updates**: Use `requestAnimationFrame` or a Canvas/Three.js loop for simulation, not React state. Reserve UI framework state for menus, HUD, and forms. +- **Broadcast vs per-connection**: Use `c.broadcast(...)` for shared updates and `conn.send(...)` for private/per-player data. + +### Shared Simulation Logic + +Shared simulation logic runs on both the client and the server. For example, an `applyInput(state, input, dt)` function that integrates velocity and clamps to world bounds can run on the client for prediction and on the server for validation. + +- **Hybrid modes**: Client runs shared movement as primary authority, server runs it for anti-cheat validation. +- **Server-authoritative modes**: Client uses shared logic for interpolation and prediction only. +- **Keep it pure**: Movement integration, input transforms, collision helpers, and constants only. +- **Put shared code in `src/shared/`**: Keep deterministic helpers in `src/shared/sim/*` with no side effects. + +### Interest Management + +Control what each client receives to reduce bandwidth and prevent information leaks. + +#### Per-Player Replication Filters + +- **Filter by relevance**: Send each client only state relevant to that player (proximity, line-of-sight, team, or game phase). +- **Shooters and action games**: Limit replication by proximity and optional field-of-view checks. +- **Server-side only**: Clients should never receive data they should not see. + +#### Sharded Worlds + +- **Partition large worlds**: Use chunk actors keyed by `worldId:chunkX:chunkY`. +- **Subscribe to nearby chunks**: Clients connect only to nearby partitions (for example a 3x3 chunk window). +- **Use sparingly**: Only when the world is large and state-heavy (sandbox builders, MMOs), not as a default for small matches. + +## Backend Infrastructure + +### Persistence + +- **In-memory state**: Best for realtime game state that changes every tick (player positions, inputs, match phase, scores). +- **SQLite (`rivetkit/db`)**: Better for large or table-like state that needs queries, indexes, or long-term persistence (tiles, inventory, matchmaking pools). Serialize DB work through a queue since multiple actions can hit the same actor concurrently. + +### Matchmaking Patterns + +Common building blocks used across the architecture patterns below. + +#### Actor Topology + +| Primitive | Use When | Typical Ownership | +| --- | --- | --- | +| `matchmaker["main"]` + `match[matchId]` | Session-based multiplayer (battle royale, arena, ranked, party, turn-based) | Matchmaker owns discovery/assignment. Match owns lifecycle and gameplay state. | +| `chunk[worldId,chunkX,chunkY]` | Large continuous worlds that need sharding | Each chunk owns local players, chunk state, and local simulation. | +| `world[playerId]` | Per-player progression loops (idle/solo world state) | Per-player resources, buildings, timers, and progression. | +| `player[username]` | Canonical profile/rating reused across matches | Durable player stats (for example rating and win/loss). | +| `leaderboard["main"]` | Shared rankings across many matches/players | Global ordered score rows and top lists. | + +#### Queueing Strategy + +- Multiple players can hit the matchmaker at the same time, so actions like find/create, queue/unqueue, and close need to be serialized through actor queues to avoid races. +- Match-local actions (gameplay, scoring) do not need queueing unless they write back to the matchmaker. + +## Security And Anti-Cheat + +Start with this baseline, then harden further for competitive or high-risk environments. + +### Baseline Checklist + +- **Identity**: Use `c.conn.id` as the authoritative transport identity. Treat `playerId`/`username` in params as untrusted input and bind through server-issued assignment/join tickets. +- **Authorization**: Validate the caller is allowed to mutate the target entity (room membership, turn ownership, host-only actions). +- **Input validation**: Clamp sizes/lengths, validate enums, and validate usernames (length, allowed chars, avoid unbounded Unicode). +- **Rate limiting**: Per-connection rate limits for spammy actions (chat, join/leave, fire, movement updates). +- **State integrity**: Server recomputes derived state (scores, win conditions, placements). Never allow client-authoritative changes to inventory/currency/leaderboard totals. + +### Movement Validation + +For any mode with client-authoritative movement (hybrid flows), clients may send position/rotation updates for smoothness, but the server must: + +- Enforce max delta per update (speed cap) based on elapsed time. +- Reject or clamp teleports. +- Enforce world bounds (and basic collision if applicable). +- Rate limit update frequency (for example 20Hz max). + +## Architecture Patterns + +Each game type below starts with a quick summary table, then details actors and lifecycle. + +### Battle Royale + +| Topic | Summary | +| --- | --- | +| Matchmaking | Immediate routing to the fullest non-started lobby (oldest tie-break); players wait in lobby until capacity, then the match starts. | +| Netcode | Hybrid. Client owns movement, camera, and local prediction. Server owns zone state, projectiles, hit resolution, eliminations, loot, and final placement. | +| Tick Rate | 10 ticks/sec (`100ms`) with a fixed loop for zone progression and lifecycle checks. | +| Physics | Client owns movement with server anti-cheat validation; projectiles, hits, and damage are server-authoritative. Use `@dimforge/rapier3d` for 3D or `@dimforge/rapier2d` for top-down 2D. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Finds or creates lobbies, tracks pending reservations, and maintains occupancy. +- **Actions** + - `findMatch` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **Queues** + - `findMatch` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **State** + - SQLite + - `matches` + - `pending_players` + - `player_count` includes connected and pending players + +- **Key**: `match[matchId]` +- **Responsibility**: Runs lobby/live/finished phases, owns player state, zone progression, and eliminations. +- **Actions** + - `connect` + - Movement and combat actions +- **Queues** + - None +- **State** + - JSON + - `phase` + - `players` + - `zone` + - `eliminations` + - `snapshot data` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant M as match + + C->>MM: findMatch() + alt no open lobby + MM->>M: create(matchId) + end + MM-->>C: {matchId, playerId} + C->>M: connect(playerId) + M->>MM: pendingPlayerConnected(matchId, playerId) + MM-->>M: accepted + Note over M: lobby countdown -> live + M-->>C: snapshot + shoot events + M->>MM: closeMatch(matchId) +``` + +### Arena + +| Topic | Summary | +| --- | --- | +| Matchmaking | Mode-based fixed-capacity queues (`duo`, `squad`, `ffa`) that build only full matches and pre-assign teams (except FFA). | +| Netcode | Hybrid. Client owns movement plus prediction and smoothing. Server owns team or FFA assignment, projectiles, hit resolution, phase transitions, and scoring. | +| Tick Rate | 20 ticks/sec (`50ms`) with a tighter loop for live team and FFA snapshots. | +| Physics | Medium to high intensity; client movement with server validation and server-authoritative combat/entities. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Runs mode queues, builds full matches, assigns teams, and publishes assignments. +- **Actions** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **Queues** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **State** + - SQLite + - `player_pool` + - `matches` + - `assignments` keyed by connection and player + +- **Key**: `match[matchId]` +- **Responsibility**: Runs match phases and in-match player/team state for score and win conditions. +- **Actions** + - `connect` + - Gameplay actions +- **Queues** + - None +- **State** + - JSON + - `phase` + - `players` + - `team assignments` + - `score and win state` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant M as match + + C->>MM: queueForMatch(mode) + Note over MM: enqueue in player_pool + Note over MM: fill when capacity reached + MM->>M: create(matchId, assignments) + Note over MM: persist assignments + MM-->>C: assignmentReady + C->>M: connect(playerId) + Note over M: waiting -> live when all players connect + M->>MM: matchCompleted(matchId) +``` + +### IO Style + +| Topic | Summary | +| --- | --- | +| Matchmaking | Open-lobby routing to the fullest room below capacity; room counts are heartbeated and new lobbies are auto-created when needed. | +| Netcode | Server-authoritative with interpolation. Client sends input intents and interpolates. Server owns movement, bounds, room membership, and canonical snapshots. | +| Tick Rate | 10 ticks/sec (`100ms`) with lightweight periodic room snapshots. | +| Physics | Low to medium intensity; server-authoritative kinematic movement, escalating to a physics engine only when collisions get complex. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Routes players into the fullest open lobby and tracks reservations and occupancy. +- **Actions** + - `findLobby` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **Queues** + - `findLobby` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **State** + - SQLite + - `matches` + - `pending_players` + - Occupancy includes pending reservations + +- **Key**: `match[matchId]` +- **Responsibility**: Runs per-match movement simulation and broadcasts snapshots. +- **Actions** + - `connect` + - `setInput` +- **Queues** + - None +- **State** + - JSON + - `players` + - `inputs` + - `movement state` + - `snapshot cache` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant M as match + + C->>MM: findLobby() + alt no open lobby + MM->>M: create(matchId) + end + MM-->>C: {matchId, playerId} + C->>M: connect(playerId) + M->>MM: pendingPlayerConnected(matchId, playerId) + MM-->>M: accepted + Note over M: fixed tick simulation + M-->>C: snapshot events + M->>MM: closeMatch(matchId) +``` + +### Open World + +| Topic | Summary | +| --- | --- | +| Matchmaking | Client-driven chunk routing from world coordinates, with nearby chunk windows preloaded via adjacent chunk connections. | +| Netcode | Hybrid for sandbox (client movement with validation) or server-authoritative for MMO-like flows. Server owns chunk routing, persistence, and canonical world state. | +| Tick Rate | 10 ticks/sec per chunk actor (`100ms`), so load scales with active chunks. | +| Physics | Medium to high at scale; chunk-local simulation can be server-authoritative (MMO-like) or client movement with server validation (sandbox-like). | + +**Actors** + +- **Key**: `chunk[worldId,chunkX,chunkY]` +- **Responsibility**: Owns chunk-local players, blocks, movement tick, and chunk membership. +- **Actions** + - `connect` + - `enterChunk` + - `addPlayer` + - `setInput` + - `leaveChunk` + - `removePlayer` +- **Queues** + - None +- **State** + - JSON + - `connections` + - `players` + - `blocks` scoped to one chunk key + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant CH as chunk + + Note over C: resolve chunk keys from world position + loop each visible chunk + C->>CH: connect(worldId, chunkX, chunkY, playerId) + Note over CH: store connection metadata + end + C->>CH: enterChunk/addPlayer + loop movement updates + C->>CH: setInput(...) + CH-->>C: snapshot + end + C->>CH: leaveChunk/removePlayer or disconnect + Note over CH: remove membership and metadata +``` + +### Party + +| Topic | Summary | +| --- | --- | +| Matchmaking | Host-created private party flow using party codes and explicit joins. | +| Netcode | Server-authoritative (basic logic). Server owns membership, host permissions, and phase transitions. | +| Tick Rate | No continuous tick; updates are event-driven (`join`, `start`, `finish`). | +| Physics | Low intensity for lobby-first flows; usually no dedicated physics or indexing unless you add realtime mini-games. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Handles party create/join flow, validates join tickets, and tracks party size. +- **Actions** + - `createParty` + - `joinParty` + - `verifyJoin` + - `updatePartySize` + - `closeParty` +- **Queues** + - `createParty` + - `joinParty` + - `verifyJoin` + - `updatePartySize` + - `closeParty` +- **State** + - SQLite + - `parties` + - `join_tickets` for party lookup and join validation + +- **Key**: `match[matchId]` +- **Responsibility**: Owns party members, host role, ready flags, and phase transitions. +- **Actions** + - `connect` + - `startGame` + - `finishGame` +- **Queues** + - None +- **State** + - JSON + - `members` + - `host` + - `ready state` + - `phase` + - `party events` + +**Lifecycle** + +### Host Flow + +```mermaid +sequenceDiagram + participant H as Host Client + participant MM as matchmaker + participant M as match + + H->>MM: createParty() + MM-->>H: {matchId, partyCode, playerId, joinToken} + H->>M: connect(playerId, joinToken) + M->>MM: verifyJoin(...) + MM-->>M: allowed + M->>MM: updatePartySize(playerCount) + H->>M: startGame() / finishGame() + M->>MM: closeParty(matchId) +``` + +### Joiner Flow + +```mermaid +sequenceDiagram + participant J as Joiner Client + participant MM as matchmaker + participant M as match + + J->>MM: joinParty(partyCode) + MM-->>J: {matchId, playerId, joinToken} + J->>M: connect(playerId, joinToken) + M->>MM: verifyJoin(...) + MM-->>M: allowed / denied + M->>MM: updatePartySize(playerCount) +``` + +### Ranked + +| Topic | Summary | +| --- | --- | +| Matchmaking | ELO-based queue pairing with a widening search window as wait time increases. | +| Netcode | Hybrid. Client owns movement with local prediction and interpolation. Server owns projectiles, hit resolution, match results, and rating updates. | +| Tick Rate | 20 ticks/sec (`50ms`) with fixed live ticks for deterministic pacing and broadcast cadence. | +| Physics | Medium to high intensity; client movement with server validation and server-authoritative combat/hit resolution. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Runs rating-based queueing, pairing, assignment persistence, and completion fanout. +- **Actions** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **Queues** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **State** + - SQLite + - `player_pool` + - `matches` + - `assignments` with rating window and connection scoping + +- **Key**: `match[matchId]` +- **Responsibility**: Runs ranked match phase, score, and winner reporting. +- **Actions** + - `connect` + - Gameplay actions +- **Queues** + - None +- **State** + - JSON + - `phase` + - `players` + - `score` + - `winner` + - `completion payload` + +- **Key**: `player[username]` +- **Responsibility**: Stores canonical player MMR and win/loss profile. +- **Actions** + - `initialize` + - `getRating` + - `applyMatchResult` +- **Queues** + - None +- **State** + - JSON + - `rating` + - `wins` + - `losses` + - `match counters` + +- **Key**: `leaderboard["main"]` +- **Responsibility**: Stores and serves top-ranked players. +- **Actions** + - `updatePlayer` +- **Queues** + - None +- **State** + - SQLite + - Leaderboard score rows + - Top-list ordering + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant P as player + participant M as match + participant LB as leaderboard + + C->>MM: queueForMatch(username) + MM->>P: initialize/getRating + P-->>MM: rating + Note over MM: store queue row + retry pairing + MM->>M: create(matchId, assigned players) + MM-->>C: assignmentReady + C->>M: connect(username) + M->>MM: matchCompleted(...) + MM->>P: applyMatchResult(...) + MM->>LB: updatePlayer(...) + Note over MM: remove matches + assignments rows +``` + +### Turn-Based + +| Topic | Summary | +| --- | --- | +| Matchmaking | Async private-invite and public-queue pairing in the same pattern. | +| Netcode | Server-authoritative (basic logic). Client can draft moves before submit. Server owns turn ownership, committed move log, turn order, and completion state. | +| Tick Rate | No continuous tick; move submission and turn transitions drive updates. | +| Physics | Very low intensity; no realtime physics loop, just discrete rules validation. Indexing is optional and mostly for board or query convenience at scale. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Handles private invite and public queue pairing for async matches. +- **Actions** + - `createGame` + - `joinByCode` + - `queueForMatch` + - `unqueueForMatch` + - `closeMatch` +- **Queues** + - `createGame` + - `joinByCode` + - `queueForMatch` + - `unqueueForMatch` + - `closeMatch` +- **State** + - SQLite + - `matches` + - `player_pool` + - `assignments` for invite and queue mapping + +- **Key**: `match[matchId]` +- **Responsibility**: Owns board state, turn order, move validation, and final result. +- **Actions** + - `connect` + - `makeMove` +- **Queues** + - None +- **State** + - JSON + - `board` + - `turns` + - `players` + - `connection presence` + - `result` + +**Lifecycle** + +### Public Queue + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant MM as matchmaker + participant M as match + + A->>MM: queueForMatch() + B->>MM: queueForMatch() + Note over MM: pair first two queued players + MM->>M: create(matchId) + seed X/O players + MM-->>A: assignment/match info + MM-->>B: assignment/match info + A->>M: connect(playerId) + B->>M: connect(playerId) + A->>M: makeMove() + B->>M: makeMove() + opt all players disconnected for timeout + Note over M: destroy after idle timeout + end + M->>MM: closeMatch(matchId) +``` + +### Private Invite + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant MM as matchmaker + participant M as match + + A->>MM: createGame() + MM-->>A: {matchId, playerId, inviteCode} + B->>MM: joinByCode(inviteCode) + MM->>M: create(matchId) + seed X/O players + MM-->>A: assignment/match info + MM-->>B: assignment/match info + A->>M: connect(playerId) + B->>M: connect(playerId) + A->>M: makeMove() + B->>M: makeMove() + M->>MM: closeMatch(matchId) +``` + +### Idle + +| Topic | Summary | +| --- | --- | +| Matchmaking | No matchmaker; each player uses a direct per-player actor and a shared leaderboard actor. | +| Netcode | Server-authoritative (basic logic). Client owns UI and build intent. Server owns resources, production rates, building validation, and leaderboard totals. | +| Tick Rate | No continuous tick; use `c.schedule.after(...)` for coarse intervals and compute offline catch-up from elapsed wall time. | +| Physics | None for standard idle loops; transitions are discrete (`build`, `collect`, `upgrade`) and do not need spatial indexing. | + +**Actors** + +- **Key**: `world[playerId]` +- **Responsibility**: Owns one player's progression, buildings, production scheduling, and state updates. +- **Actions** + - `initialize` + - `build` + - `collectProduction` +- **Queues** + - None +- **State** + - JSON + - Per-player buildings + - `resources` + - `timers` + - `progression state` + +- **Key**: `leaderboard["main"]` +- **Responsibility**: Stores global scores and serves leaderboard updates. +- **Actions** + - `updateScore` +- **Queues** + - `updateScore` +- **State** + - SQLite + - `scores` table keyed by player + - Current leaderboard totals + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant W as world + participant LB as leaderboard + + C->>W: getOrCreate(playerId) + initialize() + Note over W: seed state + schedule collection + W-->>C: stateUpdate + loop gameplay loop + C->>W: build() / collectProduction() + W->>LB: updateScore(...) + Note over LB: upsert scores + LB-->>C: leaderboardUpdate + W-->>C: stateUpdate + end +``` + +_Source doc path: /cookbook/multiplayer-game_ diff --git a/.agents/skills/ai-agent/reference/cookbook/per-tenant-database.md b/.agents/skills/ai-agent/reference/cookbook/per-tenant-database.md new file mode 100644 index 0000000..e3c5616 --- /dev/null +++ b/.agents/skills/ai-agent/reference/cookbook/per-tenant-database.md @@ -0,0 +1,119 @@ +# Database per Tenant + +> Source: `src/content/cookbook/per-tenant-database.mdx` +> Canonical URL: https://rivet.dev/cookbook/per-tenant-database +> Description: Multi-tenant data isolation with one Rivet Actor per tenant: the actor key is the tenant id, so each tenant gets its own isolated dataset and migrations. + +--- +Patterns for database-per-tenant architectures with RivetKit. Instead of one shared database with a `tenant_id` column on every table, each tenant gets its own Rivet Actor, and that actor owns the tenant's entire dataset. + +## Starter Code + +Start with the working example on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/per-tenant-database) and adapt it. The example stores each tenant's dataset in JSON actor state and serves a React dashboard with live event updates. + +| Topic | Summary | +| --- | --- | +| Isolation | One `companyDatabase` actor per tenant, keyed by company name. Switching tenants swaps the entire dataset. | +| State | JSON actor state holding `employees` and `projects` arrays plus timestamps. No SQLite, no queues, no scheduling. | +| Realtime | Every write action mutates state, then broadcasts a typed event (`employeeAdded`, `projectAdded`) to all connected clients of that tenant. | +| Auth | None. The sign-in screen is cosmetic. Production guidance is in the [security checklist](#security-checklist). | + +## The Isolation Model + +The actor key is the tenant id. The client connects with `useActor({ name: "companyDatabase", key: [companyName] })` and the actor reads `c.key[0]` in `createState` to seed that tenant's dataset. This gives you: + +- **One actor per tenant**: `companyDatabase[tenantId]` addresses exactly one actor instance. Two tenants can never share an actor. +- **One dataset per tenant**: All reads and writes go through that actor's [state](/docs/actors/state), so there is no shared table with a `tenant_id` column to filter incorrectly. Cross-tenant leaks require constructing the wrong key, not forgetting a `WHERE` clause. +- **No key injection**: Keys are arrays, not interpolated strings. `key: [tenantId]` cannot be escaped the way `"tenant:" + tenantId` string concatenation can. See [Keys](/docs/actors/keys). + +The example's test ([tests/per-tenant-database.test.ts](https://github.com/rivet-dev/rivet/tree/main/examples/per-tenant-database/tests/per-tenant-database.test.ts)) proves the isolation: data written to `companyDatabase["Alpha Co"]` never appears in `companyDatabase["Beta Co"]`. + +## Choosing a State Backend + +The example uses plain JSON actor state. The same key-equals-tenant model works with any actor state backend. + +| Backend | Use When | Docs | Working Code | +| --- | --- | --- | --- | +| JSON actor state | Small datasets, simple reads, whole dataset fits comfortably in memory. What the example uses. | [State](/docs/actors/state) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/per-tenant-database) | +| Actor SQLite (`rivetkit/db`) | Tables, indexes, SQL queries, larger-than-memory data, per-tenant relational schema. | [SQLite](/docs/actors/sqlite) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/kitchen-sink/src/actors/state/sqlite-raw.ts) | +| SQLite + Drizzle | Typed schema, query builder, and generated migration files on top of actor SQLite. | [SQLite + Drizzle](/docs/actors/sqlite-drizzle) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/kitchen-sink/src/actors/state/sqlite-drizzle/) | + +With either SQLite option, every tenant gets its own embedded SQLite database, since the database is scoped to the actor and the actor is scoped to the tenant. + +## Migrations + +The per-tenant example has no migrations because JSON state has no schema. When you adopt SQLite, migrations run per tenant database: + +- **Raw SQL**: `db({ onMigrate })` runs your migration SQL inside a SQLite savepoint before the actor serves traffic. If `onMigrate` throws, all migration SQL rolls back atomically and the actor does not start. See [SQLite](/docs/actors/sqlite). +- **Drizzle**: `drizzle-kit` generates migration files from your typed schema, and `db({ schema, migrations })` applies them when the actor wakes. See [SQLite + Drizzle](/docs/actors/sqlite-drizzle). + +Because each tenant has its own database, migrations roll out per actor as each tenant's actor wakes, rather than as one large migration against a shared database. + +## Tenant Id Must Come From Auth + +The example's sign-in is cosmetic: the client picks any company string and that string becomes the actor key, so any visitor can read and write any tenant's data. Do not ship this. As a required production extension (not implemented by the example): + +- Derive the tenant id from a verified credential, such as a JWT claim, never from user input. +- Validate the credential against `c.key` in `onBeforeConnect` (pass/fail) or `createConnState` (store the verified user on connection state). See [Authentication](/docs/actors/authentication) and [Connections](/docs/actors/connections). +- Add per-action permission checks on top of connection-level auth. See [Access Control](/docs/actors/access-control). + +## Actors + +- **Key**: `companyDatabase[companyName]` (single-element array key; `c.key[0]` is the company name) +- **Responsibility**: One actor per tenant. Holds that company's employees and projects in persistent state, serves reads and writes via actions, and broadcasts mutations to connected clients. +- **Actions** + - `addEmployee` + - `listEmployees` + - `addProject` + - `listProjects` + - `getStats` +- **Queues** + - None +- **Events** + - `employeeAdded` + - `projectAdded` +- **State** + - JSON + - `company_name` + - `employees` + - `projects` + - `created_at` + - `updated_at` + +Every write action follows the same mutate-then-broadcast shape: push the record into `c.state`, bump `updated_at`, broadcast the typed event, return the record. See [Actions](/docs/actors/actions) and [Events](/docs/actors/events). + +## Lifecycle + +```mermaid +sequenceDiagram + participant A as Tenant A client + participant DA as companyDatabase A + participant B as Tenant B client + participant DB as companyDatabase B + + Note over A: authenticate and derive tenant id + A->>DA: connect with key [tenantA] + Note over DA: createState seeds company_name, employees, projects + A->>DA: listEmployees() + listProjects() + getStats() + A->>DA: addEmployee(name, role) + DA-->>A: employeeAdded event + B->>DB: connect with key [tenantB] + Note over DB: separate actor, separate dataset + B->>DB: listEmployees() + DB-->>B: tenant B data only +``` + +In the example, the "authenticate" step is a free-text company picker. The rest of the flow matches the diagram: `createState` seeds the dataset on first creation, the dashboard loads with `listEmployees`, `listProjects`, and `getStats`, and every connected client of the same tenant receives `employeeAdded` and `projectAdded` events. + +## Security Checklist + +The example ships with none of these. Apply all of them before production. + +- **Tenant identity**: Derive the tenant id from a verified JWT claim, never from a client-supplied string. +- **Connection validation**: In `onBeforeConnect` or `createConnState`, verify the credential's tenant claim matches `c.key` and reject mismatches. +- **Per-action authorization**: Check the caller's role before mutating actions (`addEmployee`, `addProject`), not just at connect time. See [Access Control](/docs/actors/access-control). +- **Input validation**: Clamp name and role lengths and validate enums. The example only trims input and substitutes fallback defaults. +- **Key construction**: Always pass the tenant id as an array element (`key: [tenantId]`). Never interpolate tenant ids into key strings, and never build keys from one tenant's input to address another tenant's actor. +- **Growth limits**: As a recommended extension, cap or paginate the `employees` and `projects` arrays. The example lets them grow unboundedly in JSON state; move to [SQLite](/docs/actors/sqlite) when the dataset outgrows memory. + +_Source doc path: /cookbook/per-tenant-database_ diff --git a/.agents/skills/ai-agent/reference/cookbook/vpc-air-gapped.md b/.agents/skills/ai-agent/reference/cookbook/vpc-air-gapped.md new file mode 100644 index 0000000..f7d87a3 --- /dev/null +++ b/.agents/skills/ai-agent/reference/cookbook/vpc-air-gapped.md @@ -0,0 +1,136 @@ +# Deploying Rivet in a VPC or Air-Gapped Network + +> Source: `src/content/cookbook/vpc-air-gapped.mdx` +> Canonical URL: https://rivet.dev/cookbook/vpc-air-gapped +> Description: Run Rivet entirely inside your own perimeter: single-binary or Docker Compose install, file system storage with no database infrastructure, and no outbound telemetry by default. + +--- +Patterns for running self-hosted Rivet inside a private network: a VPC without internet egress, an on-premises rack, or a fully air-gapped environment. The engine is one service, the recommended single-node storage backend is the local file system, and the engine makes no outbound connections by default. Self-hosting is the only Rivet deployment model that supports air-gapped networks; see the [Self-Hosting Overview](/docs/self-hosting) for the full comparison with BYOC. + +## What Runs Inside the Perimeter + +A self-hosted deployment has three components, all of which live inside your network: + +| Component | Role | Inside the perimeter | +| --- | --- | --- | +| Your backend | Your application server, including the runner that executes actor code | Yes | +| Rivet Engine | Orchestration service that manages actor lifecycle, routes messages, and serves the dashboard and APIs | Yes | +| Storage | Persistence for actor state. Local file system for single-node, PostgreSQL or FoundationDB for multi-node | Yes | + +There is no license server, no Rivet Cloud account, and no callback to `rivet.dev`. Clients inside the perimeter reach actors through the engine's gateway over your private network. See [Architecture](/docs/self-hosting#architecture). + +## Single-Binary Install + +The engine compiles to a single `rivet-engine` binary. Build it from source outside the perimeter, then copy the binary across the boundary: + +```bash +git clone https://github.com/rivet-dev/rivet.git +cd rivet +cargo build --release -p rivet-engine +# Copy target/release/rivet-engine into the perimeter. +``` + +Prebuilt binaries are coming soon; see [Installing Rivet Engine](/docs/self-hosting/install) for current options. + +Run it with the file system backend, which stores everything on local disk and is the production-ready choice for single-node deployments. The [File System](/docs/self-hosting/filesystem) docs list air-gapped environments as a primary use case because it needs no database infrastructure: + +```bash +RIVET__database__file_system__path="/var/lib/rivet/data" ./rivet-engine +``` + +Configuration can also come from files. The engine discovers config at `/etc/rivet/config.json` on Linux (JSON, JSON5, JSONC, YAML, and YML are all supported), and `--config` overrides the path. Environment variables use the `RIVET__` prefix with `__` as the separator. See [Configuration](/docs/self-hosting/configuration). + +The engine serves its own dashboard on port `6420`, so inspection and namespace management work with nothing but a browser inside the perimeter. + +## Docker Compose Deployment + +For Docker hosts without registry access, move the engine image across the boundary the standard way: + +```bash +# Outside the perimeter. +docker pull rivetdev/engine:latest +docker save rivetdev/engine:latest -o rivet-engine.tar +# Inside the perimeter. +docker load -i rivet-engine.tar +``` + +Then run the engine and your app together in one Compose file: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - rivet-data:/data + environment: + RIVET__FILE_SYSTEM__PATH: "/data" + restart: unless-stopped + + my-app: + build: . + environment: + RIVET_ENDPOINT: "http://default:admin@rivet-engine:6420" + depends_on: + - rivet-engine + restart: unless-stopped + +volumes: + rivet-data: +``` + +`RIVET_ENDPOINT` uses the format `http://namespace:token@host:port` and tells your app to connect to the engine as a runner instead of running standalone. After both services start, register your runner with the engine through the dashboard or its API. The full walkthrough, including PostgreSQL setup for multi-node deployments, is in [Docker Compose](/docs/self-hosting/docker-compose). + +## No Outbound Telemetry + +The engine exports traces and metrics only when you opt in with OpenTelemetry. Export is disabled unless `RIVET_OTEL_ENABLED=1` is set, and the export target defaults to a local collector at `http://localhost:4317`. With no configuration, nothing crosses the perimeter. + +When you want observability, keep it inside the network: + +- Set `RIVET_OTEL_ENABLED=1` and point `RIVET_OTEL_GRPC_ENDPOINT` at a collector you run inside the perimeter. +- Adjust `RIVET_OTEL_SAMPLER_RATIO` to control trace sampling. +- Use the engine's health endpoint for liveness and readiness probes. + +See the [Production Checklist](/docs/self-hosting/production-checklist) for monitoring guidance. + +## Embedding Rivet in a Customer's Environment + +If you ship software that runs inside your customers' VPCs, the same setup turns Rivet into an internal component of your product rather than a service your customers must reach over the internet: + +- **Ship the engine next to your app.** Add `rivetdev/engine` to the Compose file or chart you already deliver. Your app finds it over the private network via `RIVET_ENDPOINT`, so one artifact deploys the whole stack. +- **One namespace per install.** The endpoint URL carries the namespace and token (`http://namespace:token@host:port`), so a single image works across customer deployments. See [Endpoints](/docs/general/endpoints). +- **Generate a strong admin token per install.** Replace the default token and keep it server-side. Never include the admin token in `RIVET_PUBLIC_ENDPOINT` or anywhere clients can read it. +- **Public endpoint only when needed.** `RIVET_PUBLIC_ENDPOINT` with a public (`pk_`) token is only required when browser clients connect to actors in [serverless runtime mode](/docs/general/runtime-modes). Backend-only deployments can skip it entirely. +- **TLS at the customer's edge.** Terminate TLS with the customer's reverse proxy or load balancer in front of the engine. + +## Scaling Past One Node + +| Backend | Use when | Status | +| --- | --- | --- | +| [File System](/docs/self-hosting/filesystem) (RocksDB-based) | Single-node deployments, including air-gapped installs | Production-ready, single node only | +| [PostgreSQL](/docs/self-hosting/postgres) | Multi-node deployments | Recommended for multi-node today, but experimental | +| FoundationDB | Largest production deployments | [Enterprise](/sales) | + +For multi-node deployments, run two or more engine nodes behind a load balancer and add NATS for pub/sub, which replaces the default PostgreSQL `LISTEN`/`NOTIFY` path at high throughput. Neither is needed for a single-node file system install. See the [Production Checklist](/docs/self-hosting/production-checklist). + +## Perimeter Checklist + +- **Admin token**: Generate a strong, random token for engine authentication and verify it is not exposed to clients. +- **TLS termination**: Encrypt connections to the engine via a reverse proxy or load balancer. +- **No public exposure**: Keep port `6420` reachable only from inside the perimeter unless clients outside it genuinely need access. +- **Health checks**: Configure liveness and readiness probes against the engine health endpoint. +- **Telemetry**: Leave OpenTelemetry export off, or point it at a collector inside the network. +- **Backups**: With the file system backend, back up the data directory. With PostgreSQL, configure automated backups and failover. + +## Full Configuration + +- [Self-Hosting Overview](/docs/self-hosting) for architecture and the self-host vs BYOC comparison +- [Installing Rivet Engine](/docs/self-hosting/install) for Docker, binary, and source installs +- [Docker Container](/docs/self-hosting/docker-container) and [Docker Compose](/docs/self-hosting/docker-compose) for container deployments +- [Kubernetes](/docs/self-hosting/kubernetes) for cluster deployments +- [Configuration](/docs/self-hosting/configuration) for every option and the full JSON schema +- [Endpoints](/docs/general/endpoints) for connecting your backend and clients +- [Production Checklist](/docs/self-hosting/production-checklist) before going live + +_Source doc path: /cookbook/vpc-air-gapped_ diff --git a/.agents/skills/ai-agent/reference/deploy/aws-ecs.md b/.agents/skills/ai-agent/reference/deploy/aws-ecs.md new file mode 100644 index 0000000..ab381ce --- /dev/null +++ b/.agents/skills/ai-agent/reference/deploy/aws-ecs.md @@ -0,0 +1,13 @@ +# Deploying to AWS ECS + +> Source: `src/content/docs/deploy/aws-ecs.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/aws-ecs +> Description: Run your backend on Amazon ECS with Fargate. + +--- +See the [AWS ECS template](https://github.com/rivet-dev/template-aws-ecs) for deployment instructions: + +- [Deploy with Terraform](https://github.com/rivet-dev/template-aws-ecs#option-a-deploy-with-terraform) +- [Deploy with AWS CLI](https://github.com/rivet-dev/template-aws-ecs#option-b-deploy-with-aws-cli) + +_Source doc path: /docs/deploy/aws-ecs_ diff --git a/.agents/skills/ai-agent/reference/deploy/aws-lambda.md b/.agents/skills/ai-agent/reference/deploy/aws-lambda.md new file mode 100644 index 0000000..f1327cc --- /dev/null +++ b/.agents/skills/ai-agent/reference/deploy/aws-lambda.md @@ -0,0 +1,10 @@ +# Deploy To Amazon Web Services Lambda + +> Source: `src/content/docs/deploy/aws-lambda.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/aws-lambda +> Description: _AWS Lambda is coming soon_ + +--- + + +_Source doc path: /docs/deploy/aws-lambda_ diff --git a/.agents/skills/ai-agent/reference/deploy/cloudflare.md b/.agents/skills/ai-agent/reference/deploy/cloudflare.md new file mode 100644 index 0000000..970078e --- /dev/null +++ b/.agents/skills/ai-agent/reference/deploy/cloudflare.md @@ -0,0 +1,53 @@ +# Deploying to Cloudflare Workers + +> Source: `src/content/docs/deploy/cloudflare.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/cloudflare +> Description: Deploy an existing Rivet project to Cloudflare Workers. + +--- +This guide covers deploying an existing Rivet project to Cloudflare Workers. + +## Prerequisites + +- [Cloudflare account](https://dash.cloudflare.com/) +- [`wrangler`](https://developers.cloudflare.com/workers/wrangler/) configured for your account +- A Rivet namespace from the [Rivet Dashboard](https://dashboard.rivet.dev/) or a self-hosted Rivet Engine + +## Steps + +### Set up your project + +Follow the [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) to set up your project locally. + +### Configure Wrangler + +Set your Rivet connection values as Worker variables. Find `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` in the [Rivet Dashboard](https://dashboard.rivet.dev/) under **Settings → Namespace → Advanced → Backend Configuration** and copy them in. + +```toml wrangler.toml +name = "rivetkit-cloudflare" +main = "src/index.ts" +compatibility_date = "2025-04-01" +compatibility_flags = ["nodejs_compat"] + +[vars] +RIVET_ENDPOINT = "https://your-namespace:sk_...@api.rivet.dev" +RIVET_PUBLIC_ENDPOINT = "https://your-namespace@api.rivet.dev" +``` + +### Deploy + +```sh +npx wrangler deploy +``` + +### Register the Serverless Runner URL + +After deploy, set the Worker URL with the `/api/rivet` path as the serverless runner URL in Rivet. + +## Related + +- [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) +- [Deploying to Supabase Functions](/docs/deploy/supabase) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/deploy/cloudflare_ diff --git a/.agents/skills/ai-agent/reference/deploy/container-runner.md b/.agents/skills/ai-agent/reference/deploy/container-runner.md new file mode 100644 index 0000000..7bb0c5a --- /dev/null +++ b/.agents/skills/ai-agent/reference/deploy/container-runner.md @@ -0,0 +1,95 @@ +# Container Runner + +> Source: `src/content/docs/deploy/container-runner.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/container-runner +> Description: Run any containerized server as a Rivet Actor. + +--- +The container runner (`rivet-container-runner`) is an adapter for running arbitrary containers as Rivet Actors. Use it for non-RivetKit workloads such as Unity or Godot dedicated game servers and batch jobs like FFmpeg transcoding. + +## Steps + +### Prerequisites + +- A containerized server (a Unity or Godot dedicated server, a plain Node process, or any HTTP/WebSocket server) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) +- Docker running locally + +### Install in Your Container + +Download the static binary from Rivet's release artifacts in your Dockerfile and set it as the entrypoint, passing your server's launch command after `--`: + +```dockerfile @nocheck +FROM debian:bookworm-slim +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl && rm -rf /var/lib/apt/lists/* + +# Install the Rivet container runner. +RUN curl -fsSL https://releases.rivet.dev/rivet/latest/container-runner/rivet-container-runner-x86_64-unknown-linux-musl \ + -o /usr/local/bin/rivet-container-runner \ + && chmod +x /usr/local/bin/rivet-container-runner + +# Your server binary and assets. +COPY build/ /game/ +WORKDIR /game + +ENTRYPOINT ["rivet-container-runner", "--", "./GameServer", "-batchmode", "-nographics", "-logFile", "-"] +``` + +Artifacts are published for `x86_64-unknown-linux-musl` and `aarch64-unknown-linux-musl`. The binaries are fully static, so they run in any Linux base image, including `scratch`. Pin a version by replacing `latest` with a release version, for example `https://releases.rivet.dev/rivet/2.3.3/container-runner/rivet-container-runner-x86_64-unknown-linux-musl`. + +### Deploy + +Deploy the image to [Rivet Compute](/docs/deploy/rivet-compute) with the CLI. For game servers, configure the pool with one actor per instance: + +```bash +npx @rivetkit/cli deploy \ + --token "$RIVET_CLOUD_TOKEN" \ + --instance-request-concurrency 1 \ + --dockerfile Dockerfile +``` + +### Create Actors and Connect Clients + +Create actors against the pool's runner (`default`) and connect clients through the gateway URL shown in the dashboard. WebSocket clients connect at the bare gateway URL with the `rivet` WebSocket subprotocol. + +## How It Works + +1. The engine cold-starts your container and calls `POST /api/rivet/start` on the port it injects as `RIVET_PORT`. +2. The runner spawns your server as a child process with `PORT` set to the child port, waits for the port to open, and reports the actor as running. +3. Gateway traffic for the actor arrives over Rivet's tunnel and is proxied to `127.0.0.1:`. WebSocket clients connect at the bare gateway URL with the `rivet` WebSocket subprotocol. Raw HTTP reaches the child under the `/request/*` prefix on the actor surface (the prefix is stripped before proxying); other paths are reserved for the runtime's own endpoints. +4. Child stdout and stderr are re-emitted with an `[actorId=... key=...]` prefix so actor logs are attributed in the dashboard. +5. When an actor stops, the runner sends its child `SIGTERM`, escalates to `SIGKILL` after a grace period, and exits the process once no actors remain. + +## Configuration + +All flags can also be set through environment variables: + +| Flag | Environment variable | Default | Description | +| --- | --- | --- | --- | +| `--port` | `RIVET_PORT` / `PORT` | `8080` | Serverless front-door HTTP port. Rivet Compute injects `RIVET_PORT` automatically. | +| `--child-port` | `CHILD_PORT` | `7770` | First local child port; each actor's child gets the next free port at or above this, exported to the child as `PORT`. | +| `--actor-name` | `RIVET_ACTOR_NAME` | `game` | Actor name this runner serves. | +| `--runner-version` | `RIVET_RUNNER_VERSION` | `1` | Version reported to the engine, used to drain old runners on deploy. | +| `--base-path` | `RIVET_SERVERLESS_BASE_PATH` | `/api/rivet` | Base path the engine calls for serverless start. | +| `--stop-grace-secs` | `RIVET_STOP_GRACE_SECS` | `25` | `SIGTERM` to `SIGKILL` grace period when stopping the child. Capped to a few seconds when the platform itself is reclaiming the instance, so shutdown fits inside the platform's own kill window. | +| `--readiness-timeout-secs` | `RIVET_READINESS_TIMEOUT_SECS` | `30` | How long to wait for the child's port to open before failing the start. | + +### Per-Actor Input + +The actor's `input` payload can override the launch spec per actor. All fields are optional and fall back to the entrypoint command. RivetKit clients pass this object directly; when creating actors through the raw engine API, encode it as CBOR before base64-encoding the `input` field: + +```json +{ + "command": ["./GameServer", "-batchmode"], + "args": ["-extra-flag"], + "env": { "MATCH_MODE": "ranked" } +} +``` + +`command` replaces the entrypoint command template, `args` are appended to it, and `env` adds environment variables for the child. + +## Source and Examples + +The runner and a full end-to-end example, including a Unity FishNet demo project and a local test harness, live in the Rivet repository under [`container-runner/`](https://github.com/rivet-dev/rivet/tree/main/container-runner). + +_Source doc path: /docs/deploy/container-runner_ diff --git a/.agents/skills/ai-agent/reference/deploy/freestyle.md b/.agents/skills/ai-agent/reference/deploy/freestyle.md new file mode 100644 index 0000000..eb6ed57 --- /dev/null +++ b/.agents/skills/ai-agent/reference/deploy/freestyle.md @@ -0,0 +1,136 @@ +# Deploying to Freestyle + +> Source: `src/content/docs/deploy/freestyle.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/freestyle +> Description: Deploy RivetKit app to Freestyle.sh, a cloud platform for running AI-generated code with built-in security and scalability. + +--- +Freestyle provides built-in security for running untrusted AI-generated code, making it ideal for AI agent applications. Using Rivet, it is easy to deploy your vibe-coded or user-provided RivetKit backends straight to Freestyle. + +- [Freestyle + Rivet](https://github.com/rivet-dev/rivet/tree/main/examples/freestyle) — Complete example of deploying RivetKit app to Freestyle.sh. + +## Setup + +### Install packages + +Install RivetKit and Hono and create your registry: + +```bash +npm install rivetkit hono +``` + +### Configure serverless driver + +Update your server code to run the registry serverless with Deno. + +```typescript index.ts @hide +import { actor, setup } from "rivetkit"; + +export const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, x: number) => { + c.state.count += x; + return c.state.count; + }, + }, +}); + +export const registry = setup({ + use: { counter }, +}); +registry.start(); +``` + +```typescript server.ts @nocheck +import { registry } from "./index"; + +// Freestyle uses Deno under the hood for web deployments +// @ts-ignore Deno is a Freestyle runtime global +Deno.serve((request: Request) => registry.handler(request)); +``` + +The `Deno.serve` API is provided by Freestyle's runtime environment. The `@ts-ignore` comment suppresses TypeScript errors for this platform-specific API. + +### Deploy to Freestyle + +Deploy your application to Freestyle with the correct configuration. Create a deployment script or add this to your existing deployment process: + +```typescript @nocheck +const FREESTYLE_DOMAIN = "my-domain.style.dev"; // Change to your desired Freestyle domain + +declare const freestyle: any; +declare const buildDir: string; + +const res = await freestyle.deployWeb(buildDir, { + envVars: { + FREESTYLE_ENDPOINT: `https://${FREESTYLE_DOMAIN}`, + RIVET_RUNNER_KIND: "serverless", + // For self-hosted instances: + // RIVET_ENDPOINT: "http://127.0.0.1:6420", + RIVET_ENDPOINT: "api.rivet.dev", + }, + timeout: 60 * 5, // Increases max request lifetime on the runner + entrypoint: "server.ts", // File which starts serverless runner + domains: [FREESTYLE_DOMAIN], + build: false, +}); +``` + +Details on `buildDir` and other settings are available on [Freestyle docs](https://docs.freestyle.sh/web/web). + +Run this deployment script to push your application to Freestyle. + +**Deployment Configuration:** + +- `timeout: 60 * 5` - Set timeout to 5 minutes for actor operations - it's important to keep this high +- `entrypoint: "server.ts"` - Entry point file with your serverless setup +- `domains` - Your Freestyle domain(s) +- `build: false` - Disable build if you're pre-building your assets + +### Configure runner + +Update the runner configuration on the Rivet side to connect with your Freestyle deployment. Create a configuration script and run it after your Freestyle deployment is live: + +```typescript @nocheck +import { RivetClient } from "@rivetkit/engine-api-full"; + +const rivet = new RivetClient({ + environment: "https://api.rivet.dev", + token: process.env.RIVET_API_TOKEN, +}); + +const FREESTYLE_DOMAIN = "my-domain.style.dev"; // Change to your desired Freestyle domain +const RIVET_NAMESPACE = "my-rivet-namespace"; // Change to your Rivet namespace + +await rivet.runnerConfigsUpsert("freestyle-runner", { + namespace: RIVET_NAMESPACE, + datacenters: { + default: { + serverless: { + url: `https://${FREESTYLE_DOMAIN}/start`, + runnersMargin: 1, + minRunners: 1, + maxRunners: 1, + slotsPerRunner: 1, + // Must be shorter than Freestyle request `timeout` config + requestLifespan: 60 * 5 - 5, + }, + }, + }, +}); +``` + +Execute this configuration script to register your Freestyle deployment with Rivet. + +**Runner Configuration:** + +- `url` - Freestyle deployment URL with `/start` endpoint +- `runnersMargin` - Buffer of runners to maintain +- `minRunners/maxRunners` - Scaling limits +- `slotsPerRunner` - Concurrent actors per runner +- `requestLifespan` - Request timeout (slightly less than Freestyle timeout) + +Once executed, Rivet will be connected to your Freestyle serverless instance. + +_Source doc path: /docs/deploy/freestyle_ diff --git a/.agents/skills/ai-agent/reference/deploy/gcp-cloud-run.md b/.agents/skills/ai-agent/reference/deploy/gcp-cloud-run.md new file mode 100644 index 0000000..f140950 --- /dev/null +++ b/.agents/skills/ai-agent/reference/deploy/gcp-cloud-run.md @@ -0,0 +1,74 @@ +# Deploying to Google Cloud Run + +> Source: `src/content/docs/deploy/gcp-cloud-run.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/gcp-cloud-run +> Description: Deploy your RivetKit app to Google Cloud Run. + +--- +## Steps + +### Prerequisites + +- Google Cloud project with Cloud Run and Artifact Registry enabled +- `gcloud` CLI authenticated (`gcloud auth login`) and project set (`gcloud config set project YOUR_PROJECT`) +- Artifact Registry repository or Container Registry enabled +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Package Your App + +Create a `Dockerfile` in your project root: + +```dockerfile +FROM node:20-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev +COPY . . +ENV PORT=8080 +CMD ["node", "server.js"] +``` + +### Build and Push the Image + +Use Cloud Build to build and push the image. Replace the region and repository with your own. + +```bash +gcloud builds submit --tag us-central1-docker.pkg.dev/YOUR_PROJECT/rivetkit-app/rivetkit-app:latest +``` + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select Google Cloud Run as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables to use when deploying. + +### Deploy to Cloud Run + +Deploy the service to Cloud Run, passing the Rivet environment variables. Adjust the region and image as needed. + +```bash +gcloud run deploy rivetkit-app \ + --image us-central1-docker.pkg.dev/YOUR_PROJECT/rivetkit-app/rivetkit-app:latest \ + --region us-central1 \ + --allow-unauthenticated \ + --min-instances 1 \ + --set-env-vars RIVET_ENDPOINT=,RIVET_PUBLIC_ENDPOINT= +``` + +### Connect to Rivet + +1. After deployment, note the service URL (e.g. `https://rivetkit-app-xxxxx-uc.a.run.app`) +2. On the Rivet dashboard, paste your URL with the `/api/rivet` path into the connect form (e.g. `https://rivetkit-app-xxxxx-uc.a.run.app/api/rivet`) +3. Click "Done" + +### Verify + +Confirm the service is running: + +```bash +gcloud run services describe rivetkit-app --region us-central1 --format 'value(status.conditions[?type="Ready"].status)' +``` + +Your app should appear as connected on the Rivet dashboard once the service reports ready. + +_Source doc path: /docs/deploy/gcp-cloud-run_ diff --git a/.agents/skills/ai-agent/reference/deploy/hetzner.md b/.agents/skills/ai-agent/reference/deploy/hetzner.md new file mode 100644 index 0000000..5b61024 --- /dev/null +++ b/.agents/skills/ai-agent/reference/deploy/hetzner.md @@ -0,0 +1,10 @@ +# Deploying to Hetzner + +> Source: `src/content/docs/deploy/hetzner.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/hetzner +> Description: Please see the VM & Bare Metal guide. + +--- + + +_Source doc path: /docs/deploy/hetzner_ diff --git a/.agents/skills/ai-agent/reference/deploy/kubernetes.md b/.agents/skills/ai-agent/reference/deploy/kubernetes.md new file mode 100644 index 0000000..43496a9 --- /dev/null +++ b/.agents/skills/ai-agent/reference/deploy/kubernetes.md @@ -0,0 +1,121 @@ +# Deploying to Kubernetes + +> Source: `src/content/docs/deploy/kubernetes.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/kubernetes +> Description: Deploy your RivetKit app to any Kubernetes cluster. + +--- +## Steps + +### Prerequisites + +- A Kubernetes cluster with `kubectl` access (EKS, GKE, k3s, etc.) +- Container registry credentials (Docker Hub, GHCR, GCR, etc.) +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Package Your App + +Create a `Dockerfile` in your project root: + +```dockerfile +FROM node:20-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev +COPY . . +ENV PORT=8080 +CMD ["node", "server.js"] +``` + +### Build and Push the Image + +```bash +docker build -t registry.example.com/your-team/rivetkit-app:latest . +docker push registry.example.com/your-team/rivetkit-app:latest +``` + +Replace `registry.example.com/your-team` with your registry path. Auth with `docker login` first if needed. + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select Kubernetes as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables. + +Create a `rivetkit-secrets.yaml` for your environment variables: + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: rivetkit-secrets +type: Opaque +stringData: + RIVET_ENDPOINT: + RIVET_PUBLIC_ENDPOINT: +``` + +### Deploy to Kubernetes + +Create a `deployment.yaml`: + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: rivetkit-app +spec: + replicas: 1 + selector: + matchLabels: + app: rivetkit-app + template: + metadata: + labels: + app: rivetkit-app + spec: + # Allow enough time for actors to gracefully stop on SIGTERM. + # The runner waits up to 30m for actors to finish. + # Add buffer for runner shutdown overhead after actors stop. + # See: /docs/actors/versions#graceful-shutdown-sigterm + terminationGracePeriodSeconds: 2100 + containers: + - name: rivetkit-app + image: registry.example.com/your-team/rivetkit-app:latest + envFrom: + - secretRef: + name: rivetkit-secrets +``` + +Apply both manifests: + +```bash +kubectl apply -f rivetkit-secrets.yaml +kubectl apply -f deployment.yaml +``` + +### Connect to Rivet + +1. Add a `Service` and Ingress to expose your app externally (e.g. `my-app.example.com`) +2. On the Rivet dashboard, paste your domain with the `/api/rivet` path into the connect form (e.g. `https://my-app.example.com/api/rivet`) +3. Click "Done" + +Rivet envoys connect to your app over long-lived WebSockets, and your app's clients (browsers, SDKs) do the same. Default Ingress and cloud load balancer idle timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +Raise the idle / read / send timeout on every Ingress and load balancer in front of your app to at least 1 hour (`3600` seconds). Examples: + +- **NGINX Ingress**: `nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"` and `nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"` +- **AWS Load Balancer Controller (ALB)**: `alb.ingress.kubernetes.io/load-balancer-attributes: idle_timeout.timeout_seconds=3600` +- **GCE Ingress (GKE)**: set `timeoutSec: 3600` on the `BackendConfig` referenced by the Service. + +### Verify + +Check that the pod is running: + +```bash +kubectl get pods -l app=rivetkit-app +``` + +Your app should appear as connected on the Rivet dashboard once the pod is ready. + +_Source doc path: /docs/deploy/kubernetes_ diff --git a/.agents/skills/ai-agent/reference/deploy/railway.md b/.agents/skills/ai-agent/reference/deploy/railway.md new file mode 100644 index 0000000..640ac37 --- /dev/null +++ b/.agents/skills/ai-agent/reference/deploy/railway.md @@ -0,0 +1,45 @@ +# Deploying to Railway + +> Source: `src/content/docs/deploy/railway.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/railway +> Description: Deploy your RivetKit app to Railway. + +--- +## Steps + +### Prerequisites + +- [Railway account](https://railway.app) +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Deploy to Railway + +1. Connect your GitHub account to Railway +2. Select your repository containing your RivetKit app +3. Railway will automatically detect and deploy your app + +See [Railway's deployment docs](https://docs.railway.com/quick-start) for more details. + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select Railway as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables to add to your Railway service. + +See [Railway's environment variables docs](https://docs.railway.com/guides/variables#service-variables) for more details. + +### Connect to Rivet + +1. In your Railway project, go to **Settings > Networking** +2. Click **Create Custom Domain** then **Create Domain** to generate a Railway domain (e.g. `my-app.railway.app`) +3. On the Rivet dashboard, paste your domain with the `/api/rivet` path into the connect form (e.g. `https://my-app.railway.app/api/rivet`) +4. Click "Done" + +Rivet envoys connect to your app over long-lived WebSockets, and your app's clients (browsers, SDKs) do the same. Railway's HTTP proxy supports WebSockets, but if you front your app with your own reverse proxy (NGINX, Caddy, etc.) inside the Railway service, raise its idle / read timeout to at least 1 hour (`3600` seconds). Default proxy timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +### Configure Sleeping & Multi-Region (Optional) + +- [Enable App Sleeping](https://docs.railway.com/reference/app-sleeping) to reduce costs when idle +- [Configure Multi-Region](https://docs.railway.com/reference/deployment-regions) to deploy closer to your users + +_Source doc path: /docs/deploy/railway_ diff --git a/.agents/skills/ai-agent/reference/deploy/rivet-compute.md b/.agents/skills/ai-agent/reference/deploy/rivet-compute.md new file mode 100644 index 0000000..69507aa --- /dev/null +++ b/.agents/skills/ai-agent/reference/deploy/rivet-compute.md @@ -0,0 +1,144 @@ +# Deploying to Rivet Compute + +> Source: `src/content/docs/deploy/rivet-compute.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/rivet-compute +> Description: Run your backend on Rivet Compute. + +--- +Using an AI coding agent? Open **Connect** on the [Rivet dashboard](https://dashboard.rivet.dev), select **Rivet Cloud**, and paste the one-shot prompt into your agent and have it connect with Rivet Compute for you. + +## Steps + +### Prerequisites + +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- A [Rivet Cloud](https://dashboard.rivet.dev) account and project +- Docker running locally + +### Create a Dockerfile + +Add a `Dockerfile` to your project root that builds and runs your RivetKit server: + +```dockerfile @nocheck +FROM node:24-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev +COPY . . +CMD ["node", "src/server.js"] +``` + +### Get Your Cloud Token + +1. Open the [Rivet dashboard](https://dashboard.rivet.dev) and navigate to your project +2. Click **Connect** and select **Rivet Cloud** +3. Copy the **`RIVET_CLOUD_TOKEN`** value shown + +### Deploy + +Run the deploy command from your project root. The token is saved to `~/.rivet/credentials`, so later deploys can omit it. + +```bash +npx @rivetkit/cli deploy --token cloud_api_xxxxx +``` + +The CLI resolves your project from the token, builds and pushes your Docker image to Rivet's built-in registry, upserts the managed pool, and prints the deployment URL on stdout when the pool is ready. + +### Optionally Add CI + +After local deploys work, install the GitHub Actions workflow that deploys on every push and pull request: + +```bash +npx @rivetkit/cli setup-ci +``` + +This writes `.github/workflows/rivet-deploy.yml`. Add your token as a repository secret to enable it: + +```bash +gh secret set RIVET_CLOUD_TOKEN +``` + +The workflow creates production and pull-request namespaces, posts preview links, and cleans up PR namespaces when pull requests close. See the [CLI reference](/docs/cli) for all commands. + +### Monitor Deployment + +The dashboard shows live status as Rivet Compute provisions your backend: + +| Status | Description | +| --- | --- | +| Initializing | Starting the runtime environment | +| Deploying | Pulling and launching your container | +| Binding | Connecting the runner to the network | +| Ready | Deployment complete | + +Once the status reaches **Ready**, your backend is live and actors are available for connections. + +If you are an agent monitoring the deployment via API rather than the dashboard, poll the managed-pool endpoint on the Cloud API. + +The `RIVET_CLOUD_TOKEN` secret is a `cloud_api_*` management token scoped to the Cloud API at `cloud-api.rivet.dev`. Use it for `Authorization: Bearer ...` against the Cloud API. Do not confuse it with a `pk_*` publishable key, which is scoped to the Rivet Engine API at `api.rivet.dev` and will 401 against this endpoint. + +Substitute `$CLOUD_API_URL` (typically `https://cloud-api.rivet.dev`), `$PROJECT`, `$ORG`, `$CLOUD_NAMESPACE`, and `$CLOUD_TOKEN`. + +Poll every 5 seconds until `status` is `ready`. Stop and investigate if `status` is `error`. + +```bash +curl -s "$CLOUD_API_URL/projects/$PROJECT/namespaces/$CLOUD_NAMESPACE/managed-pools/default?org=$ORG" -H "Authorization: Bearer $CLOUD_TOKEN" +``` + +## Checking Logs + +Use the CLI to read your deployment's logs. By default `rivet logs` prints the last 100 lines from the `production` namespace, oldest to newest, then exits. + +```bash +npx @rivetkit/cli logs +``` + +The CLI resolves your token the same way `deploy` does (the `--token` flag, then the `RIVET_CLOUD_TOKEN` environment variable, then `~/.rivet/credentials`). + +### Follow logs live + +Pass `--follow` (`-f`) to stream new logs as they arrive instead of fetching history: + +```bash +npx @rivetkit/cli logs --follow +``` + +Each formatted line is printed as ` [] `: + +``` +2026-06-16T18:26:51.160Z [INFO] eu-central-1 server listening on port 3000 +2026-06-17T11:24:20.425Z [ERROR] us-east-1 failed to connect to upstream +``` + +A few examples: + +```bash +# Last 200 lines from a specific namespace +npx @rivetkit/cli logs --namespace production -n 200 + +# Live tail, only lines containing "error" +npx @rivetkit/cli logs --follow --contains error + +# JSON output piped to jq +npx @rivetkit/cli logs -n 50 --json | jq . +``` + +## Troubleshooting + +If the status stays in **Initializing** for more than a few minutes, verify that: + +- The `RIVET_CLOUD_TOKEN` secret is correctly set in your GitHub repository +- The GitHub Actions workflow completed without errors — check the run logs + +If the status shows **Error**, check that your container starts successfully and does not exit immediately (you can check this with container logs). Common causes: + +- The server file is not calling `registry.start()` +- A runtime crash on startup — test the image locally with `docker run` +- The server is not listening on the `RIVET_PORT` environment variable (RivetKit reads `RIVET_PORT`, defaulting to `3000`) + +## Pricing + +You are billed for the compute resources your deployment uses while it is running. + +_Source doc path: /docs/deploy/rivet-compute_ diff --git a/.agents/skills/ai-agent/reference/deploy/supabase.md b/.agents/skills/ai-agent/reference/deploy/supabase.md new file mode 100644 index 0000000..fa98436 --- /dev/null +++ b/.agents/skills/ai-agent/reference/deploy/supabase.md @@ -0,0 +1,50 @@ +# Deploying to Supabase Functions + +> Source: `src/content/docs/deploy/supabase.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/supabase +> Description: Deploy an existing Rivet project to Supabase Edge Functions. + +--- +This guide covers deploying an existing Rivet project to Supabase Edge Functions. + +## Prerequisites + +- [Supabase project](https://supabase.com/) +- [Supabase CLI](https://supabase.com/docs/guides/cli) configured for your project +- A Rivet namespace from the [Rivet Dashboard](https://dashboard.rivet.dev/) or a self-hosted Rivet Engine + +## Steps + +### Set up your project + +Follow the [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) to set up your project locally. + +### Set Secrets + +Set your Rivet connection values as Supabase secrets. Find `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` in the [Rivet Dashboard](https://dashboard.rivet.dev/) under **Settings → Namespace → Advanced → Backend Configuration** and copy them in. + +```sh +npx supabase secrets set \ + RIVET_ENDPOINT=https://your-namespace:sk_...@api.rivet.dev \ + RIVET_PUBLIC_ENDPOINT=https://your-namespace@api.rivet.dev +``` + +### Deploy + +Make sure the function has the `deno.json` import map from the [quickstart](/docs/actors/quickstart/supabase) that points `rivetkit` at `@rivetkit/supabase`. It keeps the deploy to the WebAssembly runtime; without it the deploy pulls Rivet's native engine and fails with a `413` (request too large). + +```sh +npx supabase functions deploy rivet +``` + +### Register the Serverless Runner URL + +After deploy, set the function URL with the `/api/rivet` path as the serverless runner URL in Rivet. For a function named `rivet`, this is usually `https://your-project.functions.supabase.co/functions/v1/rivet/api/rivet`. + +## Related + +- [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) +- [Deploying to Cloudflare Workers](/docs/deploy/cloudflare) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/deploy/supabase_ diff --git a/.agents/skills/ai-agent/reference/deploy/vercel.md b/.agents/skills/ai-agent/reference/deploy/vercel.md new file mode 100644 index 0000000..e8b5ba3 --- /dev/null +++ b/.agents/skills/ai-agent/reference/deploy/vercel.md @@ -0,0 +1,138 @@ +# Deploying to Vercel + +> Source: `src/content/docs/deploy/vercel.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/vercel +> Description: Deploy your Next.js Rivet app to Vercel. + +--- +This guide assumes a Next.js app. + +## Prerequisites + +- [Vercel account](https://vercel.com/) +- A Next.js Rivet app +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +## Steps + +### Set up your project + +Follow the [Next.js Quickstart](/docs/actors/quickstart/next-js) to set up your project. + +### Verify Your Project Structure + +Your Next.js project should have the following structure: + +- `src/app/api/rivet/[...all]/route.ts`: RivetKit route handler +- `src/rivet/registry.ts`: Actor definitions and registry + +The route handler sets `maxDuration` to extend the serverless function timeout so long-lived actor requests are not cut short: + +```ts src/app/api/rivet/[...all]/route.ts @nocheck +import { toNextHandler } from "@rivetkit/next-js"; +import { registry } from "@/rivet/registry"; + +export const maxDuration = 300; + +export const { GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS } = toNextHandler(registry); +``` + +### Set Environment Variables + +Set `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` in your Vercel project settings using the URL auth format: + +``` +RIVET_ENDPOINT=https://my-namespace:sk_****@api.rivet.dev +RIVET_PUBLIC_ENDPOINT=https://my-namespace:pk_****@api.rivet.dev +``` + +`RIVET_ENDPOINT` uses the secret token for server-side access. `RIVET_PUBLIC_ENDPOINT` uses the publishable token and tells the metadata endpoint what connection info to provide to clients. + +### Deploy to Vercel + +1. Connect your GitHub repository to Vercel +2. Vercel will deploy your app + +### Configure Preview Deployments (Recommended) + +Add a GitHub action to automatically create isolated Rivet namespaces for each PR: + +1. Add these secrets to your GitHub repository: + - `RIVET_CLOUD_TOKEN`: Get from [Rivet Dashboard](https://dashboard.rivet.dev) → Settings → Advanced → Cloud API Tokens + - `VERCEL_TOKEN`: Get from [Vercel Account Settings](https://vercel.com/account/tokens) + +2. Create `.github/workflows/rivet-preview.yml`: + +```yaml +name: Rivet Preview + +on: + pull_request: + types: [opened, synchronize, reopened] + push: + branches: [main] + +concurrency: + group: rivet-preview-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + rivet-preview: + runs-on: ubuntu-latest + permissions: + pull-requests: write + steps: + - uses: rivet-dev/preview-namespace-action@v1 + with: + platform: vercel + rivet-token: ${{ secrets.RIVET_CLOUD_TOKEN }} + vercel-token: ${{ secrets.VERCEL_TOKEN }} +``` + +## Troubleshooting + +``` +Error: ENOENT: no such file or directory, mkdir '.../rivetkit/.../state' +``` + +**Cause:** The `RIVET_ENDPOINT` environment variable is not configured. RivetKit falls back to the file system driver, which fails in Vercel's read-only serverless environment. + +**Solution:** Ensure `RIVET_ENDPOINT` is set with your Rivet endpoint using the URL auth format: + +``` +RIVET_ENDPOINT=https://my-namespace:sk_****@api.rivet.dev +``` + +If using the [preview-namespace-action](https://github.com/rivet-dev/preview-namespace-action), this is configured automatically. + +The `/api/rivet/metadata` endpoint returns data but `clientEndpoint`, `clientNamespace`, and `clientToken` are missing. + +**Cause:** The `RIVET_PUBLIC_ENDPOINT` environment variable is not configured. This tells the metadata endpoint what connection info to provide to clients. + +**Solution:** Set `RIVET_PUBLIC_ENDPOINT` with the publishable token (for client access): + +``` +RIVET_PUBLIC_ENDPOINT=https://my-namespace:pk_****@api.rivet.dev +``` + +If using the [preview-namespace-action](https://github.com/rivet-dev/preview-namespace-action), this is configured automatically. + +Rivet fails to connect to your Vercel deployment with a 401 error mentioning "Authentication Required". + +**Cause:** [Vercel Deployment Protection](https://vercel.com/docs/security/deployment-protection) is blocking requests from Rivet. + +**Solution:** + +1. Create a bypass secret in your Vercel project settings +2. In Rivet, go to **Settings > Providers** +3. Click the three dots on your provider and select **Edit** +4. Click **Add Header** and add `x-vercel-protection-bypass` with your bypass secret + +If using the [preview-namespace-action](https://github.com/rivet-dev/preview-namespace-action), this is configured automatically. + +## Related + +- [Next.js Quickstart](/docs/actors/quickstart/next-js) +- [Self-Hosting](/docs/general/self-hosting) + +_Source doc path: /docs/deploy/vercel_ diff --git a/.agents/skills/ai-agent/reference/deploy/vm-and-bare-metal.md b/.agents/skills/ai-agent/reference/deploy/vm-and-bare-metal.md new file mode 100644 index 0000000..6a123f9 --- /dev/null +++ b/.agents/skills/ai-agent/reference/deploy/vm-and-bare-metal.md @@ -0,0 +1,96 @@ +# Deploying to VMs & Bare Metal + +> Source: `src/content/docs/deploy/vm-and-bare-metal.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/vm-and-bare-metal +> Description: Deploy your RivetKit app to any Linux VM or bare metal host. + +--- +## Steps + +### Prerequisites + +- A Linux VM or bare metal server with SSH access +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Upload Your App + +- Build your RivetKit app locally +- Copy the build output to your server (example): + +```bash +scp -r ./dist user@server:/opt/rivetkit-app +``` + +Place the files somewhere readable by the service user, such as `/opt/rivetkit-app`. + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select VM & Bare Metal as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables to use in the next step. + +### Create the systemd Service + +Create `/etc/systemd/system/rivetkit-app.service`: + +```ini +[Unit] +Description=RivetKit App +After=network.target + +[Service] +Type=simple +WorkingDirectory=/opt/rivetkit-app +ExecStart=/usr/bin/node server.js +Restart=on-failure +Environment=RIVET_ENDPOINT= +Environment=RIVET_PUBLIC_ENDPOINT= + +[Install] +WantedBy=multi-user.target +``` + +Replace the environment values with those from the Rivet dashboard and adjust paths to match your deployment. + +### Start the Service + +Reload systemd units and start the service: + +```bash +sudo systemctl daemon-reload +sudo systemctl enable --now rivetkit-app.service +``` + +### Connect to Rivet + +1. Ensure your server is accessible via a public URL (e.g. `https://my-app.example.com`) +2. On the Rivet dashboard, paste your URL with the `/api/rivet` path into the connect form (e.g. `https://my-app.example.com/api/rivet`) +3. Click "Done" + +If you front your app with a reverse proxy or load balancer (NGINX, HAProxy, Caddy, AWS ALB/NLB, etc.), raise its idle / read timeout to at least 1 hour (`3600` seconds). Rivet envoys connect to your app over long-lived WebSockets, and clients (browsers, SDKs) do the same. Default proxy timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +Examples: + +- **NGINX**: `proxy_read_timeout 3600s;` and `proxy_send_timeout 3600s;` in the relevant `location` block. +- **HAProxy**: `timeout client 1h` and `timeout server 1h` in the matching frontend / backend. +- **AWS ALB / NLB**: set the load balancer attribute `idle_timeout.timeout_seconds = 3600`. + +## Operating + +### Restart + +Restart the service after deploying new builds or environment changes: + +```bash +sudo systemctl restart rivetkit-app.service +``` + +### Logs + +Follow realtime logs when debugging: + +```bash +sudo journalctl -u rivetkit-app.service -f +``` + +_Source doc path: /docs/deploy/vm-and-bare-metal_ diff --git a/.agents/skills/ai-agent/reference/general/actor-configuration.md b/.agents/skills/ai-agent/reference/general/actor-configuration.md new file mode 100644 index 0000000..72bc6fd --- /dev/null +++ b/.agents/skills/ai-agent/reference/general/actor-configuration.md @@ -0,0 +1,19 @@ +# Actor Configuration + +> Source: `src/content/docs/general/actor-configuration.mdx` +> Canonical URL: https://rivet.dev/docs/general/actor-configuration +> Description: This page documents the configuration options available when defining a RivetKit actor. The actor configuration is passed to the `actor()` function. + +--- +## Basic Example + +## Configuration Reference + +## Related + +- [Registry Configuration](/docs/general/registry-configuration): Configure the RivetKit registry +- [State](/docs/actors/state): Managing actor state +- [Actions](/docs/actors/actions): Defining actor actions +- [Lifecycle](/docs/actors/lifecycle): Actor lifecycle hooks + +_Source doc path: /docs/general/actor-configuration_ diff --git a/.agents/skills/ai-agent/reference/general/architecture.md b/.agents/skills/ai-agent/reference/general/architecture.md new file mode 100644 index 0000000..3da2912 --- /dev/null +++ b/.agents/skills/ai-agent/reference/general/architecture.md @@ -0,0 +1,452 @@ +# Architecture + +> Source: `src/content/docs/general/architecture.mdx` +> Canonical URL: https://rivet.dev/docs/general/architecture +> Description: - rivetkit is the typescript library used for both local development & to connect your application to rivet - a rivetkit instance is called a "runner." you can run multiple runners to scale rivetkit horizontally. read omre about runners below. + +--- +## 3 ways of running + +### rivetkit + +- rivetkit is the typescript library used for both local development & to connect your application to rivet +- a rivetkit instance is called a "runner." you can run multiple runners to scale rivetkit horizontally. read more about runners below. + +#### local development + +- in local development, rivetkit provides a full actor environment for single-node deployments + +#### drivers + +- rivetkit supports multiple drivers. currently supports: file system (default in local dev), memory, rivet engine (used for rivet cloud & self-hosting), cloudflare durable objects (does not rely on rivet engine) +- drivers are very flexible to enable you to write your actors once and plug in to any system that fits your architecture adequately +- see the driver interface + - actordriver https://github.com/rivet-dev/rivet/blob/eeb01fc4d9ca0e06f2e740d267bd53280ca7330e/rivetkit-typescript/packages/rivetkit/src/actor/driver.ts + - managerdriver https://github.com/rivet-dev/rivet/blob/eeb01fc4d9ca0e06f2e740d267bd53280ca7330e/rivetkit-typescript/packages/rivetkit/src/manager/driver.ts + +### rivet cloud + +- provides multi-region and highest performance out of the box +- accessible at dashboard.rivet.dev and the api is avialble at api.rivet.dev + +### rivet self-hosted + +- available as a standalone rust binary or a docker contianer +- can be configured to persist to postgres or rocksdb +- can scale horiziontally across multipe nodes and can scale across multiple regions +- see [self-hosting docs](/docs/self-hosting/) + +## actors + +- Actors for long-lived processes with durable state, realtime, and hibernate when not in use. read more about actors at a high level at (link to actors/index) + +### actor-per-entity + +- actors are designed to have an actor-per-entity +- you can think about actors a bit like objects in object-oriented programming where each is responsible for their own state and expose methods (ie actions in our case) +- examples include + - actor per user + - actor per user session + - actor per document + - actor per game room + - actor per tenant + - actor per rate limit topic + +### architecting for scale + +- actors scale by: + - having isolated state to each actor that combines compute and storage for in-memory reads and writes + - communication is standardized based on actions & events + - scale horizontally +- read more about scaling at [Design Patterns](/docs/actors/design-patterns) + +### horizontal scaling + +- actors can run across multiple rivetkit runners. this is orchestrated by rivetkit itself. + +### lifecycle + +actors have create, destroy, wake, and sleep lifecycle hooks that you can implement to modify behavior. see the lifecycle docs for reference on actor lifecycel hook sequences + +### actor sleeping + +- actors sleep when not in use +- an actor is considered not in use when there are no active network connections to the actor (or the network connections are hibernatable websockets, see below) and there are no actions in flight +- actors have a sleep timeout (configured in `options.sleepTimeout`) that decides how long to keep the actor in memory with no recent activity +- sleep can be held off for the lifetime of a promise with `c.keepAwake(promise)` +- see the [sleeping docs](/docs/actors/lifecycle#sleeping) for full details + +### wake events + +- actors can wake to any of the follwoing events: + - network requests + - websocket messages + - alarms (see scheduling docs) + +### live actor migration + +- live actor migrations lets your application ugprade, crash, or hot reload cahnges without interruption to your user or application (including websockets) +- this is powered by hibernating websockets for live websocket migraiton & our fault tolerance mechanism (read more below) + +### coldstart performance + +- actors have negligible coldstart performance. the code to run the actor is already started (ie the runner), so creating/starting an actor is incredibly cheap. +- creating new actors with a key requires some overhead to communicate with other regions in order to reserve the actor's key (see below). actors can be created without keys with near-0 latency. + +### multi-region, globally unique actor keys + +- actors can optionally have a globally unique "key" +- when creating an actor with a key +- this system is highly optimized to reduce wan round trips using per-key Paxos with a custom database called Epoxy (https://github.com/rivet-dev/rivet/tree/main/engine/packages/epoxy) +- limitation: when creating an actor with a given key, that key will always be pinned to that region even if the actor is destroyed. creating a new actor with the same key will always live in the same region. +- see the actors keys document + +### input + +- actors have input data that can be passed to them when constructed +- this is similar to apssing data to a constructor in an object + +### generic parameters + +actor definitions include the following generic parameters that you'll see frequently in the code: + +- state +- conn state +- conn params +- ephemeral variables +- input data +- (experimental) database connector + +### persistence + +- state automatically flushes to storage intelligently +- to force a state flush and wait for it to finish, call (TODO: look this up in state document) +- read more about state persistence in the state document (link to document) +- state is stored in the same place as where the actor lives. loading an actor in to memory has comparable performance to network attached storage, and once in memory, has performance of any standard in-memory read/write like a variable. + +### scheduling & alarms + +- actors have a scheduling api to be able to wake up at any time in the indefinite future +- think of this like setTimeout but without a max timeout +- rivet is responsible for waking the actor when this timeout wakes + +### ephemeral variables + +- actors have the ability to create ephemrla variables for things that you do not want to be persisted with the actor's state +- this is useful for non-serializable data like a utility class like a pubsubs erver or something (TODO extra info) +- link to ephemeral variables docs + +### actions + +- for stateless clients, actions are sent as http requests via `POST /gateway/{actor id}/actions/{action name}` +- for stateful clients, actions are sent as websocket messages + +### events & subscriptions + +- events are sent as websocket messages + +### error handling + +- this is different than fault tolerance: + - error handling is a user error + - fault tolerance is something goes wrong that your applciation was not built to handle (ie hard crash, oom, network error) +- rivet provdies a special UserError class to throw custom errors that will be returned to the client +- all other errors are returned as a generic "internal error" +- this is becuase leaking error deatils is a common security hole, so we default to expose-nothing errors + +### logging + +- rivet uses pino for logging +- we expose a scoped child logger for each actor at `c.log` that automatically logs the actor id + key +- this allows you to search lgos easily by actor id without having to log the actor id frequently +- logs can be configured via the `RIVET_LOG_LEVEL` env var + +### fault tolerance + +- actors are fault tolerant, meaning that the host machine can crash and the actors will proceed to operate as if nothing happened +- runners maintain a socket with rivet engine. when this socket closes or takes to long to ping, actors will reschedule +- hibernating websockets (enabled by default) will live-migrate to the new actor as if nothing happened + +### crash policy + +- there are 3 crash policies: sleep, restart, and destroyed + - sleep (default, usually the option you want): + - when to use: actors that need high-performance in-memory logic. + - when not to use: you need this actor running at all times no matter what, even if idle + - examples: (list commone xamples) + - destroy: + - when to use: actors that need to run once until completion. on crash, do not try to reschedule. + - when not to use: if you want your actor to have fault tolerance and be able to run transaprenlty to the underlying runner + - examples: batch jobs, image conversions, ephemeral jobs, (TODO come up with better eaxmples) + - restart: + - when to use: actors that should be running at all times + - when not to use: if you don't absolutely need something running at all times, since this consumes needless compute resources. considure using the scheduling api instead. + - examples: maintain outbound sockets, daemons, always-running jobs, (TODO come up with better examples) + +the behavior for each is described below: + +| Event | Restart | Sleep | Destroy | +|------------------------------|--------------|--------------|--------------| +| Graceful exit (StopCode::Ok) | Destroy | Destroy | Destroy | +| Crash (non-Ok exit) | Reschedule | Sleep | Destroy | +| Lost (runner disappeared) | Reschedule | Sleep | Destroy | +| Lost + force_reschedule | Reschedule | Reschedule | Reschedule | +| GoingAway (runner draining) | Reschedule | Sleep | Destroy | +| No capacity (allocation) | Queue (wait) | Sleep | Queue (wait) | +| No capacity + serverless | Queue (wait) | Queue (wait) | Queue (wait) | +| Wake signal (while sleeping) | Reschedule | Reschedule | Reschedule | + +### inspector + +- actors provide an inspector api to implement the: + - repl + - state read/write + - network inspector + - event log +- this is impelmented over a websocket over bare + +### http api + +- see the http api document on actors + +### multi-region + +- actors can be scheduled across multiple regions +- each actor has an actor id which embeds which region it lives in +- networking is automatically routed to the region that an actor lives in +- limitation: actors curretnly cannot migrate across regions + +### backpressure + +#### no runner capacity + +- this is how actors with different crash policies behave when when there's backpressure: + - sleep = sleeps (sheds load by not rescheduling) + - restart = queues + - destroy = queues +- see the above matrix for more details on actor crash policy on how it handles no capacity. + +- the actor queue is built to withstand high amounts of backpressure on rivet, so queueing actors is fine here +- a large queue means it'll take more time for your application to process the queue to catch up with demand when it comes online. + +#### per-actor cpu & networking exhaustion + +- actors are isolated, so they each have their own individual bottleneck. you can think of this like a process thread where each thread can only do so much. +- there is no durable message queue/"mailbox" for actors. if the actor cannot respond in time, then the request is dropped. +- if an actor exhauses its cpu or networking, then the runner +- returns service unavailble (503) if the actor fails to respond to a request in time +- there is no hard cap on the networking or cpu usage for each actor at the moment +- if your actor is resource intensive, it's common to use a separate mailbox actor to act as a queue + +## runners + +### regular vs serverless runners + +there are 2 types of runners: + +- regular: these are standard nodejs processes connected to rivet that rivet can orchestrate actors to and send network requests to at any time +- serverless: rivet works with serverless platforms. when an actor is created, it has a request-per-actor model where it opens a long-running request on the serverless platofrm to run a given actor. + +### runner pool + +- runners are pooled together by sharing a common name (ie "default") +- when an actor is created, it chooses the pool by selecting the runner name to run on +- rivet will automatically load balance actors across these runners + +### runner key + +- not relevnat for serverless runners +- each runner has a unique key that it provides when connecting. keys are unique to the instace the runner is running on and should be the same if the runner is restarted. +- this can be the: machine's ip, k8s pod name, etc +- if there is an existing runner connected with a given key, the runner will disconnect the old runner and replace it +- rivet is designed to handle network partitions by waiting for runners to miss a ping, indicating it's no longer alive. however, often times runners restart immediately after a hard crash and reconnect. in this case, the runner will reconnect on restart and terminate the old runner in order to prevent further actors from scheduling to the crashed runner. + +### capacity + +- not relevnat for serverless runners +- each runner can be assigned a capacity of how many actors it can run +- rivet will schedule with spread (not binpacking) in order to spread load over actors + +#### usefulness of capacity = 1 + +- setting a capacity of 1 is helpful for situations where you have cpu-intensive apps that should not run with any other actors +- examples include game servers, ffmpeg jobs, etc + +### versions & upgrading code + +- each runner has a version index +- actors are always scheduled to the highest verison index (see runner priority below) +- this means that when a new runner is deployed: + 1. runners with higher index come online + 2. actors schedule to the highest index, stop scheduling to the older index + 3. old index runners start draining and migrating actors to new index + 4. all old runners are now shut down +- websocekts are live migrated to the new version when upgrading using hibernating websockets to users see no hiccup in their applications +- this is important because actors should never downgrade their runner. they should always move to a newer version of code in order to prevent corruption. + +### runner scheduling prioroty + +- actors are scheduled to runners sorted by priority of (version DESC, remaining capacity ASC) + +### multi-region + +TODO + +### shutdown sequence + +- runner shutdown is important to ensure that actors do not get unexpectedly terminated when either: + - upgrading your applciation and taking down old pods + - scaling down your runners horizontally (ie from an hpa) + - pressing ctrl-c when in development +- on shutdown: + 1. tell rivet the runner is stopping + 2. rivet tells all the actors on this runner to migrate + 3. runner waits for all actors to finish migrating + 4. runner exits process + +### reconnection + +- runners can handle temporary network partitions +- they'll automatically reconnect and replay missed commands/events between rivet and the runner +- this happens transparenlty to the user +- if disconnected for too long (indicating a network partition), the runner will shut itself down and exit + +### autoscaling + +- not relevant to serverless +- runners currently autoscale on cpu. more intelligent scaling is coming soon. +- tune your runner total slots capacity accordingly +- it's up to you to configure your hpa/etc to work like this. see the Connect guides (link to index page) for reference on hwo to configure this. + +### serverless timeouts + +- serverless runners take in to account the maximum run duration of the serverless platform +- the runners will mgirate actors to a new request before the request times out +- this is completely transparent to you and the user because of the fault tolerance and websocket migraiton characteristics +- it's common for actors to go sleep before hitting the serverless timeout + +## networking + +### web standards + +- everything in rivet is built on webstandards by default +- nothing in rivet requires you to use our sdk, our sdks are meant to be a convenience. it's built to be as easy to use raw http/websocket endpoints from scratch. +- actions, events, etc are all built on simple, well-documented http/websocket under the hood (link to openapi & asyncapi docs). +- you can use low-level request handlers (lnk to dock) and low-level weboscket handlers (link to doc) to handle low-level primtivies yourself + +### encoding + +- rivetkit's action/events api supports communicating via [VBARE](link to github repo, see the blog post for the link), CBOR, or JSON + - VBARE: high-perofrmance & compact, optimal use case + - CBOR: descent encoding/decoding perf + portable libraries, good for implemnting high-ish performance on other platforms + - JSON: good for fast implementations & debugging (easy to read) + +### tunneling + +- when a runner connects it opens a tunnel to rivet to allow incoming traffic + - this is simila to systems like tailscale, ngrok, or other vpns + - we do this for security & configuraiton simplicity since it means that you don't have to manage exposing your rivetkit applications' networkig to rivet. instead, anything that can open a socket to rivet can accept inbound traffic to actors. + +### gateway + +- incoming traffic to actors come to the Rivet gateway and are routed to the appropriate runner +- the rivet gateway automatically handles: + - multi-region routing to route traffic to the correct reigon for an actor + - automatically waking the actor if needed + - sending traffic over the runner + +### hibernating websockets + +- hibernating web sockets are a core component of live actor migration & fault tolerance. it allows us to maintain an open websocket while the actor crashes, upgrades, or moves to another runner. +TODO: copy the rest of this from low-level webosckets document and rephrase + +### actor health endpoin + +- actors provide a simple, utility health endpoint at `/health` that lets you check if your actor is reachable (e.g. `curl https://api.rivet.dev/gateway/{actor id}/health`) + +## multi-region + +### networking + +- actors may live in different regions than inbound requests +- Rivet uses the Epoxy (link again) system to handle global routing to route traffic to the correct region with high performance +- this is completely transparent to you. your app sends traffic to https://api.rivet.dev/gateway/* and it automatically routes to the correct actor in the appropriate region + +### globally unique actor keys + +- actor keys are globally unique to be able to benefit from multi-region capabilities without any extra work +- see more about globally uniuqe actor keys above +- see the actor keys document + +### regional endpoints + +- each reigon has a regional endpoint +- this endpoint is used specifically for connecting runners (for example https://api-us-east-1.rivet.dev), opt to use api.rivet.dev for all other traffic +- runners are required to connect to the regional endpoints + - this is because runners are sensitive to latency to the rivet regional datacenter + - we add datacenters regularly so each runner needs to be pinned to a single datacenter in order to ensure your availble datacneter list doesn't change sporadically without your consent + +### persistence + +- data is always persisted in the same region that is written +- this is important for minimal coldstarts & data locality laws + +## namespaces + +- rivet provides namespaces to run multiple actor systems in isolation +- this makes it really easy to have prod/staging environments or completely different applications running on the same rivet instance +- when you connect to rivet, you can specify which namespace you're connecting to +- self-hotsed rivet defaults to namespace "default" +- rivet cloud provdies isolated tokens for each namespace + +## manager api + +- rivet provides a standard rest api for managing actors + - useful endoints include: + - get /actors + - delete /actors/{} + - get /actors/names -> get all actor types available + +## comparison to prior art for actors + +### runtime + +- there are very few serious actor implementation targeted at the javascirpt eocsystem. rivet is arguably the most serious open-source actor implementation for typescript out there. + +### library vs orchestrator + +- some actor systems opt to be purely a library while rivet opts to have an orchestrator (i.e. the single rust binary) +- this lets us to a lot of things other actor systems can't: + - separating orchestration, persistence, and proxy lets us isoalte the core to be incredibly reliable while the fast-changing applications that ocnnect to rivet can be more error-prone safely. with a library, the blast radius of your application also affects the entire actor system. + - support for serverless platforms to benefit from cost, multi-region, blitz scaling, and relibaiblity benefits + - optimize fault tolerance since we can make more assumtions about application state when the rivet core does not crash and your app does + +### scheduling + +actors is a loose term, but there are generally 2 types of schedulign in practice: + +- ephemeral actors + - examples: erlang/otp, akka, swift + - provides no persistence or sleeping mechanism by defualt + - relies on supervisors for managing persistence +- [virtual actors](https://www.microsoft.com/en-us/research/project/orleans-virtual-actors/) + - an extension of the actor pattern that provides actors that can hibernate ("sleep") when not in use + - examples: orleans, dapr, durable objects + +rivet has similarities with both to provide more flexibility: + +- crash policies provdie for 3 types of actors: + - sleep -> most similar to virutal actors + - restart -> most similar to ephemeral actors but with a supervisor to auto-restart, however still has a durable queue ot handle backpressure + - crash -> most similar to traditional actors but with no supervisor to restart, however still has a durable queue to handle backpressure + +### communication + +- many actor frameworks use inbox patterns (think: queue-per-actor) to handle sending messages between actors +- there is no callback mechanims, instead you need to send messages back to the actual actor +- rivet opts to behave like web standards instead of using the message pattern + - actors can impelment the inbox pattern optionally + - but we provide lower-level networking to be able to be compatible with more techniologies + - rivet assumes the same serial concurerntly that other actors do (by the nature of javascript being single-threaded) but we allow you to run promises in parallel or handl eyour own concurrency control (which some other actor frameworks might require a spawning new actor to do) + +_Source doc path: /docs/general/architecture_ diff --git a/.agents/skills/ai-agent/reference/general/cors.md b/.agents/skills/ai-agent/reference/general/cors.md new file mode 100644 index 0000000..330fe38 --- /dev/null +++ b/.agents/skills/ai-agent/reference/general/cors.md @@ -0,0 +1,18 @@ +# Cross-Origin Resource Sharing + +> Source: `src/content/docs/general/cors.mdx` +> Canonical URL: https://rivet.dev/docs/general/cors +> Description: Cross-Origin Resource Sharing (CORS) controls which origins (domains) can access your actors. When actors are exposed to the public internet, proper origin validation is critical to prevent security breaches and denial of service attacks. + +--- +Unlike stateless HTTP APIs that use CORS headers, Rivet Actors are stateful and support persistent WebSocket connections. Since WebSockets don't natively support CORS, we validate origins manually in the `onBeforeConnect` hook before connections may open. + +## Implementing Origin Restrictions + +To implement origin restrictions on Rivet Actors, use the `onBeforeConnect` hook to verify the request. + +To catch the error on the client, use the following code: + + See tracking issue for [configuring CORS per-actor on the gateway](https://github.com/rivet-dev/rivet/issues/3539) that will remove the need to implement origin restrictions in `onBforeRequest`. + +_Source doc path: /docs/general/cors_ diff --git a/.agents/skills/ai-agent/reference/general/docs-for-llms.md b/.agents/skills/ai-agent/reference/general/docs-for-llms.md new file mode 100644 index 0000000..db0c216 --- /dev/null +++ b/.agents/skills/ai-agent/reference/general/docs-for-llms.md @@ -0,0 +1,51 @@ +# Documentation for LLMs & AI + +> Source: `src/content/docs/general/docs-for-llms.mdx` +> Canonical URL: https://rivet.dev/docs/general/docs-for-llms +> Description: Rivet provides optimized documentation formats specifically designed for Large Language Models (LLMs) and AI integration tools. + +--- +## Skills (Recommended) + +For AI coding assistants like Claude Code, Cursor, or Windsurf, install Rivet skills for the best development experience: + +```sh +npx skills add rivet-dev/skills +``` + +Skills provide your AI assistant with Rivet-specific knowledge, best practices, and code patterns directly in your project context. + +## Available Formats + +### `llms.txt` (Condensed) +A condensed version of the documentation perfect for quick reference and context-aware AI assistance. + +**Access:** /llms.txt + +This format includes: +- Key concepts and features +- Essential getting started information +- Summaries of main functionality +- Optimized for token efficiency + +### `llms-full.txt` (Complete) +The complete documentation in a single file, ideal for comprehensive AI assistance and in-depth analysis. + +**Access:** /llms-full.txt + +This format includes: +- Complete documentation content +- All examples and detailed explanations +- Full API references and guides +- Suitable for complex queries and comprehensive understanding + +## Access Pages As Markdown + +Each documentation page is also available as clean markdown by appending `.md` to any documentation URL path. + +For example: + +- Original URL: `https://rivet.dev/docs/actors` +- Markdown URL: `https://rivet.dev/docs/actors.md` + +_Source doc path: /docs/general/docs-for-llms_ diff --git a/.agents/skills/ai-agent/reference/general/edge.md b/.agents/skills/ai-agent/reference/general/edge.md new file mode 100644 index 0000000..814dde2 --- /dev/null +++ b/.agents/skills/ai-agent/reference/general/edge.md @@ -0,0 +1,24 @@ +# Edge Networking + +> Source: `src/content/docs/general/edge.mdx` +> Canonical URL: https://rivet.dev/docs/general/edge +> Description: Actors automatically run near your users on your provider's global network. + +--- +At the moment, edge networking is only supported on Rivet Cloud & Cloudflare Workers. More self-hosted platforms are on the roadmap. + +## Region selection + +### Automatic region selection + +By default, actors will choose the nearest region based on the client's location. + +Under the hood, Rivet and Cloudflare use [Anycast routing](https://en.wikipedia.org/wiki/Anycast) to automatically find the best location for the client to connect to without relying on a slow manual pinging process. + +### Manual region selection + +The region an actor is created in can be overridden using region options: + +See [Create Manage Actors](/docs/actors/communicating-between-actors) for more information. + +_Source doc path: /docs/general/edge_ diff --git a/.agents/skills/ai-agent/reference/general/endpoints.md b/.agents/skills/ai-agent/reference/general/endpoints.md new file mode 100644 index 0000000..5c376e1 --- /dev/null +++ b/.agents/skills/ai-agent/reference/general/endpoints.md @@ -0,0 +1,98 @@ +# Endpoints + +> Source: `src/content/docs/general/endpoints.mdx` +> Canonical URL: https://rivet.dev/docs/general/endpoints +> Description: Configure how your backend connects to Rivet and how clients reach your actors. + +--- +## Local Development + +No configuration is needed for local development. RivetKit runs entirely on your local machine without any extra configuration to run Rivet Actors. + +## Production Deployment + +When deploying to production, you need to configure endpoints so your backend can communicate with Rivet Engine and clients can reach your actors. + +Diagram showing Client connecting to Rivet, which connects to Your Backend + +### Private Endpoint + +The private endpoint tells your backend where to find the Rivet Engine. + +### Environment Variable + +```bash +RIVET_ENDPOINT=https://my-namespace:sk_xxxxx@api.rivet.dev +``` + +### Config + +### Public Endpoint + +The public endpoint tells clients where to connect to reach your actors. + +This endpoint and token will be exposed to the internet. Use a public token (`pk_`), not your secret token (`sk_`). + +The public endpoint is only required if using the [serverless runtime mode](/docs/general/runtime-modes#runners) and if you have a frontend using RivetKit. + +### Environment Variable + +```bash +RIVET_PUBLIC_ENDPOINT=https://my-namespace:pk_xxxxx@api.rivet.dev +``` + +### Config + +## Advanced + +### URL Auth Syntax + +Endpoint URLs support embedding namespace and token directly in the URL: + +``` +https://namespace:token@host/path +``` + +This is the recommended approach for simplicity. Alternatively, you can use separate environment variables: + +```bash +RIVET_ENDPOINT=https://api.rivet.dev +RIVET_NAMESPACE=my-namespace +RIVET_TOKEN=sk_xxxxx +``` + +### Security + +In serverless mode, the private endpoint is used to validate that requests to `GET /api/rivet/start` are coming from your trusted Rivet endpoint. If the private endpoint is not configured, anyone can run a self-hosted instance of Rivet and connect to your backend from any endpoint. + +### How Clients Connect + +This flow applies to [serverless runtime mode](/docs/general/runtime-modes#serverless). For [runner runtime mode](/docs/general/runtime-modes#runners) or [clients configured to connect directly to Rivet](/docs/clients/javascript), clients connect directly to Rivet and this metadata flow is not needed. + +When a client connects to your serverless application, it follows this flow: + +1. Client makes a request to `https://my-app.example.com/api/rivet/metadata` +2. Your app returns the public endpoint configuration: + ```json + { + "clientEndpoint": "https://api.rivet.dev", + "clientNamespace": "my-namespace", + "clientToken": "pk_xxxxx" + } + ``` +3. Client caches these values and uses them for subsequent requests +4. Client connects to `https://api.rivet.dev/gateway/{actor}`, which routes requests to your actors + +This indirection exists because Rivet acts as a gateway between clients and your actors. This is because Rivet handles routing, load balancing, and actor lifecycle management of actors. + +## Reference + +| Environment Variable | Config Option | Description | +|---------------------|---------------|-------------| +| `RIVET_ENDPOINT` | `endpoint` | Rivet Engine URL for your backend | +| `RIVET_NAMESPACE` | `namespace` | Namespace for actor isolation | +| `RIVET_TOKEN` | `token` | Authentication token for engine connection | +| `RIVET_PUBLIC_ENDPOINT` | `serverless.publicEndpoint` | Client-facing endpoint | +| `RIVET_PUBLIC_TOKEN` | `serverless.publicToken` | Client-facing token | + +_Source doc path: /docs/general/endpoints_ diff --git a/.agents/skills/ai-agent/reference/general/environment-variables.md b/.agents/skills/ai-agent/reference/general/environment-variables.md new file mode 100644 index 0000000..2a86e98 --- /dev/null +++ b/.agents/skills/ai-agent/reference/general/environment-variables.md @@ -0,0 +1,87 @@ +# Environment Variables + +> Source: `src/content/docs/general/environment-variables.mdx` +> Canonical URL: https://rivet.dev/docs/general/environment-variables +> Description: This page documents all environment variables that configure RivetKit behavior. + +--- +## Connection + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_ENDPOINT` | Endpoint URL to connect to Rivet Engine. Supports [URL auth syntax](/docs/general/endpoints#url-auth-syntax). | +| `RIVET_TOKEN` | Authentication token for Rivet Engine | +| `RIVET_NAMESPACE` | Namespace to use (default: "default") | + +## Public Endpoint + +These variables configure how clients connect to your actors. + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_PUBLIC_ENDPOINT` | Public endpoint for client connections. Supports [URL auth syntax](/docs/general/endpoints#url-auth-syntax). | +| `RIVET_PUBLIC_TOKEN` | Public token for client authentication | + +## Runner Configuration + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_RUNNER` | Runner name (default: "default") | +| `RIVET_RUNNER_VERSION` | Version number for the runner. See [Versions & Upgrades](/docs/actors/versions). | +| `RIVET_RUNNER_KIND` | Type of runner | +| `RIVET_TOTAL_SLOTS` | Total actor slots available (default: 100000) | + +## Engine + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_RUN_ENGINE` | Set to `1` to spawn the engine process | +| `RIVET_RUN_ENGINE_HOST` | Host to bind the spawned local engine process to. Defaults to `127.0.0.1`. | +| `RIVET_RUN_ENGINE_PORT` | Port to bind the spawned local engine process to. Defaults to `6420`. | +| `RIVET_RUN_ENGINE_VERSION` | Version of engine to download | + +## Inspector + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_INSPECTOR_DISABLE` | Set to `1` to disable the inspector | + +## Metrics + +| Environment Variable | Description | +|---------------------|-------------| +| `_RIVET_METRICS_TOKEN` | Bearer token that gates the per-actor Prometheus `/metrics` endpoint. When unset, `/metrics` is disabled. | + +## Experimental + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_EXPERIMENTAL_OTEL` | Set to `1` to enable experimental OTel tracing in Rivet Actors | + +## Storage + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVETKIT_RUNTIME` | Runtime binding to use for RivetKit core: `auto`, `native`, or `wasm`. Defaults to `auto`. | +| `RIVETKIT_STORAGE_PATH` | Overrides the default file-system storage path used by RivetKit when using the default driver. | + +## Lifecycle + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVETKIT_RUNTIME_MODE` | Controls how `registry.start()` runs. Accepted values are `envoy` and `serverless`; any other explicit value errors. Defaults to `envoy`: opens a long-lived WebSocket to the engine (Mode A). Set to `serverless` to bind an HTTP listener via `registry.listen()` (Mode B). | +| `RIVETKIT_PUBLIC_DIR` | Directory of static assets to serve alongside the framework routes when calling `registry.listen()`. Used as a fallback when `opts.publicDir` is not passed. On auto-listen via `registry.start()`, defaults to `/public` when this env var is unset. | +| `RIVET_PORT` | Port the listener binds when calling `registry.listen()` without an explicit `opts.port`. Must be an integer between 1 and 65535. Defaults to `3000`. | + +## Logging + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_LOG_LEVEL` | Log level: `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `silent` | +| `RIVET_LOG_TARGET` | Set to `1` to include log target | +| `RIVET_LOG_TIMESTAMP` | Set to `1` to include timestamps | +| `RIVET_LOG_MESSAGE` | Set to `1` to include message formatting | +| `RIVET_LOG_ERROR_STACK` | Set to `1` to include error stack traces | +| `RIVET_LOG_HEADERS` | Set to `1` to log request headers | + +_Source doc path: /docs/general/environment-variables_ diff --git a/.agents/skills/ai-agent/reference/general/http-server.md b/.agents/skills/ai-agent/reference/general/http-server.md new file mode 100644 index 0000000..c3a386c --- /dev/null +++ b/.agents/skills/ai-agent/reference/general/http-server.md @@ -0,0 +1,96 @@ +# HTTP Server + +> Source: `src/content/docs/general/http-server.mdx` +> Canonical URL: https://rivet.dev/docs/general/http-server +> Description: Different ways to run your RivetKit HTTP server. + +--- +## Methods of Running Your Server + +### registry.start() + +The simplest way to run your server. Starts a local RivetKit server, serves static files from a `public` directory, and starts the actor runner: + +Run with `npx tsx --watch index.ts` (Node.js), `bun --watch index.ts` (Bun), or `deno run --allow-net --allow-read --allow-env --watch index.ts` (Deno). Clients connect to the Rivet Engine on `http://localhost:6420`. + +### With Fetch Handlers + +A [fetch handler](https://wintercg.org/) is a function that takes a `Request` and returns a `Response`. This is the standard pattern used by Cloudflare Workers, Deno Deploy, Bun, and other modern runtimes. + +Use `registry.serve()` to get a fetch handler: + +To integrate with a router like [Hono](https://hono.dev/) or [Elysia](https://elysiajs.com/), use `registry.handler()`: + +### Hono + +### Elysia + +Then run your server: + +```bash Node.js +npx tsx --watch server.ts +``` + +```bash Bun +bun --watch server.ts +``` + +```bash Deno +deno run --allow-net --allow-read --allow-env --watch server.ts +``` + +### Explicit HTTP Server + +If you need to explicitly start the HTTP server instead of using the fetch handler pattern: + +### Node.js (Hono) + +Using Hono with `@hono/node-server`: + +### Node.js (Adapter) + +Using `@whatwg-node/server` to adapt the fetch handler to Node's HTTP server: + +```ts server.ts @nocheck +import { actor, setup } from "rivetkit"; +import { createServer } from "node:http"; +import { createServerAdapter } from "@whatwg-node/server"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +const handler = createServerAdapter(registry.serve().fetch); +const server = createServer(handler); +server.listen(3000); +``` + +### Bun + +Using Bun's native server: + +```ts server.ts @nocheck +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +Bun.serve({ + port: 3000, + fetch: (request: Request) => registry.handler(request), +}); +``` + +### Deno + +Using Deno's native server: + +```ts server.ts @nocheck +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +Deno.serve({ port: 3000 }, (request: Request) => registry.handler(request)); +``` + +_Source doc path: /docs/general/http-server_ diff --git a/.agents/skills/ai-agent/reference/general/logging.md b/.agents/skills/ai-agent/reference/general/logging.md new file mode 100644 index 0000000..f7ce9eb --- /dev/null +++ b/.agents/skills/ai-agent/reference/general/logging.md @@ -0,0 +1,74 @@ +# Logging + +> Source: `src/content/docs/general/logging.mdx` +> Canonical URL: https://rivet.dev/docs/general/logging +> Description: Actors provide a built-in way to log complex data to the console. + +--- +Using the context's log object (`c.log`) allows you to log complex data using structured logging. + +Using the actor logging API is completely optional. + +## Log levels + +There are 7 log levels: + +| Level | Call | Description | +| ------ | ------------------------------- | ---------------------------------------------------------------- | +| Fatal | `c.log.fatal(message, ...args);` | Critical errors that prevent core functionality | +| Error | `c.log.error(message, ...args);` | Errors that affect functionality but allow continued operation | +| Warn | `c.log.warn(message, ...args);` | Potentially harmful situations that should be addressed | +| Info | `c.log.info(message, ...args);` | General information about significant events & state changes | +| Debug | `c.log.debug(message, ...args);` | Detailed debugging information, usually used in development | +| Trace | `c.log.trace(message, ...args);` | Very detailed debugging information, usually for tracing flow | +| Silent | N/A | Disables all logging output | + +## Structured logging + +The built-in logging API (using `c.log`) provides structured logging to let you log key-value +pairs instead of raw strings. Structured logs are readable by both machines & +humans to make them easier to parse & search. + +When using `c.log`, the actor's name, key, and actor ID are automatically included in every log output. This makes it easy to filter and trace logs by specific actors in production environments. + +### Examples + +The logging system is built on [Pino](https://getpino.io/#/docs/api?id=logger), a high-performance structured logger for Node.js. + +## Configuration + +### Environment Variables + +You can configure logging behavior using environment variables: + +| Variable | Description | Values | Default | +| -------- | ----------- | ------ | ------- | +| `RIVET_LOG_LEVEL` | Sets the minimum log level to display | `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `silent` | `warn` | +| `RIVET_LOG_TARGET` | Include the module name that logged the message | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_TIMESTAMP` | Include timestamp in log output | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_MESSAGE` | Enable detailed message logging for debugging | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_ERROR_STACK` | Include stack traces in error output | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_HEADERS` | Log HTTP headers in requests | `1` to enable, `0` to disable | `0` | + +Example: +```bash +RIVET_LOG_LEVEL=debug RIVET_LOG_TARGET=1 RIVET_LOG_TIMESTAMP=1 node server.js +``` + +### Log Level + +You can configure the log level programmatically when setting up your registry: + +### Custom Pino Logger + +You can also provide a custom Pino base logger for more advanced logging configurations: + +If using a custom base logger, you must manually configure your own log level in the Pino logger. + +For more advanced Pino configuration options, see the [Pino API documentation](https://getpino.io/#/docs/api?id=export). + +### Disable Welcome Message + +You can disable the default RivetKit welcome message with: + +_Source doc path: /docs/general/logging_ diff --git a/.agents/skills/ai-agent/reference/general/pool-configuration.md b/.agents/skills/ai-agent/reference/general/pool-configuration.md new file mode 100644 index 0000000..21b00f1 --- /dev/null +++ b/.agents/skills/ai-agent/reference/general/pool-configuration.md @@ -0,0 +1,119 @@ +# Pool Configuration + +> Source: `src/content/docs/general/pool-configuration.mdx` +> Canonical URL: https://rivet.dev/docs/general/pool-configuration +> Description: Reference for runner pool configuration, including drain behavior, actor eviction rate limiting, and serverless-specific options. + +--- +A **runner pool** is the set of runners Rivet manages for a given runner name within a namespace. The pool configuration controls how runners are scaled, drained on version upgrades, and how quickly actors are evicted from drained runners. + +There are two pool kinds: + +- **`normal`** — runners connect to the engine themselves (for example a long-running process started by you, Docker, or Kubernetes). The engine does not start or stop runners. +- **`serverless`** — the engine calls an HTTP endpoint to wake runners on demand. Used by serverless platforms (Vercel, Cloudflare Workers, Freestyle, etc.). See [Runtime Modes](/docs/general/runtime-modes). + +## Setting the Configuration + +Configure a pool from the [Rivet dashboard](https://dashboard.rivet.dev) under your namespace's runner settings. The dashboard is the recommended way to manage pool configuration. + +You can also set pool configuration directly through the API or the TypeScript SDK: + +```typescript SDK @nocheck +import { RivetClient } from "@rivetkit/engine-api-full"; + +const rivet = new RivetClient({ + environment: "https://api.rivet.dev", + token: process.env.RIVET_TOKEN!, +}); + +await rivet.runnerConfigsUpsert("default", { + namespace: "default", + datacenters: { + default: { + serverless: { + url: "https://my-app.example.com/api/rivet", + requestLifespan: 60 * 15, + actorEvictionDelay: 5, + actorEvictionPeriod: 60, + actorEvictionRate: 1, + }, + }, + }, +}); +``` + +```bash curl +curl -X PUT "https://api.rivet.dev/runner-configs/default?namespace=default" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "datacenters": { + "default": { + "serverless": { + "url": "https://my-app.example.com/api/rivet", + "request_lifespan": 900, + "actor_eviction_delay": 5, + "actor_eviction_period": 60, + "actor_eviction_rate": 1 + } + } + } + }' +``` + +The HTTP API uses `snake_case`. The TypeScript SDK uses `camelCase`. The field names below use `camelCase`. + +## Common Options + +These options apply to both `normal` and `serverless` pools. + +| Option | Type | Default | Description | +|---|---|---|---| +| `drainOnVersionUpgrade` | `bool` | `true` | When a new runner version is deployed, stop old runners and migrate their actors. See [Versions & Upgrades](/docs/actors/versions#drain-on-version-upgrade). | +| `actorEvictionDelay` | `u32` (seconds) | `0` | Delay before actor eviction begins after a drain is triggered. Gives clients time to receive the drain signal before migrations start. | +| `actorEvictionPeriod` | `u32` (seconds) | `0` | Window over which evictions are batched. Used together with `actorEvictionRate` to smooth eviction load on the rest of the pool. | +| `actorEvictionRate` | `f32` (actors/sec) | `1.0` | Maximum number of actors evicted per second once eviction is underway. Set higher for fast cutovers, lower to spread reschedule load. | +| `metadata` | `object` | — | Arbitrary JSON metadata attached to the pool. Useful for tagging and dashboards. | + +### Tuning eviction rate limiting + +Eviction kicks in whenever a runner is drained — most commonly during a version upgrade with `drainOnVersionUpgrade: true`, but also when a runner disconnects ungracefully or is replaced. + +A typical tuning starts from: + +- `actorEvictionDelay: 5` — five-second head start so clients see the drain notification before migrations begin. +- `actorEvictionPeriod: 60` — batch over a one-minute window. +- `actorEvictionRate: 1` — evict one actor per second. + +Increase `actorEvictionRate` for small pools where a full cutover finishes in seconds. Decrease it for large pools to avoid bursts of reschedule traffic. + +## Serverless-Only Options + +These options only apply when `kind: "serverless"`. + +| Option | Type | Default | Description | +|---|---|---|---| +| `url` | `string` | — | HTTP endpoint the engine calls to wake a runner. | +| `headers` | `map` | `{}` | Additional headers sent with the wake request (for example an auth token). | +| `requestLifespan` | `u32` (seconds) | — | Total lifespan of a serverless request before drain begins. Must be shorter than your platform's request timeout. | +| `maxConcurrentActors` | `u64` | `1000` | Soft cap on concurrent actors hosted across the pool. | +| `drainGracePeriod` | `u32` (seconds) | `1800` (30 min) | Time a serverless runner reserves at the end of its lifespan for actors to stop gracefully. | +| `metadataPollInterval` | `u64` (ms) | engine default | How often each runner re-fetches pool metadata to detect new versions. | + +### Deprecated options + +The following options still parse for backwards compatibility but should not be used in new configurations: + +- `slotsPerRunner` +- `minRunners` +- `maxRunners` +- `runnersMargin` + +## Related + +- [Runtime Modes](/docs/general/runtime-modes) — runner vs serverless behavior. +- [Versions & Upgrades](/docs/actors/versions) — how `drainOnVersionUpgrade` interacts with version detection. +- [Limits](/docs/actors/limits) — request lifespan and drain grace period limits. +- [Debugging](/docs/actors/debugging) — inspect a pool configuration via the API. + +_Source doc path: /docs/general/pool-configuration_ diff --git a/.agents/skills/ai-agent/reference/general/production-checklist.md b/.agents/skills/ai-agent/reference/general/production-checklist.md new file mode 100644 index 0000000..1ebe257 --- /dev/null +++ b/.agents/skills/ai-agent/reference/general/production-checklist.md @@ -0,0 +1,98 @@ +# Production Checklist + +> Source: `src/content/docs/general/production-checklist.mdx` +> Canonical URL: https://rivet.dev/docs/general/production-checklist +> Description: Checklist for deploying Rivet Actors to production. + +--- +We recommend passing this page to your coding agent to verify your configuration before deploying. + +## Environment + +- **Set `NODE_ENV=production`.** Ensures optimized performance and disables development-only behavior. +- **Ensure log level is not set to debug.** Leave `RIVET_LOG_LEVEL` at its default or explicitly set it to `warn` to avoid excessive logging. See [Logging](/docs/general/logging). +- **Do not set `RIVET_EXPOSE_ERRORS=1` in production.** This exposes internal error details to clients. It is automatically enabled when `NODE_ENV=development`. See [Errors](/docs/actors/errors). + +## Runtime Mode + +- **Configure a runner version.** Required for graceful upgrades and draining of old actors. Applies to both serverless and runner modes. See [Versions & Upgrades](/docs/actors/versions). + +### Serverless + +- **Check platform timeouts.** Rivet handles migration between invocations automatically, but shorter timeouts increase migration frequency. See [Timeouts](/docs/general/runtime-modes#timeouts). +- **Verify `/api/rivet/start` body size limits.** Serverless actor starts carry actor config and preloaded KV or SQLite startup data in the request body. Keep `serverless.maxStartPayloadBytes` and your platform or proxy body limit at **16 MiB or higher**, or lower the preload budget if your platform cannot accept that size. See [Limits](/docs/actors/limits#kv-preloading). +- **Configure max runners.** Go to Settings > Providers > Edit Provider > Max Runners to set the limit. The default is 100,000 runners. This is effectively your max actor count. +- **Verify your platform rate limit accommodates your actor create and wake frequency.** Actor start requests are sent from Rivet's servers, so they all originate from the same IP. Per-IP rate limits will throttle the engine well before they would throttle real end-user traffic. Size your platform's rate limit to your peak actor create and wake rate, not your end-user request rate. +- **Set the per-instance max concurrent actor limit.** Each serverless instance hosts one actor per in-flight `/api/rivet/start` request, so your platform's per-instance concurrency (e.g. GCP Cloud Run `--concurrency`, AWS Lambda reserved concurrency, Vercel `maxDuration` + concurrency) directly caps actors per instance. Pick a value based on per-actor memory and CPU; the platform autoscales out additional instances once existing ones hit the cap. +- **Tune `requestLifespan` to your platform's hard request timeout.** `requestLifespan` (default `3600`, 60 minutes) is the total lifespan of each serverless request before actors migrate to a fresh instance. Set it just below your platform's hard timeout (e.g. `295` for Vercel Hobby, `3595` for Vercel Pro, `840` for Cloud Run's 15-min cap). Configure via [`configurePool`](/docs/general/registry-configuration). See [Timeouts](/docs/general/runtime-modes#timeouts). +- **Tune `drainGracePeriod` to cover graceful actor shutdown.** Time reserved at the end of `requestLifespan` for actors to stop gracefully before the request is forcibly closed. Default is 30 minutes from the engine; lower it for short-lived stateless actors, raise it if your actors do non-trivial cleanup or final SQLite writes. Configure via [`configurePool`](/docs/general/registry-configuration). See [Limits](/docs/actors/limits). + +### Runner + +- **Set a graceful shutdown period of at least 35 minutes.** Runners need up to 30 minutes to drain actors during upgrades, plus buffer for shutdown overhead. In Kubernetes, set `terminationGracePeriodSeconds: 2100` on the pod spec. + +## Actors + +### Design Patterns + +- **Do not use god actors.** Avoid putting all logic into a single actor type. See [Design Patterns](/docs/actors/design-patterns). +- **Do not use actor-per-request patterns.** Avoid creating a new actor for each request. See [Design Patterns](/docs/actors/design-patterns). + +### Lifecycle + +- **Do not rely on `onSleep` for critical cleanup.** `onSleep` is not called during crashes or forced terminations. See [Lifecycle](/docs/actors/lifecycle). + +### State + +- **Verify `c.state` does not grow unbounded.** Avoid using arrays or objects that grow over time in state. Use [SQLite](/docs/actors/sqlite) for unbounded or append-heavy data instead. +- **Verify actor data does not exceed 10 GB.** Contact [enterprise support](https://rivet.dev/sales) if you need more storage. +- **Use input parameters and `createState` for actor initialization.** See [Input Parameters](/docs/actors/input). + +### Events + +- **Use `conn.send()` instead of `c.broadcast()` for private events.** `c.broadcast()` sends to all connected clients. Use `conn.send()` to send events to a specific connection. See [Realtime](/docs/actors/events). + +### Actions + +- **Review action timeout configuration.** The default `actionTimeout` is 60 seconds. Increase it if you have long-running actions like API calls or file processing. See [Actor Configuration](/docs/general/actor-configuration). +- **Review message size limits.** The default `maxIncomingMessageSize` is 64 KiB and `maxOutgoingMessageSize` is 1 MiB. Increase if your actors send or receive large JSON payloads. See [Registry Configuration](/docs/general/registry-configuration). + +### Queues + +- **Review queue limits.** The default `maxQueueSize` is 1,000 messages and `maxQueueMessageSize` is 64 KiB. Increase if you expect burst traffic or large queue payloads. See [Actor Configuration](/docs/general/actor-configuration). +- **Ensure queue handlers are idempotent.** If processing fails before `message.complete()`, the message will be retried. See [Queues](/docs/actors/queues). + +### Workflows + +- **Verify workflows do not generate infinite steps.** Use `ctx.loop` to avoid creating unbounded step histories. See [Workflows](/docs/actors/workflows). + +## Security + +### Authentication + +- **Validate connections in `createConnState` or `onBeforeConnect`.** Do not trust client input without validation. See [Authentication](/docs/actors/authentication). + +### CORS + +- **Configure CORS for production.** Restrict allowed origins instead of allowing all. See [CORS](/docs/general/cors). + +### Tokens (Rivet Cloud) + +- **Use `pk_*` tokens for `RIVET_PUBLIC_ENDPOINT`.** Public tokens are safe to expose to clients. +- **Use `sk_*` tokens for `RIVET_ENDPOINT`.** Secret tokens should only be used server-side. +- **Do not leak your secret token.** Never expose `sk_*` tokens in client-side code, public repositories, or browser environments. See [Endpoints](/docs/general/endpoints). +- **Verify you're connecting to the correct region.** Use the nearest datacenter endpoint (e.g. `api-us-west-1.rivet.dev`) for lowest latency. + +### Access Control + +Access control is only needed if you want granular permissions for different clients. For most use cases, basic authentication in `onBeforeConnect` or `createConnState` is sufficient. + +- **Use deny-by-default rules.** Reject unknown roles in `onBeforeConnect`, action handlers, `canPublish`, and `canSubscribe`. See [Access Control](/docs/actors/access-control). +- **Authorize actions explicitly.** Check the caller's role in each action handler and throw `forbidden` for unauthorized access. +- **Gate event subscriptions and queue publishes.** Use `canSubscribe` and `canPublish` hooks to restrict which clients can subscribe to events or publish to queues. + +## Clients + +- **Dispose connections and/or client when not in use (JavaScript client).** Call `conn.dispose()` or `client.dispose()` when no longer needed to free resources. React and SwiftUI clients handle this automatically. See [Connection Lifecycle](/docs/clients/javascript#connection-lifecycle). + +_Source doc path: /docs/general/production-checklist_ diff --git a/.agents/skills/ai-agent/reference/general/registry-configuration.md b/.agents/skills/ai-agent/reference/general/registry-configuration.md new file mode 100644 index 0000000..3574c4a --- /dev/null +++ b/.agents/skills/ai-agent/reference/general/registry-configuration.md @@ -0,0 +1,32 @@ +# Registry Configuration + +> Source: `src/content/docs/general/registry-configuration.mdx` +> Canonical URL: https://rivet.dev/docs/general/registry-configuration +> Description: This page documents the configuration options available when setting up a RivetKit registry. The registry configuration is passed to the `setup()` function. + +--- +## Example Configurations + +### Basic Setup + +### Connecting to Rivet Engine + +## Starting Your App + +After configuring your registry, start it: + +See [Runtime Modes](/docs/general/runtime-modes) for details on when to use each mode. + +## Environment Variables + +Many configuration options can be set via environment variables. See [Environment Variables](/docs/general/environment-variables) for a complete reference. + +## Configuration Reference + +## Related + +- [Actor Configuration](/docs/general/actor-configuration): Configure individual actors +- [HTTP Server Setup](/docs/general/http-server): Set up HTTP routing and middleware +- [Architecture](/docs/general/architecture): Understand how RivetKit works + +_Source doc path: /docs/general/registry-configuration_ diff --git a/.agents/skills/ai-agent/reference/general/runtime-modes.md b/.agents/skills/ai-agent/reference/general/runtime-modes.md new file mode 100644 index 0000000..43ba986 --- /dev/null +++ b/.agents/skills/ai-agent/reference/general/runtime-modes.md @@ -0,0 +1,99 @@ +# Runtime Modes + +> Source: `src/content/docs/general/runtime-modes.mdx` +> Canonical URL: https://rivet.dev/docs/general/runtime-modes +> Description: RivetKit supports two runtime modes for running your actors: + +--- +- **Serverless**: Default mode. Responds to HTTP requests and scales automatically. +- **Runners**: Background processes without HTTP endpoints. Only needed for advanced scenarios. + +## Serverless + +Serverless is the default and recommended mode. Rivet sends HTTP requests to your backend to run actor logic, allowing your infrastructure to scale automatically. + +### Benefits + +- **Platform support**: Works with serverless platforms (Vercel, Cloudflare Workers, etc.) +- **Scale to zero**: No cost when idle +- **Edge deployments**: Easier to deploy to edge locations +- **Preview deployments**: Integrates with preview deployments on platforms like Vercel and Railway +- **Efficient autoscaling**: Request-based autoscaling can be faster and more efficient than CPU-based autoscaling depending on the platform + +### Example + +See [Server Setup](/docs/general/http-server/) for more configuration options. + +### Architecture + +When a client creates an actor, it sends a request to the Rivet Engine. The engine then calls `GET /api/rivet/start` on your serverless backend to run the actor. + +Serverless architecture diagram + +### Advanced + +#### Endpoints + +Rivet exposes the following endpoints: + +- `GET /api/rivet/metadata`: Validates configuration +- `GET /api/rivet/start`: Runs an actor + +You should never call these endpoints yourself, this is included purely for comprehension of how Rivet works under the hood. + +#### Timeouts + +Serverless platforms like Vercel have function timeouts. Rivet handles this automatically by migrating actors between function invocations, preserving state through `ctx.state`. Write your code as if it runs forever, Rivet handles the rest. + +Read more about [how we handle timeouts](/blog/2025-10-20-how-we-built-websocket-servers-for-vercel-functions/#timeouts-and-failover). + +#### Shutdown Sequence + +Each serverless request has a configurable lifespan (`requestLifespan`, default: 60 minutes). Set this to match your platform's function timeout (e.g. `requestLifespan: 3600` for Vercel Pro). + +When the request nears its lifespan, the engine reserves a grace period (`serverless_drain_grace_period`, default: 10 seconds) at the end to gracefully stop actors. For example, with a 3600-second lifespan, actors begin stopping at 3590 seconds. After the full lifespan elapses, the connection is forcibly closed and any remaining actors are rescheduled. + +See [Limits](/docs/actors/limits#serverless-shutdown) for configuration details. + +## Runners + +Runners run actors as long-running background processes without exposing an HTTP endpoint. + +### When to Use Runners + +- **No HTTP server**: Your app does not or cannot expose an HTTP server +- **No load balancer**: You don't have a load balancer to distribute HTTP requests across your servers +- **Custom scaling**: You have custom scaling requirements + +### Example + +The runner runs in the background, ready to run actors. + +### Architecture + +On startup, your backend calls `registry.startEnvoy()` which opens a persistent connection to the Rivet Engine. When a client creates an actor, the engine sends a command through this connection to start the actor on your backend. + +Runners architecture diagram + +### Configuration + +#### Runner Pool + +Use `RIVET_RUNNER` to assign runners to a pool. This lets you control which runners handle specific actors. + +```bash +RIVET_RUNNER=gpu-workers +``` + +See [Pool Configuration](/docs/general/pool-configuration) for how pools are scaled, drained on version upgrades, and rate-limited during actor eviction. + +## Comparison + +| Mode | Method | Use Case | +|------|--------|----------| +| Auto | `registry.start()` | Simplest setup. Starts server, serves static files, and runs actors. | +| Serverless | `registry.serve()` | Fetch handler for serverless platforms | +| Serverless | `registry.handler()` | Integrating with existing routers (Hono, Elysia, etc.) | +| Runner | `registry.startEnvoy()` | Long-running processes without HTTP endpoints | + +_Source doc path: /docs/general/runtime-modes_ diff --git a/.agents/skills/ai-agent/reference/general/wasm-vs-native-sdk.md b/.agents/skills/ai-agent/reference/general/wasm-vs-native-sdk.md new file mode 100644 index 0000000..18cdd13 --- /dev/null +++ b/.agents/skills/ai-agent/reference/general/wasm-vs-native-sdk.md @@ -0,0 +1,79 @@ +# WASM vs Native SDK + +> Source: `src/content/docs/general/wasm-vs-native-sdk.mdx` +> Canonical URL: https://rivet.dev/docs/general/wasm-vs-native-sdk +> Description: RivetKit runs your actors on a native or a WebAssembly runtime depending on your platform. + +--- +RivetKit ships two runtimes for executing actor logic. Most projects use the +native runtime automatically. Edge and serverless platforms that cannot run +native binaries use the WebAssembly runtime. + +- **Native**: Default. Runs on Node.js and Bun via native bindings. Best performance. +- **WebAssembly (wasm)**: Runs anywhere a `WebAssembly.Module` can be instantiated, including Cloudflare Workers, Supabase Edge Functions, and Deno Deploy. + +## Native runtime + +The native runtime is the default and requires no configuration. It loads +platform-specific native bindings for the best performance and full feature +support on Node.js and Bun. + +## WebAssembly runtime + +Edge platforms run on isolates (V8, Deno) that cannot load native binaries, so +RivetKit provides a WebAssembly build of its core runtime in the +`@rivetkit/rivetkit-wasm` package. You select it with `runtime: "wasm"` and pass +the wasm bindings and binary through the `wasm` option. + +### Recommended: use a platform package + +For supported platforms, use the dedicated package instead of wiring the wasm +runtime by hand. They install the wasm runtime, load the binary, and (on +Cloudflare) provide the outbound WebSocket the engine tunnel needs. + +- **Cloudflare Workers**: [`@rivetkit/cloudflare-workers`](/docs/actors/quickstart/cloudflare) +- **Supabase Edge Functions**: [`@rivetkit/supabase`](/docs/actors/quickstart/supabase) + +```typescript @nocheck +// Cloudflare Workers +import { actor } from "rivetkit"; +import { createHandler } from "@rivetkit/cloudflare-workers"; + +const counter = actor({ state: { count: 0 }, actions: {} }); + +export default createHandler({ use: { counter } }); +``` + +### Manual configuration + +For platforms without a dedicated package, configure the wasm runtime directly. +Pass the bindings from `@rivetkit/rivetkit-wasm` and the wasm binary as +`initInput`. `initInput` accepts a `Uint8Array`, `URL`, `Response`, or a +`WebAssembly.Module`. + +```typescript @nocheck +import { actor, setup } from "rivetkit"; +import * as wasmBindings from "@rivetkit/rivetkit-wasm"; +import wasmModule from "@rivetkit/rivetkit-wasm/rivetkit_wasm_bg.wasm"; + +const counter = actor({ state: { count: 0 }, actions: {} }); + +const registry = setup({ + runtime: "wasm", + wasm: { bindings: wasmBindings, initInput: wasmModule }, + use: { counter }, +}); +``` + +On platforms without an outbound `new WebSocket(url)` constructor (such as +Cloudflare Workers), you must also install a fetch-based `globalThis.WebSocket` +shim so the actor can open its tunnel to the engine. The platform packages handle +this for you, which is why they are recommended. + +## Related + +- [Runtime Modes](/docs/general/runtime-modes) +- [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) +- [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) + +_Source doc path: /docs/general/wasm-vs-native-sdk_ diff --git a/.agents/skills/ai-agent/reference/self-hosting/configuration.md b/.agents/skills/ai-agent/reference/self-hosting/configuration.md new file mode 100644 index 0000000..a71d16e --- /dev/null +++ b/.agents/skills/ai-agent/reference/self-hosting/configuration.md @@ -0,0 +1,74 @@ +# Configuration + +> Source: `src/content/docs/self-hosting/configuration.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/configuration +> Description: Rivet Engine can be configured through environment variables or configuration files. + +--- +The full JSON Schema for the configuration is available at [/docs/engine-config-schema.json](/docs/engine-config-schema.json). + +## Configuration Sources + +Rivet supports JSON, JSON5, JSONC, YAML, YML, and environment variable configurations. + +**Environment Variables** + +Use the `RIVET__` prefix with `__` as separator to configure properties in the config. For example: set the `RIVET__database__postgres__url` environment variable for `database.postgres.url`. + +**Configuration Paths** + +Configuration files are automatically discovered in platform-specific directories: + +- Linux: `/etc/rivet/config.json` +- macOS: `/Library/Application Support/rivet/config.json` +- Windows: `C:\ProgramData\rivet\config.json` + +**Multiple Files** + +Multiple configuration files in the same directory are loaded and merged together. For example: `/etc/rivet/config.json` and `/etc/rivet/database.json` will be merged together. + +**Override Configuration Path** + +You can override the default configuration path using the `--config` flag: + +```bash +# Load from a specific file +rivet-engine --config /path/to/config.json + +# Load from a directory +rivet-engine --config /etc/rivet + +# Load multiple paths (merged in order) +rivet-engine --config /etc/rivet/base.json --config /etc/rivet/override.json +``` + +## Configuration Reference + +### Pegboard Envoy Load Balancing + +`pegboard.envoy_load_balancer` supports the `hash` strategy for hash-ring-based envoy selection: + +```json +{ + "pegboard": { + "envoy_load_balancer": { + "hash": { + "virtual_nodes": 8, + "samples": 2, + "max_scan": 16, + "use_snapshot_read": true + } + } + } +} +``` + +Use `samples: 1` for a uniform random pick that skips slot reads. Use `samples >= 2` for power-of-K choices over envoy slot counts. Treat `virtual_nodes` as an operational invariant once envoys have registered. + +## Related + +- RivetKit actor runtime persistence lives in SQLite. Existing actor KV data is imported into SQLite the first time an actor wakes on the migrated runtime, then the original KV data is left frozen for downgrade safety. +- [PostgreSQL](/docs/self-hosting/postgres): Configure the experimental PostgreSQL backend +- [File System](/docs/self-hosting/filesystem): Configure file system storage for development + +_Source doc path: /docs/self-hosting/configuration_ diff --git a/.agents/skills/ai-agent/reference/self-hosting/docker-compose.md b/.agents/skills/ai-agent/reference/self-hosting/docker-compose.md new file mode 100644 index 0000000..8f2cea1 --- /dev/null +++ b/.agents/skills/ai-agent/reference/self-hosting/docker-compose.md @@ -0,0 +1,188 @@ +# Docker Compose + +> Source: `src/content/docs/self-hosting/docker-compose.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/docker-compose +> Description: Deploy Rivet Engine with docker-compose for multi-container setups. + +--- +## Quick Start + +### Create docker-compose.yaml + +Create a `docker-compose.yaml` in your project root: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - rivet-data:/data + environment: + RIVET__FILE_SYSTEM__PATH: "/data" + restart: unless-stopped + +volumes: + rivet-data: +``` + +### Start the engine + +```bash +docker-compose up -d +``` + +## Connecting Your Project + +Once the engine is running, add your app as a service in the same Compose file. + +### Create your server + +Follow the [quickstart](/docs/actors/quickstart/backend) to create a working server with actors. + +### Create a Dockerfile + +Create a `Dockerfile` in your project root: + +```dockerfile @nocheck +FROM node:22-slim +WORKDIR /app +COPY package.json pnpm-lock.yaml ./ +RUN corepack enable && pnpm install --frozen-lockfile +COPY . . +RUN pnpm build +CMD ["node", "dist/index.js"] +``` + +### Add your app to docker-compose.yaml + +Update your `docker-compose.yaml` to include your app alongside the engine: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - rivet-data:/data + environment: + RIVET__FILE_SYSTEM__PATH: "/data" + restart: unless-stopped + + my-app: + build: . + environment: + RIVET_ENDPOINT: "http://default:admin@rivet-engine:6420" + depends_on: + - rivet-engine + restart: unless-stopped + +volumes: + rivet-data: +``` + +`RIVET_ENDPOINT` tells your app to connect to the engine as a runner instead of running standalone. The URL uses the format `http://namespace:token@host:port`. Inside the Docker network, your app reaches the engine at `rivet-engine:6420`. See [Endpoints](/docs/general/endpoints) for all options. + +### Start the services + +```bash +docker-compose up -d +``` + +### Register your runner with the engine + +### Dashboard + +1. Open the Rivet Engine dashboard at `http://localhost:6420`. +2. Enter your admin token when prompted. +3. In the namespace sidebar, click **Settings**. +4. Click **Add Provider**, then choose **Custom**. +5. Click **Next** (these settings can be changed later). +6. Click **Next** (you can safely skip the env ar step for Docker Compose). +5. Go to **Confirm Connection**, enter your app endpoint (`http://my-app:6420/api/rivet`), then click **Add**. + +### CLI (curl) + +Register your runner programmatically via the engine API: + +```bash @nocheck +curl -X PUT "http://localhost:6420/runner-configs/default?namespace=default" \ + -H "Content-Type: application/json" \ + -d '{ + "datacenters": { + "default": { + "normal": {} + } + } + }' +``` + +## Configuration + +### Config File + +Mount a JSON configuration file in your `docker-compose.yaml`: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - ./rivet-config.json:/etc/rivet/config.json:ro + - rivet-data:/data + restart: unless-stopped + +volumes: + rivet-data: +``` + +Create `rivet-config.json` in the same directory as your `docker-compose.yaml`. See the [Configuration](/docs/self-hosting/configuration) docs for all available options and the full [JSON Schema](/docs/engine-config-schema.json). + +```json +{ + "postgres": { + "url": "postgresql://rivet:password@postgres:5432/rivet" + } +} +``` + +### Postgres Setup + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +```yaml +services: + postgres: + image: postgres:15 + environment: + POSTGRES_DB: rivet + POSTGRES_USER: rivet + POSTGRES_PASSWORD: rivet_password + volumes: + - postgres-data:/var/lib/postgresql/data + restart: unless-stopped + + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + environment: + RIVET__POSTGRES__URL: postgresql://rivet:rivet_password@postgres:5432/rivet + depends_on: + - postgres + restart: unless-stopped + +volumes: + postgres-data: +``` + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/docker-compose_ diff --git a/.agents/skills/ai-agent/reference/self-hosting/docker-container.md b/.agents/skills/ai-agent/reference/self-hosting/docker-container.md new file mode 100644 index 0000000..e6983ae --- /dev/null +++ b/.agents/skills/ai-agent/reference/self-hosting/docker-container.md @@ -0,0 +1,150 @@ +# Docker Container + +> Source: `src/content/docs/self-hosting/docker-container.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/docker-container +> Description: Run Rivet Engine in a single Docker container. + +--- +## Quick Start + +### Start the engine + +```bash +docker run -d \ + --name rivet-engine \ + -p 6420:6420 \ + -v rivet-data:/data \ + -e RIVET__FILE_SYSTEM__PATH="/data" \ + rivetdev/engine:latest +``` + +### Verify the engine is running + +```bash +curl http://localhost:6420/health +``` + +## Connecting Your Project + +Once the engine is running, connect your app to it. + +### Create your server + +Follow the [quickstart](/docs/actors/quickstart/backend) to create a working server with actors. + +### Start your app with RIVET_ENDPOINT + +Set `RIVET_ENDPOINT` to tell your app to connect to the engine as a runner instead of running standalone: + +```bash @nocheck +RIVET_ENDPOINT="http://default:admin@host.docker.internal:6420" npm start +``` + +If running your app outside of Docker, use `localhost` instead of `host.docker.internal`: + +```bash @nocheck +RIVET_ENDPOINT="http://default:admin@localhost:6420" npm start +``` + +See [Endpoints](/docs/general/endpoints) for all options. + +### Register your runner with the engine + +### Dashboard + +1. Open the Rivet Engine dashboard at `http://localhost:6420`. +2. Enter your admin token when prompted. +3. In the namespace sidebar, click **Settings**. +4. Click **Add Provider**, then choose **Custom**. +5. Click **Next**. +6. Go to **Confirm Connection**, enter your app endpoint, then click **Add**. + +### CLI (curl) + +Register your runner programmatically via the engine API: + +```bash @nocheck +curl -X PUT "http://localhost:6420/runner-configs/default?namespace=default" \ + -H "Content-Type: application/json" \ + -d '{ + "datacenters": { + "default": { + "normal": {} + } + } + }' +``` + +## Configuration + +### Environment Variables + +Configure Rivet using environment variables: + +```bash +docker run -d \ + --name rivet-engine \ + -p 6420:6420 \ + -v rivet-data:/data \ + -e RIVET__FILE_SYSTEM__PATH="/data" \ + -e RIVET__POSTGRES__URL="postgresql://postgres:password@localhost:5432/db" \ + rivetdev/engine:latest +``` + +### Config File + +Mount a JSON configuration file: + +```bash +docker run -d \ + --name rivet-engine \ + -p 6420:6420 \ + -v rivet-data:/data \ + -v $(pwd)/rivet-config.json:/etc/rivet/config.json:ro \ + rivetdev/engine:latest +``` + +Create `rivet-config.json` in your working directory. See the [Configuration](/docs/self-hosting/configuration) docs for all available options and the full [JSON Schema](/docs/engine-config-schema.json). + +```json +{ + "postgres": { + "url": "postgresql://postgres:password@localhost:5432/db" + } +} +``` + +### Postgres Setup + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +```bash +# Create network +docker network create rivet-net + +# Run PostgreSQL +docker run -d \ + --name postgres \ + --network rivet-net \ + -e POSTGRES_DB=rivet \ + -e POSTGRES_USER=rivet \ + -e POSTGRES_PASSWORD=rivet_password \ + -v postgres-data:/var/lib/postgresql/data \ + postgres:15 + +# Run Rivet Engine +docker run -d \ + --name rivet-engine \ + --network rivet-net \ + -p 6420:6420 \ + -e RIVET__POSTGRES__URL="postgresql://rivet:rivet_password@postgres:5432/rivet" \ + rivetdev/engine +``` + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- Use [Docker Compose](/docs/self-hosting/docker-compose) for multi-container setups +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/docker-container_ diff --git a/.agents/skills/ai-agent/reference/self-hosting/filesystem.md b/.agents/skills/ai-agent/reference/self-hosting/filesystem.md new file mode 100644 index 0000000..30f7bdb --- /dev/null +++ b/.agents/skills/ai-agent/reference/self-hosting/filesystem.md @@ -0,0 +1,47 @@ +# File System + +> Source: `src/content/docs/self-hosting/filesystem.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/filesystem +> Description: The file system backend stores all data on the local disk. This is suitable for single-node deployments, development, and testing. + +--- +For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based); for multi-node deployments, PostgreSQL is the recommended backend today but remains experimental as we evaluate the best fit for scalability and performance, and Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB. + +## Configuration + +```json Configuration-file +{ + "database": { + "file_system": { + "path": "/var/lib/rivet/data" + } + } +} +``` + +```bash Environment-variables +RIVET__database__file_system__path="/var/lib/rivet/data" +``` + +## Default Paths + +If no path is specified, Rivet uses platform-specific default locations: + +- Linux: `~/.local/share/rivet-engine/db` +- macOS: `~/Library/Application Support/rivet-engine/db` +- Windows: `%APPDATA%\rivet-engine\db` + +When running in a container or as a service, the path defaults to `./data/db` relative to the working directory. + +## When to Use File System + +The file system backend is ideal for: + +- Local development +- Single-node deployments +- Testing and prototyping +- Air-gapped environments without database infrastructure + +If you need a production-ready Rivet deployment today, use this backend for smaller single-node setups; for multi-node deployments, PostgreSQL is the recommended backend today though still experimental, and Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +_Source doc path: /docs/self-hosting/filesystem_ diff --git a/.agents/skills/ai-agent/reference/self-hosting/foundationdb.md b/.agents/skills/ai-agent/reference/self-hosting/foundationdb.md new file mode 100644 index 0000000..b8331bb --- /dev/null +++ b/.agents/skills/ai-agent/reference/self-hosting/foundationdb.md @@ -0,0 +1,35 @@ +# FoundationDB (Enterprise) + +> Source: `src/content/docs/self-hosting/foundationdb.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/foundationdb +> Description: FoundationDB is the recommended storage backend for scalable production Rivet deployments. + +--- +FoundationDB requires an enterprise license. Contact [enterprise support](https://rivet.dev/sales) for setup guidance and access. + +## Overview + +FoundationDB is the recommended storage backend for scalable, production-ready Rivet deployments. It is a distributed, ordered key-value store originally built by Apple. + +FoundationDB powers some of the largest infrastructure in the world: + +- **Apple**: iCloud and other Apple services +- **Snowflake**: Cloud data platform metadata layer +- **Datadog**: Observability and monitoring platform +- **Tigris Data**: Globally distributed object storage + +Its strict serializability guarantees, fault tolerance, and ability to scale linearly across nodes make it the ideal backend for Rivet's actor state and orchestration layer. + +## Why FoundationDB + +| | RocksDB (File System) | PostgreSQL | FoundationDB | +|---|---|---|---| +| **Scalability** | Single node | Primary/replica failover | Linear horizontal scaling | +| **Fault tolerance** | None | Primary/replica failover | Automatic recovery with no data loss | +| **Production readiness** | Development and small deployments | Experimental for multi-node | Battle-tested at global scale | + +## Getting Started + +FoundationDB configuration and cluster setup are handled as part of enterprise onboarding. Contact [enterprise support](https://rivet.dev/sales) to get started. + +_Source doc path: /docs/self-hosting/foundationdb_ diff --git a/.agents/skills/ai-agent/reference/self-hosting/install.md b/.agents/skills/ai-agent/reference/self-hosting/install.md new file mode 100644 index 0000000..344be8e --- /dev/null +++ b/.agents/skills/ai-agent/reference/self-hosting/install.md @@ -0,0 +1,32 @@ +# Installing Rivet Engine + +> Source: `src/content/docs/self-hosting/install.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/install +> Description: Install Rivet Engine using Docker, binaries, or a source build. + +--- +For more options: + +- [Docker Container](/docs/self-hosting/docker-container) for persistent storage, configuration, and production setups +- [Docker Compose](/docs/self-hosting/docker-compose) for multi-container deployments with PostgreSQL + +## Docker + +```bash +docker run -p 6420:6420 rivetdev/engine +``` + +## Prebuilt Binaries + + Prebuilt binaries coming soon + +## Build From Source + +```bash +git clone https://github.com/rivet-dev/rivet.git +cd rivet +cargo build --release -p rivet-engine +./target/release/rivet-engine +``` + +_Source doc path: /docs/self-hosting/install_ diff --git a/.agents/skills/ai-agent/reference/self-hosting/kubernetes.md b/.agents/skills/ai-agent/reference/self-hosting/kubernetes.md new file mode 100644 index 0000000..a2c619c --- /dev/null +++ b/.agents/skills/ai-agent/reference/self-hosting/kubernetes.md @@ -0,0 +1,236 @@ +# Kubernetes + +> Source: `src/content/docs/self-hosting/kubernetes.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/kubernetes +> Description: Deploy production-ready Rivet Engine to Kubernetes with PostgreSQL storage. + +--- +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Prerequisites + +- Kubernetes cluster +- `kubectl` configured +- [Metrics server](https://github.com/kubernetes-sigs/metrics-server) (required for HPA) — included by default in most distributions (k3d, GKE, EKS, AKS) + +## Deploy Rivet Engine + + +### Download Manifests + + Download the `self-host/k8s/engine` directory from the Rivet repository: + + ```bash + npx giget@latest gh:rivet-dev/rivet/self-host/k8s/engine rivet-k8s + cd rivet-k8s + ``` + + + +### Configure Engine + + In `02-engine-configmap.yaml`, set `public_url` to your engine's external URL. + + + +### Configure PostgreSQL + + In `11-postgres-secret.yaml`, update the PostgreSQL password. See [Using a Managed PostgreSQL Service](#using-a-managed-postgresql-service) for external databases. + + + +### Configure Admin Token + + Generate a secure admin token and save it somewhere safe: + + ```bash + openssl rand -hex 32 + ``` + + Create the namespace and store the token as a Kubernetes secret: + + ```bash + kubectl create namespace rivet-engine + kubectl -n rivet-engine create secret generic rivet-secrets --from-literal=admin-token=YOUR_TOKEN_HERE + ``` + + + +### Deploy + + ```bash + # Apply all manifests + kubectl apply -f . + + # Wait for all pods to be ready + kubectl -n rivet-engine wait --for=condition=ready pod -l app=nats --timeout=300s + kubectl -n rivet-engine wait --for=condition=ready pod -l app=postgres --timeout=300s + kubectl -n rivet-engine wait --for=condition=ready pod -l app=rivet-engine --timeout=300s + + # Verify all pods are running + kubectl -n rivet-engine get pods + ``` + + + +### Access the Engine + + Visit `/ui` on your `public_url` to access the dashboard. + + +## Connecting Your Project + +### Create your server + +Follow the [quickstart](/docs/actors/quickstart/backend) to create a working server with actors. + +### Create Kubernetes manifests + +Create these manifest files for your app: + +```yaml deployment.yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: rivetkit-app + namespace: your-namespace +spec: + replicas: 1 + selector: + matchLabels: + app: rivetkit-app + template: + metadata: + labels: + app: rivetkit-app + spec: + # Allow enough time for actors to gracefully stop on SIGTERM. + # The runner waits up to 30m for actors to finish. + # Add buffer for runner shutdown overhead after actors stop. + # See: /docs/actors/versions#graceful-shutdown-sigterm + terminationGracePeriodSeconds: 2100 + containers: + - name: rivetkit-app + image: registry.example.com/your-team/rivetkit-app:latest + envFrom: + - secretRef: + name: rivetkit-secrets +``` + +```yaml service.yaml +apiVersion: v1 +kind: Service +metadata: + name: rivetkit-app + namespace: your-namespace +spec: + selector: + app: rivetkit-app + ports: + - name: http + port: 8080 + targetPort: 8080 +``` + +### Configure the endpoint + +Create `rivetkit-secrets.yaml` with `RIVET_ENDPOINT` pointing to the engine. This tells your app to connect as a runner instead of running standalone. See [Endpoints](/docs/general/endpoints) for all options. + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: rivetkit-secrets + namespace: your-namespace +type: Opaque +stringData: + RIVET_ENDPOINT: http://my-app:your-admin-token@your-engine.example.com +``` + +### Deploy your app + +```bash +kubectl apply -f rivetkit-secrets.yaml +kubectl apply -f deployment.yaml +kubectl apply -f service.yaml +``` + +### Register your runner with the engine + +### Dashboard + +1. Open the Rivet Engine dashboard in your browser. +2. Enter your admin token when prompted. +3. In the namespace sidebar, click **Settings**. +4. Click **Add Provider**, then choose **Custom**. +5. Click **Next**. +6. Go to **Confirm Connection**, enter your app endpoint (e.g. `http://rivetkit-app.your-namespace:8080/api/rivet`), then click **Add**. + +### CLI (curl) + +Register your runner programmatically via the engine API: + +```bash @nocheck +curl -X PUT "https://your-engine.example.com/runner-configs/default?namespace=default" \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer your-admin-token" \ + -d '{ + "datacenters": { + "default": { + "normal": {} + } + } + }' +``` + +## Advanced + +### Using a Managed PostgreSQL Service + +If you prefer to use a managed PostgreSQL service (e.g. Amazon RDS, Cloud SQL, Azure Database) instead of the bundled Postgres deployment: + +- Update the `postgres.url` connection string in `02-engine-configmap.yaml` to point to your managed instance +- Delete the bundled PostgreSQL manifests: + - `10-postgres-configmap.yaml` + - `11-postgres-secret.yaml` + - `12-postgres-statefulset.yaml` + - `13-postgres-service.yaml` + +### Applying Configuration Updates + +When making subsequent changes to `02-engine-configmap.yaml`, restart the engine pods to pick up the new configuration: + +```bash +kubectl apply -f 02-engine-configmap.yaml +kubectl -n rivet-engine rollout restart deployment/rivet-engine +``` + +### Ingress and Load Balancer Timeouts + +Rivet uses long-lived WebSocket connections for both client traffic (browsers, SDKs) and envoy traffic (actor hosts connecting back to the engine). Default Ingress and cloud load balancer idle timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +Raise the idle / read / send timeout on every Ingress and load balancer in front of the engine to at least 1 hour (`3600` seconds). Examples: + +- **NGINX Ingress** (annotations on the Ingress): + + ```yaml + nginx.ingress.kubernetes.io/proxy-read-timeout: "3600" + nginx.ingress.kubernetes.io/proxy-send-timeout: "3600" + ``` + +- **AWS Load Balancer Controller (ALB)**: + + ```yaml + alb.ingress.kubernetes.io/load-balancer-attributes: idle_timeout.timeout_seconds=3600 + ``` + +- **GCE Ingress (GKE)**: set `timeoutSec: 3600` on the `BackendConfig` referenced by the Service. + +The same guidance applies to the load balancer fronting your RivetKit app, since envoys connect to it over WebSocket. + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all engine config options + +_Source doc path: /docs/self-hosting/kubernetes_ diff --git a/.agents/skills/ai-agent/reference/self-hosting/multi-region.md b/.agents/skills/ai-agent/reference/self-hosting/multi-region.md new file mode 100644 index 0000000..2ecca85 --- /dev/null +++ b/.agents/skills/ai-agent/reference/self-hosting/multi-region.md @@ -0,0 +1,10 @@ +# Multi-Region + +> Source: `src/content/docs/self-hosting/multi-region.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/multi-region +> Description: Rivet Engine supports scaling transparently across multiple regions. + +--- +Documentation coming soon + +_Source doc path: /docs/self-hosting/multi-region_ diff --git a/.agents/skills/ai-agent/reference/self-hosting/postgres.md b/.agents/skills/ai-agent/reference/self-hosting/postgres.md new file mode 100644 index 0000000..e935246 --- /dev/null +++ b/.agents/skills/ai-agent/reference/self-hosting/postgres.md @@ -0,0 +1,192 @@ +# PostgreSQL + +> Source: `src/content/docs/self-hosting/postgres.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/postgres +> Description: Configure PostgreSQL for self-hosted Rivet deployments. + +--- +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Basic Configuration + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://user:password@host:5432/database" + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://user:password@host:5432/database" +``` + +## Managed Postgres Compatibility + +Some hosted PostgreSQL platforms require additional configuration due to platform-specific restrictions. + +### PlanetScale + +Use direct connection (not connection pooler). + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://pscale_api_.:@.pg.psdb.cloud:5432/postgres?sslmode=require", + "unstable_disable_lock_customization": true + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://pscale_api_.:@.pg.psdb.cloud:5432/postgres?sslmode=require" +RIVET__database__postgres__unstable_disable_lock_customization=true +``` + +### Supabase + +Use direct connection on port `5432` (not connection pooler). + +#### Without SSL + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=disable", + "unstable_disable_lock_customization": true + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=disable" +RIVET__database__postgres__unstable_disable_lock_customization=true +``` + +#### With SSL + +Download the root certificate from your Supabase dashboard and specify its path. See [Supabase SSL Enforcement](https://supabase.com/docs/guides/platform/ssl-enforcement) for details. + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=require", + "unstable_disable_lock_customization": true, + "ssl": { + "root_cert_path": "/path/to/supabase-ca.crt" + } + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=require" +RIVET__database__postgres__unstable_disable_lock_customization=true +RIVET__database__postgres__ssl__root_cert_path="/path/to/supabase-ca.crt" +``` + +## SSL/TLS Support + +To enable SSL for Postgres, add `sslmode=require` to your PostgreSQL connection URL: + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://user:password@host.example.com:5432/database?sslmode=require" + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://user:password@host.example.com:5432/database?sslmode=require" +``` + +The `sslmode` parameter controls TLS usage: + +- `disable`: Do not use TLS +- `prefer`: Use TLS if available, otherwise connect without TLS (default) +- `require`: Require TLS connection (fails if TLS is not available) + +To verify the server certificate against a CA or verify the hostname, use custom SSL certificates (see below). + +### Custom SSL Certificates + +For databases using custom certificate authorities (e.g., Supabase) or requiring client certificate authentication, you can specify certificate paths in the configuration: + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://user:password@host:5432/database?sslmode=require", + "ssl": { + "root_cert_path": "/path/to/root-ca.crt", + "client_cert_path": "/path/to/client.crt", + "client_key_path": "/path/to/client.key" + } + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://user:password@host:5432/database?sslmode=require" +RIVET__database__postgres__ssl__root_cert_path="/path/to/root-ca.crt" +RIVET__database__postgres__ssl__client_cert_path="/path/to/client.crt" +RIVET__database__postgres__ssl__client_key_path="/path/to/client.key" +``` + +| Parameter | Description | PostgreSQL Equivalent | +|-----------|-------------|----------------------| +| `root_cert_path` | Path to the root certificate file for verifying the server's certificate | `sslrootcert` | +| `client_cert_path` | Path to the client certificate file for client certificate authentication | `sslcert` | +| `client_key_path` | Path to the client private key file for client certificate authentication | `sslkey` | + +All SSL paths are optional. If not specified, Rivet uses the default system root certificates from Mozilla's root certificate store. + +## Do Not Use Connection Poolers + +Rivet requires direct PostgreSQL connections for session-level features and does not support connection poolers. + +Do not use: + +- PgBouncer +- Supavisor +- AWS RDS Proxy + +## Troubleshooting + +### Permission Denied Errors + +If you see errors like: + +``` +ERROR: permission denied to set parameter "deadlock_timeout" +ERROR: current transaction is aborted, commands ignored until end of transaction block +``` + +Add `unstable_disable_lock_customization: true` to your configuration: + +```json +{ + "database": { + "postgres": { + "url": "postgresql://...", + "unstable_disable_lock_customization": true + } + } +} +``` + +This disables Rivet's attempt to set `lock_timeout = 0` and `deadlock_timeout = 10ms`. Since `lock_timeout` defaults to `0` in PostgreSQL, skipping these settings is safe. Deadlock detection will use the default `1s` timeout instead of `10ms`. + +_Source doc path: /docs/self-hosting/postgres_ diff --git a/.agents/skills/ai-agent/reference/self-hosting/production-checklist.md b/.agents/skills/ai-agent/reference/self-hosting/production-checklist.md new file mode 100644 index 0000000..3cefa5a --- /dev/null +++ b/.agents/skills/ai-agent/reference/self-hosting/production-checklist.md @@ -0,0 +1,53 @@ +# Production Checklist + +> Source: `src/content/docs/self-hosting/production-checklist.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/production-checklist +> Description: Checklist for deploying a self-hosted Rivet Engine to production. + +--- +We recommend passing this page to your coding agent to verify your configuration before deploying. + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +Also review the [general production checklist](/docs/general/production-checklist). + +## Security + +- **Validate that you have an admin token configured.** Generate a strong, random token for engine authentication. See [Configuration](/docs/self-hosting/configuration). +- **Verify your admin token is not exposed publicly.** Do not include the admin token in `RIVET_PUBLIC_ENDPOINT` or anywhere accessible to clients. See [Endpoints](/docs/general/endpoints#public-endpoint). +- **Configure TLS termination.** Ensure connections to the engine are encrypted via a reverse proxy or load balancer. + +## Resources + +- **Set container resource limits.** Recommended at least 1 CPU and 2 GB of RAM per Rivet Engine instance. +- **Configure health checks.** Set up liveness and readiness probes on port `6421` at `/health`. Recommended timeout of 5 seconds. + +## Scaling + +- **Configure autoscaling for the Rivet Engine.** Set target CPU utilization to 70% and memory to 80% to ensure headroom for traffic spikes. In Kubernetes, this is configured via a Horizontal Pod Autoscaler (HPA). +- **Use 2+ engine nodes for redundancy.** Running a single engine node is a single point of failure. Deploy at least two engine instances behind a load balancer. +- **RocksDB only supports a single node.** Do not run multiple RocksDB nodes. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). For multi-node deployments, PostgreSQL is the recommended backend today, though it remains experimental as we evaluate the best fit for scalability and performance. +- **Validate the rate limit on your serverless actor host.** Actor start requests are sent from your engine instances, so they all originate from a small set of IPs. Per-IP rate limits on the actor host will throttle the engine before they would throttle end-user traffic. Size the limit to your peak actor create and wake rate, and configure platform max concurrency (e.g. on GCP Cloud Run) to match your expected concurrent actor count. + +## PostgreSQL + +- **PostgreSQL is recommended for multi-node deployments, but remains experimental.** Validate the deployment carefully before rollout. +- **Configure automated backups.** Set up regular backups for your PostgreSQL database to prevent data loss. +- **Configure failover.** Set up a standby replica with automatic failover to ensure high availability. +- **Use FoundationDB for the most scalable production-ready deployments.** FoundationDB provides the best performance, scalability, and uptime for Rivet. Contact [enterprise support](https://rivet.dev/sales) for FoundationDB guidance. + +## NATS + +- **Use NATS for pub/sub (recommended).** By default, Rivet uses PostgreSQL `LISTEN`/`NOTIFY` for pub/sub which has limited throughput. NATS significantly improves performance for high-traffic deployments. This is not needed if using RocksDB. See [Configuration](/docs/self-hosting/configuration). +- **Deploy 2+ NATS replicas.** Run at least two NATS replicas for high availability. + +## Monitoring + +- **Configure OpenTelemetry.** The Rivet Engine supports exporting traces and metrics via OpenTelemetry. Set `RIVET_OTEL_ENABLED=1` and `RIVET_OTEL_GRPC_ENDPOINT` to your collector endpoint (defaults to `http://localhost:4317`). Adjust `RIVET_OTEL_SAMPLER_RATIO` to control trace sampling (defaults to `0.001`). See [Configuration](/docs/self-hosting/configuration). +- **Set up alerts for critical metrics.** Monitor engine CPU, memory, request latency, and error rates. Configure alerts to notify your team before issues become outages. + +## Enterprise + +- **Contact [enterprise support](https://rivet.dev/sales) for production-ready deployments.** We can help with architecture review, scaling guidance, and FoundationDB support. + +_Source doc path: /docs/self-hosting/production-checklist_ diff --git a/.agents/skills/ai-agent/reference/self-hosting/railway.md b/.agents/skills/ai-agent/reference/self-hosting/railway.md new file mode 100644 index 0000000..c4bb922 --- /dev/null +++ b/.agents/skills/ai-agent/reference/self-hosting/railway.md @@ -0,0 +1,99 @@ +# Railway Deployment + +> Source: `src/content/docs/self-hosting/railway.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/railway +> Description: Railway provides a simple platform for deploying Rivet Engine with automatic scaling and managed infrastructure. + +--- +## Video Tutorial + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Quick Deploy + +Choose the template that best fits your needs: + +| **Rivet Template** | **Rivet Starter** | +|-------------------|-------------------| +| [![Deploy on Railway](https://railway.com/button.svg)](https://railway.com/deploy/rivet?referralCode=RC7bza&utm_medium=integration&utm_source=template&utm_campaign=generic) | [![Deploy Rivet Starter](https://railway.com/button.svg)](https://railway.com/deploy/rivet-starter) | +| **Blank template** to start fresh | **Complete example** with chat app | +| - Rivet Engine | - Pre-configured Rivet Engine | +| - PostgreSQL database | - Example chat application with Actors | +| - Basic configuration | - PostgreSQL database | +| - Manual setup required | - Rivet Inspector for debugging | +| | - Ready to run immediately | + +You can also use the [Rivet Railway template](https://github.com/rivet-dev/template-railway) as a starting point for your application. + +After deploying either template, you can find the `RIVET__AUTH__ADMIN_TOKEN` under the **Variables** tab in the Railway dashboard. This token is required to access the Rivet Inspector. + +## Manual Deployment + +### Prerequisites + +1. [Railway account](https://railway.app) +2. [Railway CLI](https://docs.railway.app/develop/cli) (optional) + +### Step 1: Create New Project + +```bash +# Using Railway CLI +railway init + +# Or create via dashboard +# https://railway.app/new +``` + +### Step 2: Add Services + +#### Deploy PostgreSQL Database + +1. Click "New Service" → "Database" → "PostgreSQL" +2. Railway automatically provisions and configures PostgreSQL +3. Note the connection string from the service variables + +#### Deploy Rivet Engine + +1. Click "New Service" → "Docker Image" +2. Set image: `rivetdev/engine:latest` +3. Configure environment variables: + - `RIVET__POSTGRES__URL=${{Postgres.DATABASE_URL}}` +4. Configure graceful shutdown (see [Graceful Shutdown](#graceful-shutdown) below) + +### Step 3: Deploy Your Application + +Follow the [Railway Quick Start guide](https://docs.railway.com/quick-start) to deploy your repository: + +1. Connect your GitHub account to Railway +2. Select your repository containing your Rivet application +3. Railway will automatically detect and deploy your application +4. Configure environment variables for your application: + - `RIVET_ENDPOINT=${{Rivet.RAILWAY_PRIVATE_DOMAIN}}` - Points to the Rivet Engine service's private domain + +## WebSocket Timeouts + +Rivet uses long-lived WebSocket connections for both client traffic (browsers, SDKs) and envoy traffic (actor hosts connecting back to the engine). Railway's HTTP proxy supports WebSockets, but you must make sure no app-side timeout cuts them off. + +If you front the engine with your own reverse proxy (NGINX, Caddy, etc.) inside the Railway service, raise its idle / read timeout to at least 1 hour (`3600` seconds). The same guidance applies to the Railway service hosting your RivetKit app, since envoys connect to it over WebSocket. + +## Graceful Shutdown + +By default, Railway kills the old deploy 0 seconds after sending `SIGTERM` (see [Railway's docs](https://docs.railway.com/deployments/reference#singleton-deploys)), so in-flight requests are dropped and state flushes can be interrupted on every deploy. Rivet ships with a `SIGTERM` handler that drains cleanly, but it only gets to run if Railway is configured to give it time. + +Configure the following under **Settings → Deploy** on your service: + +- **Draining seconds** — the grace window between `SIGTERM` and `SIGKILL`. This is how long Rivet has to finish in-flight work and flush state. See [Railway's deployment teardown docs](https://docs.railway.com/deployments/deployment-teardown). + +Set draining seconds in the dashboard, via `drainingSeconds` in config-as-code, or via the `RAILWAY_DEPLOYMENT_DRAINING_SECONDS` service variable. A reasonable value is **60 seconds**. + +If your start command is a wrapper process (for example `npm start`, `yarn start`, `pnpm start`, or a shell script), the wrapper becomes PID 1 and swallows the signal — your app never drains and Railway force-kills it at the end of the window. + +- Invoke your binary directly as the start command (for example `node dist/index.js`, not `npm start`). +- Or run `dumb-init` / `tini` as PID 1 in your Dockerfile so signals forward to your process. + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/railway_ diff --git a/.agents/skills/ai-agent/reference/self-hosting/render.md b/.agents/skills/ai-agent/reference/self-hosting/render.md new file mode 100644 index 0000000..0bc6d6c --- /dev/null +++ b/.agents/skills/ai-agent/reference/self-hosting/render.md @@ -0,0 +1,131 @@ +# Render Deployment + +> Source: `src/content/docs/self-hosting/render.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/render +> Description: Deploy Rivet Engine to Render with managed PostgreSQL and automatic HTTPS, using the experimental PostgreSQL backend. + +--- +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Prerequisites + +1. A [Render account](https://render.com) +2. A GitHub repository + +## Deploy Rivet Engine + + +### Create the Blueprint Files + + Add these three files to the root of your GitHub repository: + + **render.yaml** + + ```yaml + databases: + - name: rivet-db + plan: basic-256mb + databaseName: rivet + user: rivet + + services: + - type: web + name: rivet-engine + runtime: docker + dockerfilePath: ./Dockerfile.render + plan: starter + healthCheckPath: /health + envVars: + - key: DATABASE_URL + fromDatabase: + name: rivet-db + property: connectionString + - key: RIVET__AUTH__ADMIN_TOKEN + generateValue: true + ``` + + **Dockerfile.render** + + ```dockerfile + FROM rivetdev/engine:latest + + COPY entrypoint.render.sh /entrypoint.render.sh + RUN chmod +x /entrypoint.render.sh + + ENTRYPOINT ["/entrypoint.render.sh"] + ``` + + **entrypoint.render.sh** + + ```bash + #!/bin/sh + + if [ -n "$DATABASE_URL" ]; then + export RIVET__POSTGRES__URL="${DATABASE_URL}?sslmode=disable" + fi + + exec /usr/bin/rivet-engine start + ``` + + Commit and push these files to your repository. + + + +### Deploy to Render + + 1. Go to the [Render Dashboard](https://dashboard.render.com/) + 2. Click **Blueprints** in the left sidebar + 3. Click **New Blueprint Instance** + 4. Connect your GitHub account if you haven't already + 5. Select the repository containing the files from the previous step + 6. Click **Apply** + + Render will automatically create the PostgreSQL database and deploy the Rivet Engine. + + + +### Get Your Admin Token + + 1. Once deployed, go to your **rivet-engine** service in the Render Dashboard + 2. Click the **Environment** tab + 3. Find `RIVET__AUTH__ADMIN_TOKEN` and click the eye icon to reveal the value + 4. Copy this token — you'll need it to access the dashboard + + + +### Access the Rivet Dashboard + + Open your service URL in a browser: + + ``` + https://rivet-engine-xxxx.onrender.com/ui/ + ``` + + Replace `rivet-engine-xxxx` with your actual service name from the Render Dashboard. + + Enter the admin token from the previous step to log in. + + +## WebSocket Timeouts + +Rivet uses long-lived WebSocket connections for both client traffic (browsers, SDKs) and envoy traffic (actor hosts connecting back to the engine). Render's HTTP proxy supports WebSockets, but its default idle timeout will close connections that have no traffic for too long. + +If you front the engine with your own reverse proxy (NGINX, Caddy, etc.) on Render, raise its idle / read timeout to at least 1 hour (`3600` seconds). The same guidance applies to the Render service hosting your RivetKit app, since envoys connect to it over WebSocket. + +## Connecting Your Application + +To connect a RivetKit application to your self-hosted engine, set these environment variables in your app: + +```bash +RIVET_ENDPOINT=https://:@rivet-engine-xxxx.onrender.com +RIVET_PUBLIC_ENDPOINT=https://@rivet-engine-xxxx.onrender.com +``` + +See the [Connect guide](/docs/deploy/custom) for more details on connecting your application. + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/render_ diff --git a/.agents/skills/ai-agent/reference/self-hosting/tls.md b/.agents/skills/ai-agent/reference/self-hosting/tls.md new file mode 100644 index 0000000..63573d2 --- /dev/null +++ b/.agents/skills/ai-agent/reference/self-hosting/tls.md @@ -0,0 +1,22 @@ +# TLS & Certificates + +> Source: `src/content/docs/self-hosting/tls.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/tls +> Description: How Rivet validates TLS root certificates. + +--- +Public CAs (Let's Encrypt, AWS ACM, and so on) work out of the box. You only need to read this page if you're running behind a corporate or private CA. + +Rivet reads the operating system trust store (`/etc/ssl/certs` on Linux, Keychain on macOS, Schannel on Windows) for all outbound HTTPS. Operator-installed corporate CAs live there and are honored automatically. + +To trust a private CA inside the official `rivetdev/engine` image, extend it the standard Debian way: + +```dockerfile +FROM rivetdev/engine:latest +COPY my-corp-ca.crt /usr/local/share/ca-certificates/ +RUN update-ca-certificates +``` + +Rebuild and redeploy. The same approach works for any machine running a Rivet client: install the CA into the OS trust store and Rivet picks it up. + +_Source doc path: /docs/self-hosting/tls_ diff --git a/.agents/skills/chat-room/BASE_SKILL.md b/.agents/skills/chat-room/BASE_SKILL.md new file mode 100644 index 0000000..ca710ba --- /dev/null +++ b/.agents/skills/chat-room/BASE_SKILL.md @@ -0,0 +1,537 @@ +--- +name: "rivetkit" +description: "RivetKit backend and Rivet Actor runtime guidance. Use for building, modifying, debugging, or testing Rivet Actors, registries, serverless/runner modes, deployment, or actor-based workflows." +--- + +# Rivet Actors + +Build high-performance, long-lived, in-memory processes on Rivet's actor runtime. Use this skill whenever HTTP endpoints, databases, or queues no longer meet the requirements for AI agents, realtime collaboration, workflow orchestration, or geo-distributed data. + +## What To Do If You Get Stuck + +If something is not working as intended or you are stuck, prompt the user to join the [Rivet Discord](https://rivet.dev/discord) or file an issue on the [Rivet GitHub](https://github.com/rivet-dev/rivet) to report an issue and get help. + +Provide the user with a pre-generated report with: + +- Symptoms + - If this is happening in local dev, deployed, or both + - The error you're seeing + - Relevant source code related to this +- What you've tried to solve it +- Environment + - RivetKit version + - Runtime (Node, Bun, etc) including version + - If applicable, provider in use (e.g. Vercel, Railway, etc) + - If applicable, HTTP router in use (e.g. Hono, Express, Elysia) + +## Debugging Actors + +Use the inspector HTTP API to examine running actors. These endpoints are accessible through the gateway at `/gateway/{actor_id}/inspector/*`. Key endpoints: + +- `GET /inspector/summary` - full actor snapshot (state, connections, RPCs, queue) +- `GET /inspector/state` / `PATCH /inspector/state` - read/write actor state +- `GET /inspector/connections` - active connections +- `GET /inspector/rpcs` - available actions +- `POST /inspector/action/{name}` - execute an action with `{"args": [...]}` +- `POST /inspector/database/execute` - run SQL with `{"sql": "...", "args": [...]}` or `{"sql": "...", "properties": {...}}` for reads or mutations +- `GET /inspector/queue?limit=50` - queue status +- `GET /inspector/traces?startMs=0&endMs=...&limit=1000` - trace spans (OTLP JSON) +- `GET /inspector/workflow-history` - workflow history and status as JSON (`nameRegistry`, `entries`, `entryMetadata`) +- `POST /inspector/workflow/replay` - replay a workflow from a specific step or from the beginning; returns `409 actor/workflow_in_flight` if the workflow is still running +- `GET /inspector/database/schema` - SQLite tables and views exposed by `c.db` +- `GET /inspector/database/rows?table=...&limit=100&offset=0` - paged SQLite rows for a table or view + +In local dev, no auth token is needed. In production, pass `Authorization: Bearer `, where the inspector token is the actor-specific token auto-generated on first start and persisted in the actor's internal KV at key `0x03`. The Rivet dashboard retrieves this token automatically; for direct API access, fetch it through the management KV endpoint. See the [debugging docs](https://rivet.dev/docs/actors/debugging) for details. + +## Citing Sources + +When providing information from Rivet documentation, cite the canonical URL so users can learn more. Each reference file includes its canonical URL in the header metadata. + +**How to cite:** + +- Use inline links for key concepts: "Use [actor keys](https://rivet.dev/docs/actors/keys) to uniquely identify instances." +- Add a "Learn more" link after explanations for complex topics + +**Finding canonical URLs:** + +The Reference Map below links to reference files. Each file's header contains: + +``` +> Canonical URL: https://rivet.dev/docs/actors/actions +``` + +Use that canonical URL when citing, not the reference file path. + +**Examples:** + +- Actions → `https://rivet.dev/docs/actors/actions` +- React client → `https://rivet.dev/docs/clients/react` +- Self-hosting on Kubernetes → `https://rivet.dev/docs/self-hosting/kubernetes` + +## Version Check + +Before starting any work, check if the user's project is on the latest version of RivetKit (latest: 2.3.4). Look at the `rivetkit` version in the user's `package.json` (check both `dependencies` and `devDependencies`). If the installed version is older than 2.3.4, inform the user and suggest upgrading: + +```bash +npm install rivetkit@2.3.4 +``` + +If the user also uses `@rivetkit/react`, `@rivetkit/next-js`, or other `@rivetkit/*` client packages, suggest upgrading those too. Outdated versions may have known bugs or missing features that cause issues. + +## First Steps + +1. Install RivetKit (latest: 2.3.4) + ```bash + npm install rivetkit@2.3.4 + ``` +2. Define a registry with `setup({ use: { /* actors */ } })`. +3. Call `registry.start()` to start the server. For custom HTTP server integration, use `registry.handler()` with a router like Hono. For serverless deployments, use `registry.serve()`. For runner-only mode, use `registry.startEnvoy()`. +4. Verify `/api/rivet/metadata` returns 200 before deploying. +5. Configure Rivet Cloud or self-hosted engine + - You must configure versioning for production builds. This is not needed for local development. See [Versions & Upgrades](https://rivet.dev/docs/actors/versions). +6. Integrate clients (see client guides below for JavaScript, React, or Swift) +7. Prompt the user if they want to deploy. If so, go to Deploying Rivet Backends. + +For more information, read the quickstart guide relevant to the user's project. + +## Project Setup + +### .gitignore + +Every RivetKit project should have a `.gitignore`. Include at minimum: + +``` +node_modules/ +dist/ +.env +``` + +### .dockerignore + +Every project with a Dockerfile should have a `.dockerignore` to keep the image small and avoid leaking secrets: + +``` +node_modules/ +dist/ +.env +.git/ +``` + +### Dockerfile + +Use this as a base Dockerfile for deploying a RivetKit project. The `RIVET_RUNNER_VERSION` build arg is only needed when self-hosting or using a custom runner (not needed for Rivet Compute). It lets Rivet track which version of the actor is running and drain old actors on deploy. See https://rivet.dev/docs/actors/versions for details. + +```dockerfile +FROM node:24-alpine + +ARG RIVET_RUNNER_VERSION +ENV RIVET_RUNNER_VERSION=$RIVET_RUNNER_VERSION + +WORKDIR /app + +COPY package.json package-lock.json ./ +RUN npm ci + +COPY . . +RUN npm run build --if-present + +CMD ["node", "dist/index.js"] +``` + +Build with: + +```bash +docker build --build-arg RIVET_RUNNER_VERSION=$(date +%s) . +``` + +Adjust the `CMD` to match the project's entry point. If the project uses a different output directory or start command, update accordingly. + +## Error Handling Policy + +- Prefer fail-fast behavior by default. +- Avoid `try/catch` unless it is required for a real recovery path, cleanup boundary, or to add actionable context. +- Never swallow errors. If you add a `catch`, you must handle the error explicitly, at minimum by logging it. +- When you cannot recover, log context and rethrow. + +## State vs Vars: Persistence Rules + +**`c.vars` is ephemeral.** Data in `c.vars` is lost on every restart, crash, upgrade, or sleep/wake cycle. Only use `c.vars` for non-serializable objects (e.g., physics engines, WebSocket references, event emitters, caches) or truly transient runtime data (e.g., current input direction that doesn't matter after disconnect). + +**Persistent storage options.** Any data that must survive restarts belongs in one of these, NOT in `c.vars`: + +- **`c.state`** — CBOR-serializable data for small, bounded datasets. Ideal for configuration, counters, small player lists, phase flags, etc. Keep under 128 KB. Do not store unbounded or growing data here (e.g., chat logs, event histories, spawned entity lists that grow without limit). State is read/written as a single blob on every persistence cycle. +- **`c.kv`** — Key-value store for unbounded data. This is what `c.state` uses under the hood. Supports binary values. Use for larger or variable-size data like user inventories, world chunks, file blobs, or any collection that may grow over time. Keys are scoped to the actor instance. +- **`c.db`** — SQLite database for structured or complex data. Use when you need queries, indexes, joins, aggregations, or relational modeling. Ideal for leaderboards, match histories, player pools, or any data that benefits from SQL. + +**Common mistake:** Storing meaningful game/application data in `c.vars` instead of persisting it. For example, if users can spawn objects in a physics simulation, the spawn definitions (position, size, type) must be persisted in `c.state` (or `c.kv` if unbounded), even though the physics engine handles (non-serializable) live in `c.vars`. On restart, `run()` should recreate the runtime objects from the persisted data. + +## Deploying Rivet Backends + +Assume the user is deploying to Rivet Cloud, unless otherwise specified. If user is self-hosting, read the self-hosting guides below. + +1. Verify that Rivet Actors are working in local dev +2. Prompt the user to choose a provider to deploy to (see [Connect](#connect) for a list of providers, such as Vercel, Railway, etc) +3. Follow the deploy guide for that given provider. You will need to instruct the user when you need manual intervention. + +## API Reference + +The RivetKit OpenAPI specification is available in the skill directory at `openapi.json`. This file documents all HTTP endpoints for managing actors. + +## Misc Notes + +- The Rivet domain is rivet.dev, not rivet.gg + +## TypeScript Caveat: Actor Client Inference + +- In multi-file TypeScript projects, bidirectional actor calls can create a circular type dependency when both actors use `c.client()`. +- Symptoms usually include `c.state` becoming `unknown`, actor methods becoming possibly `undefined`, or `TS2322` / `TS2722` errors after the first cross-actor call. +- If an action returns the result of another actor call, prefer an explicit return type annotation on that action instead of relying on inference through `c.client()`. +- If explicit return types are not enough, use a narrower client or registry type for only the actors that action needs. +- As a last resort, pass `unknown` for the registry type and be explicit that this gives up type safety at that call site. + +## Features + +- **Long-Lived, Stateful Compute**: Each unit of compute is like a tiny server that remembers things between requests – no need to re-fetch data from a database or worry about timeouts. Like AWS Lambda, but with memory and no timeouts. +- **Blazing-Fast Reads & Writes**: State is stored on the same machine as your compute, so reads and writes are ultra-fast. No database round trips, no latency spikes. State is persisted to Rivet for long term storage, so it survives server restarts. +- **Realtime**: Update state and broadcast changes in realtime with WebSockets. No external pub/sub systems, no polling – just built-in low-latency events. +- **Infinitely Scalable**: Automatically scale from zero to millions of concurrent actors. Pay only for what you use with instant scaling and no cold starts. +- **Fault Tolerant**: Built-in error handling and recovery. Actors automatically restart on failure while preserving state integrity and continuing operations. + +## When to Use Rivet Actors + +- **AI agents & sandboxes**: multi-step toolchains, conversation memory, sandbox orchestration. +- **Multiplayer or collaborative apps**: CRDT docs, shared cursors, realtime dashboards, chat. +- **Workflow automation**: background jobs, cron, rate limiters, durable queues, backpressure control. +- **Data-intensive backends**: geo-distributed or per-tenant databases, in-memory caches, sharded SQL. +- **Networking workloads**: WebSocket servers, custom protocols, local-first sync, edge fanout. + +## Minimal Project + +### Backend + +**index.ts** + +### Client Docs + +Use the client SDK that matches your app: + +- [JavaScript Client](/docs/clients/javascript) +- [React Client](/docs/clients/react) +- [Swift Client](/docs/clients/swift) + +## Actor Quick Reference + +### In-Memory State + +Persistent data that survives restarts, crashes, and deployments. State is persisted on Rivet Cloud or Rivet self-hosted, so it survives restarts if the current process crashes or exits. + +### Static Initial State + +### Dynamic Initial State + +[Documentation](/docs/actors/state) + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +[Documentation](/docs/actors/keys) + +### Input + +Pass initialization data when creating actors. Input is only available in `createState` and `onCreate`, so store it in state if you need it later. + +[Documentation](/docs/actors/input) + +### Temporary Variables + +Temporary data that doesn't survive restarts. Use for non-serializable objects (event emitters, connections, etc). + +### Static Initial Vars + +### Dynamic Initial Vars + +[Documentation](/docs/actors/state) + +### Actions + +Actions are the primary way clients and other actors communicate with an actor. + +[Documentation](/docs/actors/actions) + +### Events & Broadcasts + +Events enable real-time communication from actors to connected clients. + +[Documentation](/docs/actors/events) + +### Connections + +Access the current connection via `c.conn` or all connected clients via `c.conns`. Use `c.conn.id` or `c.conn.state` to securely identify who is calling an action. `c.conn` is only available for actions invoked through a connected client; stateless actor-handle calls run without a connection, so guard against that. Connection state is initialized via `connState` or `createConnState`, which receives parameters passed by the client on connect. + +### Static Connection Initial State + +### Dynamic Connection Initial State + +[Documentation](/docs/actors/connections) + +### Queues + +Use queues to process durable messages in order inside a `run` loop. + +[Documentation](/docs/actors/queues) + +### Workflows + +Use workflows when your `run` logic needs durable, replayable multi-step execution. + +[Documentation](/docs/actors/workflows) + +### Actor-to-Actor Communication + +Actors can call other actors using `c.client()`. + +[Documentation](/docs/actors/communicating-between-actors) + +### Scheduling + +Schedule actions to run after a delay or at a specific time. Schedules persist across restarts, upgrades, and crashes. + +[Documentation](/docs/actors/schedule) + +### Destroying Actors + +Permanently delete an actor and its state using `c.destroy()`. + +[Documentation](/docs/actors/destroy) + +### Lifecycle Hooks + +Actors support hooks for initialization, background processing, connections, networking, and state changes. Use `run` for long-lived background loops, and use `c.aborted` or `c.abortSignal` for graceful shutdown. + +[Documentation](/docs/actors/lifecycle) + +### Context Types + +When writing helper functions outside the actor definition, use `*ContextOf` to extract the correct context type. Helpers like `ActionContextOf`, `CreateContextOf`, `ConnContextOf`, and `ConnInitContextOf` are exported from `"rivetkit"`. Do not manually define your own context interface. Always derive it from the actor definition. + +[Documentation](/docs/actors/types) + +### Errors + +Use `UserError` to throw errors that are safely returned to clients. Pass `metadata` to include structured data. Other errors are converted to generic "internal error" for security. + +### Actor + +### Client + +[Documentation](/docs/actors/errors) + +### Low-Level HTTP & WebSocket Handlers + +For custom protocols or integrating libraries that need direct access to HTTP `Request`/`Response` or WebSocket connections, use `onRequest` and `onWebSocket`. + +[HTTP Handler Documentation](/docs/actors/request-handler) · [WebSocket Handler Documentation](/docs/actors/websocket-handler) + +### Icons & Names + +Customize how actors appear in the UI with display names and icons. It's recommended to always provide a name and icon to actors in order to make them easier to distinguish in the dashboard. + +```typescript +import { actor } from "rivetkit"; + +const chatRoom = actor({ + options: { + name: "Chat Room", + icon: "💬", // or FontAwesome: "comments", "chart-line", etc. + }, + // ... +}); +``` + +[Documentation](/docs/actors/appearance) + +## Client Documentation + +Find the full client guides here: + +- [JavaScript Client](/docs/clients/javascript) +- [React Client](/docs/clients/react) +- [Swift Client](/docs/clients/swift) + +## Common Patterns + +Actors scale naturally through isolated state and message-passing. Structure your applications with these patterns: + +[Documentation](/docs/actors/design-patterns) + +### Actor Per Entity + +Create one actor per user, document, or room. Use compound keys to scope entities: + +### Coordinator & Data Actors + +**Data actors** handle core logic (chat rooms, game sessions, user data). **Coordinator actors** track and manage collections of data actors—think of them as an index. + +### Run Loop + +Use a `run` loop for continuous background work inside an actor. Process queue messages in order, run logic on intervals, stream AI responses, or coordinate long-running tasks. + +### Workflow Loop + +Use this pattern for long-lived, durable workflows that initialize resources, process commands in a loop, then clean up. + +[Documentation](/docs/actors/workflows) + +### Actions vs Queues + +- **Actions** are not durable. Use them for realtime reads, ephemeral data, and low-latency communication like player input. +- **Queues** are durable. Use them to serialize mutations through the run loop, avoiding race conditions with SQLite and other local state. Callers can still wait for a response from queued work. + +### Authentication, Security, & CORS + +- Validate credentials in `onBeforeConnect` or `createConnState` and throw an error to reject unauthorized connections. +- Use `c.conn.state` to securely identify users in actions rather than trusting action parameters. +- For cross-origin access, validate the request origin in `onBeforeConnect`. + +[Authentication Documentation](/docs/actors/authentication) · [CORS Documentation](/docs/general/cors) + +### Versions & Upgrades + +When deploying new code, set a version number so Rivet can route new actors to the latest runner and optionally drain old ones. Use a build timestamp, git commit count, or CI build number as the version. It is very important to [configure versioning](/docs/actors/versions) before deploying to production. Without versioning, actors can regress by running on older runner versions, and existing actors will never be forced to migrate to new runners. They will continue running indefinitely on the old runners until they exit. + +[Documentation](/docs/actors/versions) + +### Anti-Patterns + +#### Never build a "god" actor + +Do not put all your logic in a single actor. A god actor serializes every operation through one bottleneck, kills parallelism, and makes the entire system fail as a unit. Split into focused actors per entity. + +#### Never create an actor per request + +Actors are long-lived and maintain state across requests. Creating a new actor for every incoming request throws away the core benefit of the model and wastes resources on actor creation and teardown. Use actors for persistent entities and regular functions for stateless work. + +## Reference Map + +### Actors + +- [Access Control](reference/actors/access-control.md) +- [Actions](reference/actors/actions.md) +- [Actor Keys](reference/actors/keys.md) +- [Actor Runtime Socket](reference/actors/actor-runtime-socket.md) +- [Actor Scheduling](reference/actors/schedule.md) +- [Actor Statuses](reference/actors/statuses.md) +- [Authentication](reference/actors/authentication.md) +- [Cloudflare Workers Quickstart](reference/actors/quickstart/cloudflare.md) +- [Communicating Between Actors](reference/actors/communicating-between-actors.md) +- [Connections](reference/actors/connections.md) +- [Custom Inspector Tabs](reference/actors/inspector-tabs.md) +- [Debugging](reference/actors/debugging.md) +- [Design Patterns](reference/actors/design-patterns.md) +- [Destroying Actors](reference/actors/destroy.md) +- [Effect.ts Quickstart (Beta)](reference/actors/quickstart/effect.md) +- [Errors](reference/actors/errors.md) +- [Fetch and WebSocket Handler](reference/actors/fetch-and-websocket-handler.md) +- [Helper Types](reference/actors/helper-types.md) +- [Icons & Names](reference/actors/appearance.md) +- [In-Memory State](reference/actors/state.md) +- [Input Parameters](reference/actors/input.md) +- [Lifecycle](reference/actors/lifecycle.md) +- [Limits](reference/actors/limits.md) +- [Low-Level HTTP Request Handler](reference/actors/request-handler.md) +- [Low-Level KV Storage](reference/actors/kv.md) +- [Low-Level WebSocket Handler](reference/actors/websocket-handler.md) +- [Metadata](reference/actors/metadata.md) +- [Next.js Quickstart](reference/actors/quickstart/next-js.md) +- [Node.js & Bun Quickstart](reference/actors/quickstart/backend.md) +- [Queues & Run Loops](reference/actors/queues.md) +- [React Quickstart](reference/actors/quickstart/react.md) +- [Realtime](reference/actors/events.md) +- [Rust Quickstart (Beta)](reference/actors/quickstart/rust.md) +- [Scaling & Concurrency](reference/actors/scaling.md) +- [Sharing and Joining State](reference/actors/sharing-and-joining-state.md) +- [SQLite](reference/actors/sqlite.md) +- [SQLite + Drizzle](reference/actors/sqlite-drizzle.md) +- [Supabase Functions Quickstart](reference/actors/quickstart/supabase.md) +- [Testing](reference/actors/testing.md) +- [Troubleshooting](reference/actors/troubleshooting.md) +- [Types](reference/actors/types.md) +- [Vanilla HTTP API](reference/actors/http-api.md) +- [Versions & Upgrades](reference/actors/versions.md) +- [Workflows](reference/actors/workflows.md) + +### Cli + +- [CLI](reference/cli.md) + +### Clients + +- [Node.js & Bun](reference/clients/javascript.md) +- [React](reference/clients/react.md) +- [Rust (Beta)](reference/clients/rust.md) +- [Swift](reference/clients/swift.md) +- [SwiftUI](reference/clients/swiftui.md) + +### Cookbook + +- [AI Agent](reference/cookbook/ai-agent.md) +- [Chat Room](reference/cookbook/chat-room.md) +- [Collaborative Text Editor](reference/cookbook/collaborative-text-editor.md) +- [Cron Jobs and Scheduled Tasks](reference/cookbook/cron-jobs.md) +- [Database per Tenant](reference/cookbook/per-tenant-database.md) +- [Deploying Rivet in a VPC or Air-Gapped Network](reference/cookbook/vpc-air-gapped.md) +- [Live Cursors and Presence](reference/cookbook/live-cursors.md) +- [Multiplayer Game](reference/cookbook/multiplayer-game.md) + +### Deploy + +- [Container Runner](reference/deploy/container-runner.md) +- [Deploy To Amazon Web Services Lambda](reference/deploy/aws-lambda.md) +- [Deploying to AWS ECS](reference/deploy/aws-ecs.md) +- [Deploying to Cloudflare Workers](reference/deploy/cloudflare.md) +- [Deploying to Freestyle](reference/deploy/freestyle.md) +- [Deploying to Google Cloud Run](reference/deploy/gcp-cloud-run.md) +- [Deploying to Hetzner](reference/deploy/hetzner.md) +- [Deploying to Kubernetes](reference/deploy/kubernetes.md) +- [Deploying to Railway](reference/deploy/railway.md) +- [Deploying to Rivet Compute](reference/deploy/rivet-compute.md) +- [Deploying to Supabase Functions](reference/deploy/supabase.md) +- [Deploying to Vercel](reference/deploy/vercel.md) +- [Deploying to VMs & Bare Metal](reference/deploy/vm-and-bare-metal.md) + +### General + +- [Actor Configuration](reference/general/actor-configuration.md) +- [Architecture](reference/general/architecture.md) +- [Cross-Origin Resource Sharing](reference/general/cors.md) +- [Documentation for LLMs & AI](reference/general/docs-for-llms.md) +- [Edge Networking](reference/general/edge.md) +- [Endpoints](reference/general/endpoints.md) +- [Environment Variables](reference/general/environment-variables.md) +- [HTTP Server](reference/general/http-server.md) +- [Logging](reference/general/logging.md) +- [Pool Configuration](reference/general/pool-configuration.md) +- [Production Checklist](reference/general/production-checklist.md) +- [Registry Configuration](reference/general/registry-configuration.md) +- [Runtime Modes](reference/general/runtime-modes.md) +- [WASM vs Native SDK](reference/general/wasm-vs-native-sdk.md) + +### Self Hosting + +- [Configuration](reference/self-hosting/configuration.md) +- [Docker Compose](reference/self-hosting/docker-compose.md) +- [Docker Container](reference/self-hosting/docker-container.md) +- [File System](reference/self-hosting/filesystem.md) +- [FoundationDB (Enterprise)](reference/self-hosting/foundationdb.md) +- [Installing Rivet Engine](reference/self-hosting/install.md) +- [Kubernetes](reference/self-hosting/kubernetes.md) +- [Multi-Region](reference/self-hosting/multi-region.md) +- [PostgreSQL](reference/self-hosting/postgres.md) +- [Production Checklist](reference/self-hosting/production-checklist.md) +- [Railway Deployment](reference/self-hosting/railway.md) +- [Render Deployment](reference/self-hosting/render.md) +- [TLS & Certificates](reference/self-hosting/tls.md) + diff --git a/.agents/skills/chat-room/SKILL.md b/.agents/skills/chat-room/SKILL.md new file mode 100644 index 0000000..6eb25c7 --- /dev/null +++ b/.agents/skills/chat-room/SKILL.md @@ -0,0 +1,243 @@ +--- +name: "chat-room" +description: "Build a realtime chat room backend with Rivet Actors: one actor per room, SQLite-backed message history, and WebSocket broadcast to every connected client." +--- + +# Chat Room + +**IMPORTANT: Before doing anything, you MUST read `BASE_SKILL.md` in this skill's directory. It contains essential guidance on debugging, error handling, state management, deployment, and project setup. Those rules and patterns apply to all RivetKit work. Everything below assumes you have already read and understood it.** + +## Working Examples + +If you need a reference implementation, read the raw working example code in these templates: + +- [chat-room](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room) + + +Patterns for building a chat room backend with RivetKit: room-scoped actors, persistent message history, and realtime delivery over WebSocket connections. + +## Starter Code + +Start with the working example on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room) and adapt it. The backend is a single `chatRoom` actor; the frontend is a React app using `@rivetkit/react` (see the [React quickstart](/docs/actors/quickstart/react)). + +| Topic | Summary | +| --- | --- | +| Room model | One `chatRoom` actor per room key. The frontend defaults the key to `general`; typing a different room name connects to a different actor. | +| History | SQLite `messages` table created in `db({ onMigrate })`, read back with `ORDER BY id ASC`. | +| Delivery | `sendMessage` inserts the row, then broadcasts a typed `newMessage` event to every connected client. | +| Identity | None in the example. `sender` is a plain action argument; production should bind identity to the connection. | + +## Room-Per-Actor Model + +Each room is one Rivet Actor instance, addressed by [key](/docs/actors/keys). The client calls `useActor({ name: "chatRoom", key: [roomId] })`, which gets-or-creates the actor for that room. This gives you: + +- **Isolation**: each room's history and connections are fully scoped to its key. Switching the room input re-keys the hook and connects to a different actor with separate history. +- **A single serialized writer**: all `sendMessage` calls for one room run through one actor, so message ordering is consistent without locks. The SQLite `AUTOINCREMENT` id is the canonical order, which is why `getHistory` sorts by `id` rather than by timestamp. +- **Natural scaling**: rooms spread across the cluster independently. A hot room does not slow down other rooms. + +## Message History Storage + +This example stores history in the actor's SQLite database, not in JSON state. Pick based on history size and query needs: + +| Approach | Use When | Implementation Guidance | +| --- | --- | --- | +| [SQLite](/docs/actors/sqlite) (what this example uses) | Large or long-lived history that needs ordering, caps, pagination, or search | Create the `messages` table in `db({ onMigrate })`, insert with parameterized queries (`c.db.execute("INSERT ... VALUES (?, ?, ?)", ...)`), and read with `ORDER BY id ASC`. History survives actor sleep and scales past what you want in memory. | +| [JSON state](/docs/actors/state) | Small recent history, for example the last 50 to 100 messages | Push onto a `messages` array in actor state and trim to a cap on every send. Simplest option, but the whole history lives in memory and there is no query layer, so it only fits bounded recent-history use cases. | + +## Broadcast Delivery + +New messages reach connected clients through a typed [event](/docs/actors/events): + +- The actor declares `events: { newMessage: event() }`, where `Message` is `{ sender, text, timestamp }`. +- The `sendMessage` [action](/docs/actors/actions) builds the message with a server-side `Date.now()` timestamp, inserts it into the `messages` table, then calls `c.broadcast("newMessage", message)` and returns the message to the caller. +- Each client subscribes with `useEvent("newMessage", ...)` and appends to its local list. The sender renders its own message through the same broadcast path as everyone else, so all clients stay on one code path. +- History load is connection-gated: once the connection is ready, the client calls `getHistory()` once to render the backlog, then relies on events for everything after. + +Use `c.broadcast(...)` for room-wide messages. For private or per-recipient payloads (such as DMs inside a room), send on the individual connection instead, which is a recommended extension beyond this example. + +## Typing Indicators And Presence (Extension) + +The example does not implement typing indicators, presence, or join/leave handling of any kind. There is no `createConnState`, `onConnect`, or `onDisconnect` in the code. If you need them, add them as ephemeral [connection](/docs/actors/connections) behavior: + +- **Keep it ephemeral**: store the username and typing flag in per-connection state, never in SQLite or persisted actor state. Presence is derived from live connections and should disappear with them. +- **Broadcast on change only**: emit a typing event when a user starts or stops typing, and a presence event from `onConnect` / `onDisconnect`, rather than polling or ticking. +- **Expire on the client**: clear a typing indicator after a short client-side timeout so a dropped connection never leaves a stuck "is typing" row. + +## Per-User Inbox (Extension) + +For offline delivery, DMs, unread counts, or notification fanout, add a `userInbox[userId]` actor per user. This is an extension beyond the example: + +- The room actor forwards each message to the inbox actor of every member via [actor-to-actor calls](/docs/actors/communicating-between-actors), so users who are not connected to the room still accumulate messages. +- The inbox actor owns per-user unread state and serves it when the user comes online, independent of which rooms they are in. +- DMs become a degenerate room: either a `chatRoom` keyed by the sorted pair of user ids, or direct inbox-to-inbox delivery if you do not need shared history semantics. + +## Actors + +- **Key**: `chatRoom[roomId]` +- **Responsibility**: Owns one chat room. Persists the room's message history in its SQLite database and broadcasts each new message to every connected client. +- **Actions** + - `sendMessage` + - `getHistory` +- **Queues** + - None +- **Events** + - `newMessage` +- **State** + - SQLite + - `messages` table: `id` (autoincrement primary key), `sender`, `text`, `timestamp` + +## Lifecycle + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant R as chatRoom + + A->>R: connect with key [roomId] + Note over R: every start runs onMigrate (CREATE TABLE IF NOT EXISTS messages) + A->>R: getHistory() + R-->>A: Message[] ordered by id + B->>R: connect with key [roomId] + B->>R: getHistory() + R-->>B: Message[] ordered by id + A->>R: sendMessage(sender, text) + Note over R: INSERT row with server timestamp + R-->>A: newMessage (broadcast) + R-->>B: newMessage (broadcast) + A->>R: disconnect + Note over R: history stays in SQLite for the next connection +``` + +## Security Checklist + +The example is intentionally minimal and skips all of the following. Add them before production: + +- **Auth before join**: any client can join any room by knowing its name, and `sender` is arbitrary client input on every call. Validate a token during [connection auth](/docs/actors/authentication), bind identity to [connection state](/docs/actors/connections), and check room membership before serving history. Never trust a sender name passed as an action argument. +- **Message length clamps**: the example accepts empty messages and has no length limit. Trim server-side, reject empty text, and clamp to a maximum length. +- **Per-connection rate limiting**: rate limit `sendMessage` per connection to stop spam and broadcast amplification. +- **Server-side timestamps and ids**: the example already does this correctly. `timestamp` comes from `Date.now()` inside the action and `id` from SQLite `AUTOINCREMENT`. Keep it that way; never accept client-supplied timestamps or ids. +- **History caps**: `getHistory` returns every row with no limit. Add a `LIMIT` plus pagination, and prune or archive old rows so a long-lived room cannot grow unbounded. +- **Parameterized queries**: the example already inserts with `?` placeholders. Keep all user-supplied text out of SQL string interpolation. + +## Reference Map + +### Actors + +- [Access Control](reference/actors/access-control.md) +- [Actions](reference/actors/actions.md) +- [Actor Keys](reference/actors/keys.md) +- [Actor Runtime Socket](reference/actors/actor-runtime-socket.md) +- [Actor Scheduling](reference/actors/schedule.md) +- [Actor Statuses](reference/actors/statuses.md) +- [Authentication](reference/actors/authentication.md) +- [Cloudflare Workers Quickstart](reference/actors/quickstart/cloudflare.md) +- [Communicating Between Actors](reference/actors/communicating-between-actors.md) +- [Connections](reference/actors/connections.md) +- [Custom Inspector Tabs](reference/actors/inspector-tabs.md) +- [Debugging](reference/actors/debugging.md) +- [Design Patterns](reference/actors/design-patterns.md) +- [Destroying Actors](reference/actors/destroy.md) +- [Effect.ts Quickstart (Beta)](reference/actors/quickstart/effect.md) +- [Errors](reference/actors/errors.md) +- [Fetch and WebSocket Handler](reference/actors/fetch-and-websocket-handler.md) +- [Helper Types](reference/actors/helper-types.md) +- [Icons & Names](reference/actors/appearance.md) +- [In-Memory State](reference/actors/state.md) +- [Input Parameters](reference/actors/input.md) +- [Lifecycle](reference/actors/lifecycle.md) +- [Limits](reference/actors/limits.md) +- [Low-Level HTTP Request Handler](reference/actors/request-handler.md) +- [Low-Level KV Storage](reference/actors/kv.md) +- [Low-Level WebSocket Handler](reference/actors/websocket-handler.md) +- [Metadata](reference/actors/metadata.md) +- [Next.js Quickstart](reference/actors/quickstart/next-js.md) +- [Node.js & Bun Quickstart](reference/actors/quickstart/backend.md) +- [Queues & Run Loops](reference/actors/queues.md) +- [React Quickstart](reference/actors/quickstart/react.md) +- [Realtime](reference/actors/events.md) +- [Rust Quickstart (Beta)](reference/actors/quickstart/rust.md) +- [Scaling & Concurrency](reference/actors/scaling.md) +- [Sharing and Joining State](reference/actors/sharing-and-joining-state.md) +- [SQLite](reference/actors/sqlite.md) +- [SQLite + Drizzle](reference/actors/sqlite-drizzle.md) +- [Supabase Functions Quickstart](reference/actors/quickstart/supabase.md) +- [Testing](reference/actors/testing.md) +- [Troubleshooting](reference/actors/troubleshooting.md) +- [Types](reference/actors/types.md) +- [Vanilla HTTP API](reference/actors/http-api.md) +- [Versions & Upgrades](reference/actors/versions.md) +- [Workflows](reference/actors/workflows.md) + +### Cli + +- [CLI](reference/cli.md) + +### Clients + +- [Node.js & Bun](reference/clients/javascript.md) +- [React](reference/clients/react.md) +- [Rust (Beta)](reference/clients/rust.md) +- [Swift](reference/clients/swift.md) +- [SwiftUI](reference/clients/swiftui.md) + +### Cookbook + +- [AI Agent](reference/cookbook/ai-agent.md) +- [Chat Room](reference/cookbook/chat-room.md) +- [Collaborative Text Editor](reference/cookbook/collaborative-text-editor.md) +- [Cron Jobs and Scheduled Tasks](reference/cookbook/cron-jobs.md) +- [Database per Tenant](reference/cookbook/per-tenant-database.md) +- [Deploying Rivet in a VPC or Air-Gapped Network](reference/cookbook/vpc-air-gapped.md) +- [Live Cursors and Presence](reference/cookbook/live-cursors.md) +- [Multiplayer Game](reference/cookbook/multiplayer-game.md) + +### Deploy + +- [Container Runner](reference/deploy/container-runner.md) +- [Deploy To Amazon Web Services Lambda](reference/deploy/aws-lambda.md) +- [Deploying to AWS ECS](reference/deploy/aws-ecs.md) +- [Deploying to Cloudflare Workers](reference/deploy/cloudflare.md) +- [Deploying to Freestyle](reference/deploy/freestyle.md) +- [Deploying to Google Cloud Run](reference/deploy/gcp-cloud-run.md) +- [Deploying to Hetzner](reference/deploy/hetzner.md) +- [Deploying to Kubernetes](reference/deploy/kubernetes.md) +- [Deploying to Railway](reference/deploy/railway.md) +- [Deploying to Rivet Compute](reference/deploy/rivet-compute.md) +- [Deploying to Supabase Functions](reference/deploy/supabase.md) +- [Deploying to Vercel](reference/deploy/vercel.md) +- [Deploying to VMs & Bare Metal](reference/deploy/vm-and-bare-metal.md) + +### General + +- [Actor Configuration](reference/general/actor-configuration.md) +- [Architecture](reference/general/architecture.md) +- [Cross-Origin Resource Sharing](reference/general/cors.md) +- [Documentation for LLMs & AI](reference/general/docs-for-llms.md) +- [Edge Networking](reference/general/edge.md) +- [Endpoints](reference/general/endpoints.md) +- [Environment Variables](reference/general/environment-variables.md) +- [HTTP Server](reference/general/http-server.md) +- [Logging](reference/general/logging.md) +- [Pool Configuration](reference/general/pool-configuration.md) +- [Production Checklist](reference/general/production-checklist.md) +- [Registry Configuration](reference/general/registry-configuration.md) +- [Runtime Modes](reference/general/runtime-modes.md) +- [WASM vs Native SDK](reference/general/wasm-vs-native-sdk.md) + +### Self Hosting + +- [Configuration](reference/self-hosting/configuration.md) +- [Docker Compose](reference/self-hosting/docker-compose.md) +- [Docker Container](reference/self-hosting/docker-container.md) +- [File System](reference/self-hosting/filesystem.md) +- [FoundationDB (Enterprise)](reference/self-hosting/foundationdb.md) +- [Installing Rivet Engine](reference/self-hosting/install.md) +- [Kubernetes](reference/self-hosting/kubernetes.md) +- [Multi-Region](reference/self-hosting/multi-region.md) +- [PostgreSQL](reference/self-hosting/postgres.md) +- [Production Checklist](reference/self-hosting/production-checklist.md) +- [Railway Deployment](reference/self-hosting/railway.md) +- [Render Deployment](reference/self-hosting/render.md) +- [TLS & Certificates](reference/self-hosting/tls.md) + diff --git a/.agents/skills/chat-room/index.json b/.agents/skills/chat-room/index.json new file mode 100644 index 0000000..50c995d --- /dev/null +++ b/.agents/skills/chat-room/index.json @@ -0,0 +1,694 @@ +{ + "name": "chat-room", + "description": "Build a realtime chat room backend with Rivet Actors: one actor per room, SQLite-backed message history, and WebSocket broadcast to every connected client.", + "skill_url": "/metadata/skills/chat-room/SKILL.md", + "generated_at": "2026-07-18T12:40:07.502Z", + "references": [ + { + "name": "actors/access-control", + "title": "Access Control", + "description": "Authorize actions, queue publishes, and event subscriptions with explicit hooks.", + "canonical_url": "https://rivet.dev/docs/actors/access-control", + "reference_url": "/metadata/skills/chat-room/reference/actors/access-control.md" + }, + { + "name": "actors/actions", + "title": "Actions", + "description": "Actions are how your backend, frontend, or other actors can communicate with actors.", + "canonical_url": "https://rivet.dev/docs/actors/actions", + "reference_url": "/metadata/skills/chat-room/reference/actors/actions.md" + }, + { + "name": "general/actor-configuration", + "title": "Actor Configuration", + "description": "This page documents the configuration options available when defining a RivetKit actor. The actor configuration is passed to the `actor()` function.", + "canonical_url": "https://rivet.dev/docs/general/actor-configuration", + "reference_url": "/metadata/skills/chat-room/reference/general/actor-configuration.md" + }, + { + "name": "actors/keys", + "title": "Actor Keys", + "description": "Actor keys uniquely identify actor instances within each actor type. Keys are used for addressing which specific actor to communicate with.", + "canonical_url": "https://rivet.dev/docs/actors/keys", + "reference_url": "/metadata/skills/chat-room/reference/actors/keys.md" + }, + { + "name": "actors/actor-runtime-socket", + "title": "Actor Runtime Socket", + "description": "Connect trusted local tools to a running Rivet Actor over an experimental actor-local protocol.", + "canonical_url": "https://rivet.dev/docs/actors/actor-runtime-socket", + "reference_url": "/metadata/skills/chat-room/reference/actors/actor-runtime-socket.md" + }, + { + "name": "actors/schedule", + "title": "Actor Scheduling", + "description": "Schedule actor actions in the future with persistent timers that survive restarts and upgrades.", + "canonical_url": "https://rivet.dev/docs/actors/schedule", + "reference_url": "/metadata/skills/chat-room/reference/actors/schedule.md" + }, + { + "name": "actors/statuses", + "title": "Actor Statuses", + "description": "Understand the lifecycle statuses of Rivet Actors, what they mean, how they appear in the API, and how to troubleshoot common issues.", + "canonical_url": "https://rivet.dev/docs/actors/statuses", + "reference_url": "/metadata/skills/chat-room/reference/actors/statuses.md" + }, + { + "name": "cookbook/ai-agent", + "title": "AI Agent", + "description": "Build an AI agent backend with persistent memory: one Rivet Actor per conversation, queued message handling, and streaming LLM responses as realtime events.", + "canonical_url": "https://rivet.dev/cookbook/ai-agent", + "reference_url": "/metadata/skills/chat-room/reference/cookbook/ai-agent.md" + }, + { + "name": "general/architecture", + "title": "Architecture", + "description": "- rivetkit is the typescript library used for both local development & to connect your application to rivet - a rivetkit instance is called a \"runner.\" you can run multiple runners to scale rivetkit horizontally. read omre about runners below.", + "canonical_url": "https://rivet.dev/docs/general/architecture", + "reference_url": "/metadata/skills/chat-room/reference/general/architecture.md" + }, + { + "name": "actors/authentication", + "title": "Authentication", + "description": "Secure your actors with authentication and authorization.", + "canonical_url": "https://rivet.dev/docs/actors/authentication", + "reference_url": "/metadata/skills/chat-room/reference/actors/authentication.md" + }, + { + "name": "cookbook/chat-room", + "title": "Chat Room", + "description": "Build a realtime chat room backend with Rivet Actors: one actor per room, SQLite-backed message history, and WebSocket broadcast to every connected client.", + "canonical_url": "https://rivet.dev/cookbook/chat-room", + "reference_url": "/metadata/skills/chat-room/reference/cookbook/chat-room.md" + }, + { + "name": "cli", + "title": "CLI", + "description": "Reference for the optional rivet CLI: deploy to Rivet Compute and run local dev for serverless platforms.", + "canonical_url": "https://rivet.dev/docs/cli", + "reference_url": "/metadata/skills/chat-room/reference/cli.md" + }, + { + "name": "actors/quickstart/cloudflare", + "title": "Cloudflare Workers Quickstart", + "description": "Set up a Rivet project locally targeting Cloudflare Workers.", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/cloudflare", + "reference_url": "/metadata/skills/chat-room/reference/actors/quickstart/cloudflare.md" + }, + { + "name": "cookbook/collaborative-text-editor", + "title": "Collaborative Text Editor", + "description": "Build a collaborative text editor backend with Yjs CRDTs and Rivet Actors: per-document actors relay sync and awareness updates and persist snapshots.", + "canonical_url": "https://rivet.dev/cookbook/collaborative-text-editor", + "reference_url": "/metadata/skills/chat-room/reference/cookbook/collaborative-text-editor.md" + }, + { + "name": "actors/communicating-between-actors", + "title": "Communicating Between Actors", + "description": "Learn how actors can call other actors and share data", + "canonical_url": "https://rivet.dev/docs/actors/communicating-between-actors", + "reference_url": "/metadata/skills/chat-room/reference/actors/communicating-between-actors.md" + }, + { + "name": "self-hosting/configuration", + "title": "Configuration", + "description": "Rivet Engine can be configured through environment variables or configuration files.", + "canonical_url": "https://rivet.dev/docs/self-hosting/configuration", + "reference_url": "/metadata/skills/chat-room/reference/self-hosting/configuration.md" + }, + { + "name": "actors/connections", + "title": "Connections", + "description": "Connections represent client connections to your actor. They provide a way to handle client authentication, manage connection-specific data, and control the connection lifecycle.", + "canonical_url": "https://rivet.dev/docs/actors/connections", + "reference_url": "/metadata/skills/chat-room/reference/actors/connections.md" + }, + { + "name": "deploy/container-runner", + "title": "Container Runner", + "description": "Run any containerized server as a Rivet Actor.", + "canonical_url": "https://rivet.dev/docs/deploy/container-runner", + "reference_url": "/metadata/skills/chat-room/reference/deploy/container-runner.md" + }, + { + "name": "cookbook/cron-jobs", + "title": "Cron Jobs and Scheduled Tasks", + "description": "Durable cron jobs with Rivet Actors: schedule.after and schedule.at timers survive restarts and crashes, plus re-arming recurring jobs and idempotent handlers.", + "canonical_url": "https://rivet.dev/cookbook/cron-jobs", + "reference_url": "/metadata/skills/chat-room/reference/cookbook/cron-jobs.md" + }, + { + "name": "general/cors", + "title": "Cross-Origin Resource Sharing", + "description": "Cross-Origin Resource Sharing (CORS) controls which origins (domains) can access your actors. When actors are exposed to the public internet, proper origin validation is critical to prevent security breaches and denial of service attacks.", + "canonical_url": "https://rivet.dev/docs/general/cors", + "reference_url": "/metadata/skills/chat-room/reference/general/cors.md" + }, + { + "name": "actors/inspector-tabs", + "title": "Custom Inspector Tabs", + "description": "Ship your own UI tabs alongside a Rivet Actor — embedded directly in the dashboard inspector.", + "canonical_url": "https://rivet.dev/docs/actors/inspector-tabs", + "reference_url": "/metadata/skills/chat-room/reference/actors/inspector-tabs.md" + }, + { + "name": "cookbook/per-tenant-database", + "title": "Database per Tenant", + "description": "Multi-tenant data isolation with one Rivet Actor per tenant: the actor key is the tenant id, so each tenant gets its own isolated dataset and migrations.", + "canonical_url": "https://rivet.dev/cookbook/per-tenant-database", + "reference_url": "/metadata/skills/chat-room/reference/cookbook/per-tenant-database.md" + }, + { + "name": "actors/debugging", + "title": "Debugging", + "description": "Inspect and debug running Rivet Actors, runners, and provider configs using management, runner, and actor inspector HTTP APIs.", + "canonical_url": "https://rivet.dev/docs/actors/debugging", + "reference_url": "/metadata/skills/chat-room/reference/actors/debugging.md" + }, + { + "name": "deploy/aws-lambda", + "title": "Deploy To Amazon Web Services Lambda", + "description": "_AWS Lambda is coming soon_", + "canonical_url": "https://rivet.dev/docs/deploy/aws-lambda", + "reference_url": "/metadata/skills/chat-room/reference/deploy/aws-lambda.md" + }, + { + "name": "cookbook/vpc-air-gapped", + "title": "Deploying Rivet in a VPC or Air-Gapped Network", + "description": "Run Rivet entirely inside your own perimeter: single-binary or Docker Compose install, file system storage with no database infrastructure, and no outbound telemetry by default.", + "canonical_url": "https://rivet.dev/cookbook/vpc-air-gapped", + "reference_url": "/metadata/skills/chat-room/reference/cookbook/vpc-air-gapped.md" + }, + { + "name": "deploy/aws-ecs", + "title": "Deploying to AWS ECS", + "description": "Run your backend on Amazon ECS with Fargate.", + "canonical_url": "https://rivet.dev/docs/deploy/aws-ecs", + "reference_url": "/metadata/skills/chat-room/reference/deploy/aws-ecs.md" + }, + { + "name": "deploy/cloudflare", + "title": "Deploying to Cloudflare Workers", + "description": "Deploy an existing Rivet project to Cloudflare Workers.", + "canonical_url": "https://rivet.dev/docs/deploy/cloudflare", + "reference_url": "/metadata/skills/chat-room/reference/deploy/cloudflare.md" + }, + { + "name": "deploy/freestyle", + "title": "Deploying to Freestyle", + "description": "Deploy RivetKit app to Freestyle.sh, a cloud platform for running AI-generated code with built-in security and scalability.", + "canonical_url": "https://rivet.dev/docs/deploy/freestyle", + "reference_url": "/metadata/skills/chat-room/reference/deploy/freestyle.md" + }, + { + "name": "deploy/gcp-cloud-run", + "title": "Deploying to Google Cloud Run", + "description": "Deploy your RivetKit app to Google Cloud Run.", + "canonical_url": "https://rivet.dev/docs/deploy/gcp-cloud-run", + "reference_url": "/metadata/skills/chat-room/reference/deploy/gcp-cloud-run.md" + }, + { + "name": "deploy/hetzner", + "title": "Deploying to Hetzner", + "description": "Please see the VM & Bare Metal guide.", + "canonical_url": "https://rivet.dev/docs/deploy/hetzner", + "reference_url": "/metadata/skills/chat-room/reference/deploy/hetzner.md" + }, + { + "name": "deploy/kubernetes", + "title": "Deploying to Kubernetes", + "description": "Deploy your RivetKit app to any Kubernetes cluster.", + "canonical_url": "https://rivet.dev/docs/deploy/kubernetes", + "reference_url": "/metadata/skills/chat-room/reference/deploy/kubernetes.md" + }, + { + "name": "deploy/railway", + "title": "Deploying to Railway", + "description": "Deploy your RivetKit app to Railway.", + "canonical_url": "https://rivet.dev/docs/deploy/railway", + "reference_url": "/metadata/skills/chat-room/reference/deploy/railway.md" + }, + { + "name": "deploy/rivet-compute", + "title": "Deploying to Rivet Compute", + "description": "Run your backend on Rivet Compute.", + "canonical_url": "https://rivet.dev/docs/deploy/rivet-compute", + "reference_url": "/metadata/skills/chat-room/reference/deploy/rivet-compute.md" + }, + { + "name": "deploy/supabase", + "title": "Deploying to Supabase Functions", + "description": "Deploy an existing Rivet project to Supabase Edge Functions.", + "canonical_url": "https://rivet.dev/docs/deploy/supabase", + "reference_url": "/metadata/skills/chat-room/reference/deploy/supabase.md" + }, + { + "name": "deploy/vercel", + "title": "Deploying to Vercel", + "description": "Deploy your Next.js Rivet app to Vercel.", + "canonical_url": "https://rivet.dev/docs/deploy/vercel", + "reference_url": "/metadata/skills/chat-room/reference/deploy/vercel.md" + }, + { + "name": "deploy/vm-and-bare-metal", + "title": "Deploying to VMs & Bare Metal", + "description": "Deploy your RivetKit app to any Linux VM or bare metal host.", + "canonical_url": "https://rivet.dev/docs/deploy/vm-and-bare-metal", + "reference_url": "/metadata/skills/chat-room/reference/deploy/vm-and-bare-metal.md" + }, + { + "name": "actors/design-patterns", + "title": "Design Patterns", + "description": "Common patterns and anti-patterns for building scalable actor systems.", + "canonical_url": "https://rivet.dev/docs/actors/design-patterns", + "reference_url": "/metadata/skills/chat-room/reference/actors/design-patterns.md" + }, + { + "name": "actors/destroy", + "title": "Destroying Actors", + "description": "Actors can be permanently destroyed. Common use cases include:", + "canonical_url": "https://rivet.dev/docs/actors/destroy", + "reference_url": "/metadata/skills/chat-room/reference/actors/destroy.md" + }, + { + "name": "self-hosting/docker-compose", + "title": "Docker Compose", + "description": "Deploy Rivet Engine with docker-compose for multi-container setups.", + "canonical_url": "https://rivet.dev/docs/self-hosting/docker-compose", + "reference_url": "/metadata/skills/chat-room/reference/self-hosting/docker-compose.md" + }, + { + "name": "self-hosting/docker-container", + "title": "Docker Container", + "description": "Run Rivet Engine in a single Docker container.", + "canonical_url": "https://rivet.dev/docs/self-hosting/docker-container", + "reference_url": "/metadata/skills/chat-room/reference/self-hosting/docker-container.md" + }, + { + "name": "general/docs-for-llms", + "title": "Documentation for LLMs & AI", + "description": "Rivet provides optimized documentation formats specifically designed for Large Language Models (LLMs) and AI integration tools.", + "canonical_url": "https://rivet.dev/docs/general/docs-for-llms", + "reference_url": "/metadata/skills/chat-room/reference/general/docs-for-llms.md" + }, + { + "name": "general/edge", + "title": "Edge Networking", + "description": "Actors automatically run near your users on your provider's global network.", + "canonical_url": "https://rivet.dev/docs/general/edge", + "reference_url": "/metadata/skills/chat-room/reference/general/edge.md" + }, + { + "name": "actors/quickstart/effect", + "title": "Effect.ts Quickstart (Beta)", + "description": "Build a Rivet Actor with the Effect SDK", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/effect", + "reference_url": "/metadata/skills/chat-room/reference/actors/quickstart/effect.md" + }, + { + "name": "general/endpoints", + "title": "Endpoints", + "description": "Configure how your backend connects to Rivet and how clients reach your actors.", + "canonical_url": "https://rivet.dev/docs/general/endpoints", + "reference_url": "/metadata/skills/chat-room/reference/general/endpoints.md" + }, + { + "name": "general/environment-variables", + "title": "Environment Variables", + "description": "This page documents all environment variables that configure RivetKit behavior.", + "canonical_url": "https://rivet.dev/docs/general/environment-variables", + "reference_url": "/metadata/skills/chat-room/reference/general/environment-variables.md" + }, + { + "name": "actors/errors", + "title": "Errors", + "description": "Rivet provides robust error handling with security built in by default. Errors are handled differently based on whether they should be exposed to clients or kept private.", + "canonical_url": "https://rivet.dev/docs/actors/errors", + "reference_url": "/metadata/skills/chat-room/reference/actors/errors.md" + }, + { + "name": "actors/fetch-and-websocket-handler", + "title": "Fetch and WebSocket Handler", + "description": "These docs have moved to [Low-Level WebSocket Handler](/docs/actors/websocket-handler) and [Low-Level Request Handler](/docs/actors/request-handler).", + "canonical_url": "https://rivet.dev/docs/actors/fetch-and-websocket-handler", + "reference_url": "/metadata/skills/chat-room/reference/actors/fetch-and-websocket-handler.md" + }, + { + "name": "self-hosting/filesystem", + "title": "File System", + "description": "The file system backend stores all data on the local disk. This is suitable for single-node deployments, development, and testing.", + "canonical_url": "https://rivet.dev/docs/self-hosting/filesystem", + "reference_url": "/metadata/skills/chat-room/reference/self-hosting/filesystem.md" + }, + { + "name": "self-hosting/foundationdb", + "title": "FoundationDB (Enterprise)", + "description": "FoundationDB is the recommended storage backend for scalable production Rivet deployments.", + "canonical_url": "https://rivet.dev/docs/self-hosting/foundationdb", + "reference_url": "/metadata/skills/chat-room/reference/self-hosting/foundationdb.md" + }, + { + "name": "actors/helper-types", + "title": "Helper Types", + "description": "This page has moved to [Types](/docs/actors/types).", + "canonical_url": "https://rivet.dev/docs/actors/helper-types", + "reference_url": "/metadata/skills/chat-room/reference/actors/helper-types.md" + }, + { + "name": "general/http-server", + "title": "HTTP Server", + "description": "Different ways to run your RivetKit HTTP server.", + "canonical_url": "https://rivet.dev/docs/general/http-server", + "reference_url": "/metadata/skills/chat-room/reference/general/http-server.md" + }, + { + "name": "actors/appearance", + "title": "Icons & Names", + "description": "Customize actors with display names and icons for the Rivet inspector and dashboard.", + "canonical_url": "https://rivet.dev/docs/actors/appearance", + "reference_url": "/metadata/skills/chat-room/reference/actors/appearance.md" + }, + { + "name": "actors/state", + "title": "In-Memory State", + "description": "Actors store state in memory for instant reads and writes. State can be persisted automatically or kept ephemeral.", + "canonical_url": "https://rivet.dev/docs/actors/state", + "reference_url": "/metadata/skills/chat-room/reference/actors/state.md" + }, + { + "name": "actors/input", + "title": "Input Parameters", + "description": "Pass initialization data to actors when creating instances", + "canonical_url": "https://rivet.dev/docs/actors/input", + "reference_url": "/metadata/skills/chat-room/reference/actors/input.md" + }, + { + "name": "self-hosting/install", + "title": "Installing Rivet Engine", + "description": "Install Rivet Engine using Docker, binaries, or a source build.", + "canonical_url": "https://rivet.dev/docs/self-hosting/install", + "reference_url": "/metadata/skills/chat-room/reference/self-hosting/install.md" + }, + { + "name": "self-hosting/kubernetes", + "title": "Kubernetes", + "description": "Deploy production-ready Rivet Engine to Kubernetes with PostgreSQL storage.", + "canonical_url": "https://rivet.dev/docs/self-hosting/kubernetes", + "reference_url": "/metadata/skills/chat-room/reference/self-hosting/kubernetes.md" + }, + { + "name": "actors/lifecycle", + "title": "Lifecycle", + "description": "Learn about actor lifecycle hooks for initialization, state management, and cleanup.", + "canonical_url": "https://rivet.dev/docs/actors/lifecycle", + "reference_url": "/metadata/skills/chat-room/reference/actors/lifecycle.md" + }, + { + "name": "actors/limits", + "title": "Limits", + "description": "Limits and constraints for Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/actors/limits", + "reference_url": "/metadata/skills/chat-room/reference/actors/limits.md" + }, + { + "name": "cookbook/live-cursors", + "title": "Live Cursors and Presence", + "description": "Live cursors and multiplayer presence with Rivet Actors: per-connection cursor state, realtime updates over events or raw WebSockets, and throttling.", + "canonical_url": "https://rivet.dev/cookbook/live-cursors", + "reference_url": "/metadata/skills/chat-room/reference/cookbook/live-cursors.md" + }, + { + "name": "general/logging", + "title": "Logging", + "description": "Actors provide a built-in way to log complex data to the console.", + "canonical_url": "https://rivet.dev/docs/general/logging", + "reference_url": "/metadata/skills/chat-room/reference/general/logging.md" + }, + { + "name": "actors/request-handler", + "title": "Low-Level HTTP Request Handler", + "description": "Actors can handle HTTP requests through the `onRequest` handler.", + "canonical_url": "https://rivet.dev/docs/actors/request-handler", + "reference_url": "/metadata/skills/chat-room/reference/actors/request-handler.md" + }, + { + "name": "actors/kv", + "title": "Low-Level KV Storage", + "description": "Use the built-in key-value store on ActorContext for durable string and binary data alongside actor state.", + "canonical_url": "https://rivet.dev/docs/actors/kv", + "reference_url": "/metadata/skills/chat-room/reference/actors/kv.md" + }, + { + "name": "actors/websocket-handler", + "title": "Low-Level WebSocket Handler", + "description": "Actors can handle WebSocket connections through the `onWebSocket` handler.", + "canonical_url": "https://rivet.dev/docs/actors/websocket-handler", + "reference_url": "/metadata/skills/chat-room/reference/actors/websocket-handler.md" + }, + { + "name": "actors/metadata", + "title": "Metadata", + "description": "Metadata provides information about the currently running actor.", + "canonical_url": "https://rivet.dev/docs/actors/metadata", + "reference_url": "/metadata/skills/chat-room/reference/actors/metadata.md" + }, + { + "name": "self-hosting/multi-region", + "title": "Multi-Region", + "description": "Rivet Engine supports scaling transparently across multiple regions.", + "canonical_url": "https://rivet.dev/docs/self-hosting/multi-region", + "reference_url": "/metadata/skills/chat-room/reference/self-hosting/multi-region.md" + }, + { + "name": "cookbook/multiplayer-game", + "title": "Multiplayer Game", + "description": "Pragmatic patterns for building multiplayer games: matchmaking, tick loops, realtime state, interest management, and validation.", + "canonical_url": "https://rivet.dev/cookbook/multiplayer-game", + "reference_url": "/metadata/skills/chat-room/reference/cookbook/multiplayer-game.md" + }, + { + "name": "actors/quickstart/next-js", + "title": "Next.js Quickstart", + "description": "Get started with Rivet Actors in Next.js", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/next-js", + "reference_url": "/metadata/skills/chat-room/reference/actors/quickstart/next-js.md" + }, + { + "name": "clients/javascript", + "title": "Node.js & Bun", + "description": "Connect JavaScript apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/javascript", + "reference_url": "/metadata/skills/chat-room/reference/clients/javascript.md" + }, + { + "name": "actors/quickstart/backend", + "title": "Node.js & Bun Quickstart", + "description": "Get started with Rivet Actors in Node.js and Bun", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/backend", + "reference_url": "/metadata/skills/chat-room/reference/actors/quickstart/backend.md" + }, + { + "name": "general/pool-configuration", + "title": "Pool Configuration", + "description": "Reference for runner pool configuration, including drain behavior, actor eviction rate limiting, and serverless-specific options.", + "canonical_url": "https://rivet.dev/docs/general/pool-configuration", + "reference_url": "/metadata/skills/chat-room/reference/general/pool-configuration.md" + }, + { + "name": "self-hosting/postgres", + "title": "PostgreSQL", + "description": "Configure PostgreSQL for self-hosted Rivet deployments.", + "canonical_url": "https://rivet.dev/docs/self-hosting/postgres", + "reference_url": "/metadata/skills/chat-room/reference/self-hosting/postgres.md" + }, + { + "name": "general/production-checklist", + "title": "Production Checklist", + "description": "Checklist for deploying Rivet Actors to production.", + "canonical_url": "https://rivet.dev/docs/general/production-checklist", + "reference_url": "/metadata/skills/chat-room/reference/general/production-checklist.md" + }, + { + "name": "self-hosting/production-checklist", + "title": "Production Checklist", + "description": "Checklist for deploying a self-hosted Rivet Engine to production.", + "canonical_url": "https://rivet.dev/docs/self-hosting/production-checklist", + "reference_url": "/metadata/skills/chat-room/reference/self-hosting/production-checklist.md" + }, + { + "name": "actors/queues", + "title": "Queues & Run Loops", + "description": "Use actor-local durable queues for serial run loops and request/response workflows.", + "canonical_url": "https://rivet.dev/docs/actors/queues", + "reference_url": "/metadata/skills/chat-room/reference/actors/queues.md" + }, + { + "name": "self-hosting/railway", + "title": "Railway Deployment", + "description": "Railway provides a simple platform for deploying Rivet Engine with automatic scaling and managed infrastructure.", + "canonical_url": "https://rivet.dev/docs/self-hosting/railway", + "reference_url": "/metadata/skills/chat-room/reference/self-hosting/railway.md" + }, + { + "name": "clients/react", + "title": "React", + "description": "Connect React apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/react", + "reference_url": "/metadata/skills/chat-room/reference/clients/react.md" + }, + { + "name": "actors/quickstart/react", + "title": "React Quickstart", + "description": "Build realtime React applications with Rivet Actors", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/react", + "reference_url": "/metadata/skills/chat-room/reference/actors/quickstart/react.md" + }, + { + "name": "actors/events", + "title": "Realtime", + "description": "Events enable realtime communication from actors to clients. While clients use actions to send data to actors, events allow actors to push updates to connected clients instantly.", + "canonical_url": "https://rivet.dev/docs/actors/events", + "reference_url": "/metadata/skills/chat-room/reference/actors/events.md" + }, + { + "name": "general/registry-configuration", + "title": "Registry Configuration", + "description": "This page documents the configuration options available when setting up a RivetKit registry. The registry configuration is passed to the `setup()` function.", + "canonical_url": "https://rivet.dev/docs/general/registry-configuration", + "reference_url": "/metadata/skills/chat-room/reference/general/registry-configuration.md" + }, + { + "name": "self-hosting/render", + "title": "Render Deployment", + "description": "Deploy Rivet Engine to Render with managed PostgreSQL and automatic HTTPS, using the experimental PostgreSQL backend.", + "canonical_url": "https://rivet.dev/docs/self-hosting/render", + "reference_url": "/metadata/skills/chat-room/reference/self-hosting/render.md" + }, + { + "name": "general/runtime-modes", + "title": "Runtime Modes", + "description": "RivetKit supports two runtime modes for running your actors:", + "canonical_url": "https://rivet.dev/docs/general/runtime-modes", + "reference_url": "/metadata/skills/chat-room/reference/general/runtime-modes.md" + }, + { + "name": "clients/rust", + "title": "Rust (Beta)", + "description": "Connect Rust apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/rust", + "reference_url": "/metadata/skills/chat-room/reference/clients/rust.md" + }, + { + "name": "actors/quickstart/rust", + "title": "Rust Quickstart (Beta)", + "description": "Build a Rivet Actor in Rust", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/rust", + "reference_url": "/metadata/skills/chat-room/reference/actors/quickstart/rust.md" + }, + { + "name": "actors/scaling", + "title": "Scaling & Concurrency", + "description": "This page has moved to [design patterns](/docs/actors/design-patterns).", + "canonical_url": "https://rivet.dev/docs/actors/scaling", + "reference_url": "/metadata/skills/chat-room/reference/actors/scaling.md" + }, + { + "name": "actors/sharing-and-joining-state", + "title": "Sharing and Joining State", + "description": "This page has moved to [design patterns](/docs/actors/design-patterns).", + "canonical_url": "https://rivet.dev/docs/actors/sharing-and-joining-state", + "reference_url": "/metadata/skills/chat-room/reference/actors/sharing-and-joining-state.md" + }, + { + "name": "actors/sqlite", + "title": "SQLite", + "description": "Use embedded SQLite in Rivet Actors with raw SQL queries.", + "canonical_url": "https://rivet.dev/docs/actors/sqlite", + "reference_url": "/metadata/skills/chat-room/reference/actors/sqlite.md" + }, + { + "name": "actors/sqlite-drizzle", + "title": "SQLite + Drizzle", + "description": "Use Drizzle ORM with embedded SQLite in Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/actors/sqlite-drizzle", + "reference_url": "/metadata/skills/chat-room/reference/actors/sqlite-drizzle.md" + }, + { + "name": "actors/quickstart/supabase", + "title": "Supabase Functions Quickstart", + "description": "Set up a Rivet project locally targeting Supabase Edge Functions.", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/supabase", + "reference_url": "/metadata/skills/chat-room/reference/actors/quickstart/supabase.md" + }, + { + "name": "clients/swift", + "title": "Swift", + "description": "Connect Swift apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/swift", + "reference_url": "/metadata/skills/chat-room/reference/clients/swift.md" + }, + { + "name": "clients/swiftui", + "title": "SwiftUI", + "description": "Build SwiftUI apps with Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/swiftui", + "reference_url": "/metadata/skills/chat-room/reference/clients/swiftui.md" + }, + { + "name": "actors/testing", + "title": "Testing", + "description": "Rivet provides a straightforward testing framework to build reliable and maintainable applications. This guide covers how to write effective tests for your actor-based services.", + "canonical_url": "https://rivet.dev/docs/actors/testing", + "reference_url": "/metadata/skills/chat-room/reference/actors/testing.md" + }, + { + "name": "self-hosting/tls", + "title": "TLS & Certificates", + "description": "How Rivet validates TLS root certificates.", + "canonical_url": "https://rivet.dev/docs/self-hosting/tls", + "reference_url": "/metadata/skills/chat-room/reference/self-hosting/tls.md" + }, + { + "name": "actors/troubleshooting", + "title": "Troubleshooting", + "description": "Common issues with Rivet Actors and how to resolve them.", + "canonical_url": "https://rivet.dev/docs/actors/troubleshooting", + "reference_url": "/metadata/skills/chat-room/reference/actors/troubleshooting.md" + }, + { + "name": "actors/types", + "title": "Types", + "description": "TypeScript types for working with Rivet Actors. This page covers context types used in lifecycle hooks and actions, as well as helper types for extracting types from actor definitions.", + "canonical_url": "https://rivet.dev/docs/actors/types", + "reference_url": "/metadata/skills/chat-room/reference/actors/types.md" + }, + { + "name": "actors/http-api", + "title": "Vanilla HTTP API", + "description": "Use the low-level HTTP handler to send and receive requests from actors.", + "canonical_url": "https://rivet.dev/docs/actors/http-api", + "reference_url": "/metadata/skills/chat-room/reference/actors/http-api.md" + }, + { + "name": "actors/versions", + "title": "Versions & Upgrades", + "description": "When you deploy new code, Rivet ensures actors are upgraded seamlessly without downtime.", + "canonical_url": "https://rivet.dev/docs/actors/versions", + "reference_url": "/metadata/skills/chat-room/reference/actors/versions.md" + }, + { + "name": "general/wasm-vs-native-sdk", + "title": "WASM vs Native SDK", + "description": "RivetKit runs your actors on a native or a WebAssembly runtime depending on your platform.", + "canonical_url": "https://rivet.dev/docs/general/wasm-vs-native-sdk", + "reference_url": "/metadata/skills/chat-room/reference/general/wasm-vs-native-sdk.md" + }, + { + "name": "actors/workflows", + "title": "Workflows", + "description": "Build durable, replayable run loops in Rivet Actors with steps, queue waits, timers, and rollback.", + "canonical_url": "https://rivet.dev/docs/actors/workflows", + "reference_url": "/metadata/skills/chat-room/reference/actors/workflows.md" + } + ] +} \ No newline at end of file diff --git a/.agents/skills/chat-room/openapi.json b/.agents/skills/chat-room/openapi.json new file mode 100644 index 0000000..ca482f7 --- /dev/null +++ b/.agents/skills/chat-room/openapi.json @@ -0,0 +1,1311 @@ +{ + "openapi": "3.0.0", + "info": { + "version": "2.2.0", + "title": "RivetKit API" + }, + "components": { + "schemas": {}, + "parameters": {} + }, + "paths": { + "/actors": { + "get": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": false, + "name": "name", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "actor_ids", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "key", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "actors": { + "type": "array", + "items": { + "type": "object", + "properties": { + "actor_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "namespace_id": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "create_ts": { + "type": "number" + }, + "connectable_ts": { + "type": "number", + "nullable": true + }, + "destroy_ts": { + "type": "number", + "nullable": true + }, + "sleep_ts": { + "type": "number", + "nullable": true + }, + "start_ts": { + "type": "number", + "nullable": true + }, + "error": { + "nullable": true + } + }, + "required": [ + "actor_id", + "name", + "key", + "namespace_id", + "runner_name_selector", + "create_ts" + ] + } + } + }, + "required": [ + "actors" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + }, + "put": { + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "datacenter": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "crash_policy": { + "type": "string" + }, + "input": { + "type": "string", + "nullable": true + } + }, + "required": [ + "name", + "key", + "runner_name_selector", + "crash_policy" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "actor": { + "type": "object", + "properties": { + "actor_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "namespace_id": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "create_ts": { + "type": "number" + }, + "connectable_ts": { + "type": "number", + "nullable": true + }, + "destroy_ts": { + "type": "number", + "nullable": true + }, + "sleep_ts": { + "type": "number", + "nullable": true + }, + "start_ts": { + "type": "number", + "nullable": true + }, + "error": { + "nullable": true + } + }, + "required": [ + "actor_id", + "name", + "key", + "namespace_id", + "runner_name_selector", + "create_ts" + ] + }, + "created": { + "type": "boolean" + } + }, + "required": [ + "actor", + "created" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + }, + "post": { + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "datacenter": { + "type": "string" + }, + "name": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "crash_policy": { + "type": "string" + }, + "key": { + "type": "string", + "nullable": true + }, + "input": { + "type": "string", + "nullable": true + } + }, + "required": [ + "name", + "runner_name_selector", + "crash_policy" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "actor": { + "type": "object", + "properties": { + "actor_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "namespace_id": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "create_ts": { + "type": "number" + }, + "connectable_ts": { + "type": "number", + "nullable": true + }, + "destroy_ts": { + "type": "number", + "nullable": true + }, + "sleep_ts": { + "type": "number", + "nullable": true + }, + "start_ts": { + "type": "number", + "nullable": true + }, + "error": { + "nullable": true + } + }, + "required": [ + "actor_id", + "name", + "key", + "namespace_id", + "runner_name_selector", + "create_ts" + ] + } + }, + "required": [ + "actor" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/actors/names": { + "get": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "namespace", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "names": { + "type": "object", + "additionalProperties": { + "type": "object", + "properties": { + "metadata": { + "type": "object", + "additionalProperties": { + "nullable": true + } + } + }, + "required": [ + "metadata" + ] + } + } + }, + "required": [ + "names" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/actors/{actor_id}/kv/keys/{key}": { + "get": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "actor_id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "key", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "value": { + "type": "string", + "nullable": true + } + }, + "required": [ + "value" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/gateway/{actorId}/health": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + } + ], + "responses": { + "200": { + "description": "Health check", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + } + } + } + }, + "/gateway/{actorId}/action/{action}": { + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "action", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The name of the action to execute" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "args": {} + }, + "required": [ + "args" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Action executed successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "output": {} + }, + "required": [ + "output" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Invalid action" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/gateway/{actorId}/request/{path}": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "put": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "delete": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "patch": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "head": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "options": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + } + }, + "/gateway/{actorId}/inspector/state": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Current actor state", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": {} + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + }, + "patch": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": {} + }, + "required": [ + "state" + ] + } + } + } + }, + "responses": { + "200": { + "description": "State updated", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "ok": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/connections": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Current actor connections", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "connections": { + "type": "array", + "items": { + "type": "object" + } + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/rpcs": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Available actor actions/RPCs", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "rpcs": { + "type": "object" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/action/{name}": { + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The name of the action to execute" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "args": { + "type": "array", + "items": {} + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Action executed successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "output": {} + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/queue": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 50 + }, + "description": "Maximum number of queue messages to return" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Queue status", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "size": { + "type": "integer" + }, + "maxSize": { + "type": "integer" + }, + "truncated": { + "type": "boolean" + }, + "messages": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "createdAtMs": { + "type": "integer" + } + } + } + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/traces": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "startMs", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 0 + }, + "description": "Start of time range in epoch milliseconds" + }, + { + "name": "endMs", + "in": "query", + "required": false, + "schema": { + "type": "integer" + }, + "description": "End of time range in epoch milliseconds. Defaults to now." + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 1000 + }, + "description": "Maximum number of spans to return" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Trace spans in OTLP JSON format", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "otlp": { + "type": "object" + }, + "clamped": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/workflow-history": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Workflow history and status", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "history": {}, + "isWorkflowEnabled": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/workflow/replay": { + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "entryId": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Workflow history after scheduling a replay", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "history": {}, + "isWorkflowEnabled": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/summary": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Full actor inspector summary", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": {}, + "connections": { + "type": "array", + "items": { + "type": "object" + } + }, + "rpcs": { + "type": "object" + }, + "queueSize": { + "type": "integer" + }, + "isStateEnabled": { + "type": "boolean" + }, + "isDatabaseEnabled": { + "type": "boolean" + }, + "isWorkflowEnabled": { + "type": "boolean" + }, + "workflowHistory": {} + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + } + } +} \ No newline at end of file diff --git a/.agents/skills/chat-room/reference/actors/access-control.md b/.agents/skills/chat-room/reference/actors/access-control.md new file mode 100644 index 0000000..02dc4e8 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/access-control.md @@ -0,0 +1,48 @@ +# Access Control + +> Source: `src/content/docs/actors/access-control.mdx` +> Canonical URL: https://rivet.dev/docs/actors/access-control +> Description: Authorize actions, queue publishes, and event subscriptions with explicit hooks. + +--- +Use access control to decide what authenticated clients are allowed to do. + +This is authorization, not authentication: + +- Use [authentication](/docs/actors/authentication) to identify who is calling. +- Use access-control rules to decide what they can do after connecting. + +## Permission Surfaces + +RivetKit authorization is explicit per surface: + +- `onBeforeConnect` rejects unauthenticated or malformed connections. +- Action handlers (`actions.*`) enforce action permissions. +- `queues..canPublish` allows or denies inbound queue publishes. +- `events..canSubscribe` allows or denies event subscriptions. + +## Fail By Default + +Use deny-by-default rules everywhere: + +1. Keep `onBeforeConnect` strict and reject invalid credentials. +2. In each action, explicitly allow expected roles and throw `forbidden` otherwise. +3. In `canPublish` and `canSubscribe`, return `true` only for allowed roles and end with `return false`. + +## Return Value Contract + +`canPublish` and `canSubscribe` must return a boolean: + +- `true`: allow +- `false`: deny with `forbidden` + +Returning `undefined`, `null`, or any non-boolean throws an internal error. + +## Notes + +- `canPublish` only applies to queue names defined in `queues`. +- Incoming queue messages for undefined queues are ignored and the publish succeeds as completed. +- `canSubscribe` only applies to event names defined in `events`. +- Broadcasting an event not defined in `events` still publishes to subscribers. + +_Source doc path: /docs/actors/access-control_ diff --git a/.agents/skills/chat-room/reference/actors/actions.md b/.agents/skills/chat-room/reference/actors/actions.md new file mode 100644 index 0000000..d00324e --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/actions.md @@ -0,0 +1,98 @@ +# Actions + +> Source: `src/content/docs/actors/actions.mdx` +> Canonical URL: https://rivet.dev/docs/actors/actions +> Description: Actions are how your backend, frontend, or other actors can communicate with actors. + +--- +Actions are very lightweight. They can be called thousands of times per second safely. Actions are executed via HTTP requests or via WebSockets if [using `.connect()`](/docs/actors/connections). + +For advanced use cases that require direct access to HTTP requests or WebSocket connections, see [raw HTTP and WebSocket handling](/docs/actors/fetch-and-websocket-handler). + +By default, actions run in parallel. If you need advanced control over concurrency, use [queues](/docs/actors/queues). + +## Writing Actions + +Actions are defined in the `actions` object when creating an actor: + +Each action receives a context object (commonly named `c`) as its first parameter, which provides access to state, connections, and other utilities. Additional parameters follow after that. + +## Calling Actions + +Actions can be called in different ways depending on your use case: + +### Frontend (createClient) + +Learn more about [communicating with actors from the frontend](/docs/actors/communicating-between-actors). + +### Backend (registry.handler) + +Learn more about [communicating with actors from the backend](/docs/actors/communicating-between-actors). + +### Actor-to-Actor (c.client()) + +Learn more about [communicating between actors](/docs/actors/communicating-between-actors). + +Calling actions from the client are async and require an `await`, even if the action itself is not async. + +### Type Safety + +The actor client includes type safety out of the box. When you use `createClient()`, TypeScript automatically infers action parameter and return types: + +## Error Handling + +Actors provide robust error handling out of the box for actions. + +### User Errors + +`UserError` can be used to return rich error data to the client. You can provide: + +- A human-readable message +- A machine-readable code that's useful for matching errors in a try-catch (optional) +- A metadata object for providing richer error context (optional) + +For example: + +### Internal Errors + +All other errors will return an error with the code `internal_error` to the client. This helps keep your application secure, as errors can sometimes expose sensitive information. + +## Schema Validation + +If passing data to an actor from the frontend, use a library like [Zod](https://zod.dev/) to validate input data. + +For example, to validate action parameters: + +## Streaming Data + +Actions have a single return value. To stream realtime data in response to an action, use [events](/docs/actors/events). + +## Canceling Long-Running Actions + +For operations that should be cancelable on-demand, create your own `AbortController`. Chain it with `c.abortSignal` so actor shutdown also cancels the operation. + +See [Actor Shutdown Abort Signal](/docs/actors/lifecycle#actor-shutdown-abort-signal) for automatically canceling operations when the actor stops. + +## Using `ActionContext` Externally + +When writing complex logic for actions, you may want to extract parts of your implementation into separate helper functions. When doing this, you'll need a way to properly type the context parameter. + +Rivet provides the `ActionContextOf` utility type for exactly this purpose: + +See [types](/docs/actors/types) for more details on using `ActionContextOf` and other utility types. + +## Debugging + +- `GET /inspector/rpcs` lists all available actions on an actor. +- `POST /inspector/action/:name` executes an action with JSON args and returns output. +- In non-dev mode, inspector endpoints require authorization. + +## API Reference + +- [`Actions`](/typedoc/interfaces/rivetkit.mod.Actions.html) - Interface for defining actions +- [`ActionContext`](/typedoc/interfaces/rivetkit.mod.ActionContext.html) - Context available in action handlers +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining actors with actions +- [`ActorHandle`](/typedoc/types/rivetkit.client_mod.ActorHandle.html) - Handle for calling actions from client +- [`ActorActionFunction`](/typedoc/types/rivetkit.client_mod.ActorActionFunction.html) - Type for action functions + +_Source doc path: /docs/actors/actions_ diff --git a/.agents/skills/chat-room/reference/actors/actor-runtime-socket.md b/.agents/skills/chat-room/reference/actors/actor-runtime-socket.md new file mode 100644 index 0000000..2f736d5 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/actor-runtime-socket.md @@ -0,0 +1,54 @@ +# Actor Runtime Socket + +> Source: `src/content/docs/actors/actor-runtime-socket.mdx` +> Canonical URL: https://rivet.dev/docs/actors/actor-runtime-socket +> Description: Connect trusted local tools to a running Rivet Actor over an experimental actor-local protocol. + +--- +> **Experimental:** The Actor Runtime Socket protocol and API may change between releases. It is available only in the Unix native runtime and must be enabled per actor. + +The **Actor Runtime Socket** is a generic, actor-local protocol for trusted tools running in the same application environment as a Rivet Actor. SQLite is its first capability; Unix domain sockets are its current transport. + +Each running actor generation lazily creates its own socket. The socket is removed when that generation sleeps, stops, or is destroyed, so clients must request the current path again after the actor wakes or restarts. + +## Enable the socket + +Enable the feature under the actor's `options`, then provision it from the actor context: + +```ts @nocheck +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +export const example = actor({ + options: { + enableActorRuntimeSocket: true, + }, + db: db({ + onMigrate: async (db) => { + await db.execute("CREATE TABLE IF NOT EXISTS items (value TEXT)"); + }, + }), + run: async (c) => { + const { path } = await c.actorRuntimeSocket(); + // Give `path` only to trusted, application-local tooling. + }, +}); +``` + +Provisioning fails unless the actor has an enabled LocalNative SQLite database. The per-process socket directory uses mode `0700`, and each actor socket uses mode `0600`. + +## Protocol + +Unix `SOCK_STREAM` provides a reliable local byte stream but does not preserve message boundaries. Every frame is therefore a four-byte big-endian payload length followed by a versioned BARE (`vbare`) payload. The embedded protocol version is a two-byte little-endian prefix. Clients begin with `ClientHello`; the server returns `HelloOk` with the maximum frame size or rejects an unsupported version. + +The current protocol supports: + +- multi-statement SQLite scripts with `SqliteExec`; +- single-statement parameterized queries with `SqliteQuery`; +- transactions spanning requests with `SqliteBegin`, `SqliteCommit`, and `SqliteRollback`. + +A transaction is identified by a client-chosen `leaseKey` scoped to one connection. Other actor SQL and other socket transactions wait in FIFO order while it runs. Transactions default to a 60-second safety timeout; `SqliteBegin.timeoutMs` may override it. If the deadline fires, RivetKit rolls the transaction back and later requests for that key receive `LeaseExpired`. + +The socket is an application-local integration boundary, not a network authentication boundary. It intentionally has no bearer token. Clients must still honor framing and response limits, and should reconnect using a newly provisioned path after actor generation changes. + +_Source doc path: /docs/actors/actor-runtime-socket_ diff --git a/.agents/skills/chat-room/reference/actors/appearance.md b/.agents/skills/chat-room/reference/actors/appearance.md new file mode 100644 index 0000000..f60b1a1 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/appearance.md @@ -0,0 +1,50 @@ +# Icons & Names + +> Source: `src/content/docs/actors/appearance.mdx` +> Canonical URL: https://rivet.dev/docs/actors/appearance +> Description: Customize actors with display names and icons for the Rivet inspector and dashboard. + +--- +# Icons & Names + +Actors can be customized with a display name and icon that appear in the Rivet inspector & dashboard. This helps identify actors at a glance when managing your application. + +## Configuration + +Set the `name` and `icon` properties in your actor's `options`: + +## Icon Formats + +The `icon` property accepts two formats: + +### Emoji + +Use any emoji character directly: + +### FontAwesome Icons + +Use [FontAwesome](https://fontawesome.com/search) icon names without the "fa" prefix: + +## Default Behavior + +If no `icon` is specified, actors display the default actor icon. If no `name` is specified, the actor's registry key (e.g., `chatRoom`, `gameServer`) is displayed instead. + +## Examples + +Here are some common patterns: + +## Advanced: Run Handler Metadata + +For library developers creating reusable run handlers, you can bundle icon and name metadata directly with the `run` property. This allows libraries to provide sensible defaults without requiring users to configure them manually. + +Instead of returning a function from your run handler factory, return an object with `name`, `icon`, and `run`: + +Users can then use this directly: + +This run-handler metadata is currently applied through the registry and serverless metadata paths. The native runtime and inspector config read the actor's `options.name` and `options.icon` directly, so set those explicitly if you need the name or icon to appear everywhere. + +Actor-level `options.name` and `options.icon` always take precedence, allowing users to override library defaults: + +The built-in `workflow()` helper uses this pattern to automatically display the workflow icon for workflow-based actors. + +_Source doc path: /docs/actors/appearance_ diff --git a/.agents/skills/chat-room/reference/actors/authentication.md b/.agents/skills/chat-room/reference/actors/authentication.md new file mode 100644 index 0000000..c456dde --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/authentication.md @@ -0,0 +1,105 @@ +# Authentication + +> Source: `src/content/docs/actors/authentication.mdx` +> Canonical URL: https://rivet.dev/docs/actors/authentication +> Description: Secure your actors with authentication and authorization. + +--- +## Do You Need Authentication? + +### Rivet Cloud + + Actors are private by default on Rivet Cloud. Only requests with the publishable token can interact with actors. + + - **Backend-only actors**: If your publishable token is only included in your backend, then authentication is not necessary. + - **Frontend-accessible actors**: If your publishable token is included in your frontend, then implementing authentication is recommended. + +### Self-Hosted + + Actors are public by default on self-hosted Rivet. Anyone can access them without a token. + + - **Only accessible within private network**: If Rivet is only accessible within your private network, then authentication is not necessary. + - **Rivet exposed to the public internet**: If Rivet is configured to accept traffic from the public internet, then implementing authentication is recommended. + +## Authentication Connections + +Authentication is configured through either: + +- `onBeforeConnect` for simple pass/fail validation +- `createConnState` when you need to access user data in your actions via `c.conn.state` + +## Access Control + +After a connection is authenticated, use [Access Control](/docs/actors/access-control) to enforce authorization: + +- Check permissions in action handlers. +- Use `queues..canPublish` to gate inbound queue publishes. +- Use `events..canSubscribe` to gate event subscriptions. + +### `onBeforeConnect` + +The `onBeforeConnect` hook validates credentials before allowing a connection. Throw an error to reject the connection. + +### `createConnState` + +Use `createConnState` to extract user data from credentials and store it in connection state. This data is accessible in actions via `c.conn.state`. Like `onBeforeConnect`, throwing an error will reject the connection. See [connections](/docs/actors/connections) for more details. + +## Available Auth Data + +Authentication hooks have access to several properties: + +| Property | Description | +|----------|-------------| +| `params` | Custom data passed by the client when connecting (see [connection params](/docs/actors/connections#extracting-data-from-connection-params)) | +| `c.request` | The underlying HTTP request object | +| `c.request.headers` | Request headers for tokens, API keys (does not work for `.connect()`) | +| `c.state` | Actor state for authorization decisions (see [state](/docs/actors/state)) | +| `c.key` | The actor's key (see [keys](/docs/actors/keys)) | + +It's recommended to use `params` instead of `c.request.headers` whenever possible since it works for both HTTP & WebSocket connections. + +## Client Usage + +### Passing Credentials + +Pass authentication data when connecting. Use `getParams` when you need a fresh JWT for every connection or reconnect: + +### Handling Errors + +Authentication errors use the same system as regular errors. See [errors](/docs/actors/errors) for more details. + +## Examples + +### JWT + +Validate JSON Web Tokens and extract user claims: + +### External Auth Provider + +Validate credentials against an external authentication service: + +### Using `c.state` In Authorization + +Access actor state via `c.state` and the actor's key via `c.key` to make authorization decisions: + +### Role-Based Access Control + +Create helper functions for common authorization patterns: + +### Rate Limiting + +Use `c.vars` to track connection attempts and rate limit by user: + +The limits in this example are [ephemeral](/docs/actors/state#ephemeral-variables). If you wish to persist rate limits, you can optionally replace `vars` with `state`. + +### Caching Tokens + +Cache validated tokens in `c.vars` to avoid redundant validation on repeated connections. See [ephemeral variables](/docs/actors/state#ephemeral-variables) for more details. + +## API Reference + +- [`AuthIntent`](/typedoc/types/rivetkit.mod.AuthIntent.html) - Authentication intent type +- [`OnBeforeConnectContext`](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html) - Context for auth checks +- [`OnConnectContext`](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html) - Context after connection + +_Source doc path: /docs/actors/authentication_ diff --git a/.agents/skills/chat-room/reference/actors/communicating-between-actors.md b/.agents/skills/chat-room/reference/actors/communicating-between-actors.md new file mode 100644 index 0000000..8aeaf39 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/communicating-between-actors.md @@ -0,0 +1,42 @@ +# Communicating Between Actors + +> Source: `src/content/docs/actors/communicating-between-actors.mdx` +> Canonical URL: https://rivet.dev/docs/actors/communicating-between-actors +> Description: Learn how actors can call other actors and share data + +--- +Actors can communicate with each other using the server-side actor client, enabling complex workflows and data sharing between different actor instances. + +We recommend reading the [clients documentation](/docs/clients) first. This guide focuses specifically on communication between actors. + +## Using the Server-Side Actor Client + +The server-side actor client allows actors to call other actors within the same registry. Access it via `c.client()` in your actor context: + +If two actors call each other and their return types are inferred from the other actor's response, you may hit circular type errors (`TS2322`, `TS2722`, or `c.state` becoming `unknown`). Fix this by writing explicit return types on those actions. + +## Use Cases and Patterns + +### Actor Orchestration + +Use a coordinator actor to manage complex workflows: + +### Data Aggregation + +Collect data from multiple actors: + +### Event-Driven Architecture + +Use connections to listen for events from other actors: + +### Batch Operations + +Process multiple items in parallel: + +## API Reference + +- [`ActorHandle`](/typedoc/types/rivetkit.client_mod.ActorHandle.html) - Handle for calling other actors +- [`Client`](/typedoc/types/rivetkit.mod.Client.html) - Client type for actor communication +- [`ActorAccessor`](/typedoc/interfaces/rivetkit.client_mod.ActorAccessor.html) - Accessor for getting actor handles + +_Source doc path: /docs/actors/communicating-between-actors_ diff --git a/.agents/skills/chat-room/reference/actors/connections.md b/.agents/skills/chat-room/reference/actors/connections.md new file mode 100644 index 0000000..10ef081 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/connections.md @@ -0,0 +1,119 @@ +# Connections + +> Source: `src/content/docs/actors/connections.mdx` +> Canonical URL: https://rivet.dev/docs/actors/connections +> Description: Connections represent client connections to your actor. They provide a way to handle client authentication, manage connection-specific data, and control the connection lifecycle. + +--- +For documentation on connecting to actors from clients, see the [Clients documentation](/docs/clients). For worked presence and chat patterns, see the cookbook: [Live Cursors and Presence](/cookbook/live-cursors/) and [Chat Room](/cookbook/chat-room/). + +## Parameters + +When clients connect to an actor, they can pass connection parameters that are handled during the connection process. Use `params` for static values, or `getParams` when you need fresh connection data each time a connection opens. + +For example: + +## Connection State + +There are two ways to define an actor's connection state: + + +### connState + + Define connection state as a constant value: + + + + This value will be cloned for every new connection using `structuredClone`. + + + +### createConnState + + Create connection state dynamically with a function called for each connection: + + + + +## Connection Lifecycle + +Each client connection goes through a series of lifecycle hooks that allow you to validate, initialize, and clean up connection-specific resources. + +**On Connect** (per client) + +- `onBeforeConnect` +- `createConnState` +- `onConnect` + +Pending connections are not visible in `c.conns` while `onBeforeConnect` or `createConnState` is running. RivetKit adds the connection to `c.conns` after those hooks succeed and before `onConnect` runs. + +**On Disconnect** (per client) + +- `onDisconnect` + +### `createConnState` and `connState` + +[API Reference](/typedoc/interfaces/rivetkit.mod.CreateConnStateContext.html) + +There are two ways to define the initial state for connections: +1. `connState`: Define a constant object that will be used as the initial state for all connections +2. `createConnState`: A function that dynamically creates initial connection state based on connection parameters. Can be async. + +Connections are not visible in `c.conns` until `createConnState` completes successfully. + +### `onBeforeConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html) + +The `onBeforeConnect` hook is called whenever a new client connects to the actor. Can be async. Clients can pass parameters when connecting, accessible via `params`. This hook is used for connection validation and can throw errors to reject connections. + +The `onBeforeConnect` hook does NOT return connection state - it's used solely for validation. + +Connections are not visible in `c.conns` while `onBeforeConnect` is running. + +Connections cannot interact with the actor until this method completes successfully. Throwing an error will abort the connection. This can be used for authentication, see [Authentication](/docs/actors/authentication) for details. + +### `onConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html) + +Executed after the client has successfully connected. Can be async. Receives the connection object as a second parameter. + +By the time `onConnect` runs, the connection is visible in `c.conns`. + +Messages will not be processed for this actor until this hook succeeds. Errors thrown from this hook will cause the client to disconnect. + +### `onDisconnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Called when a client disconnects from the actor. Can be async. Receives the connection object as a second parameter. Use this to clean up any connection-specific resources. + +## Connection List + +All active connections can be accessed through the context object's `conns` property. This is a `Map` of all current connections, keyed by connection ID. + +This is frequently used with `conn.send(name, event)` to send messages directly to clients. To send an event to all connections at once, use `c.broadcast()` instead. See [Events](/docs/actors/events) for more details on broadcasting. + +For example: + +`conn.send()` has no effect on [low-level WebSocket connections](/docs/actors/websocket-handler). For low-level WebSockets, use the WebSocket API directly (e.g., `websocket.send()`). + +## Disconnecting clients + +Connections can be disconnected from within an action: + +If you need to wait for the disconnection to complete, you can use `await`: + +This ensures the underlying network connections close cleanly before continuing. + +## API Reference + +- [`Conn`](/typedoc/interfaces/rivetkit.mod.Conn.html) - Connection interface +- [`ConnInitContext`](/typedoc/interfaces/rivetkit.mod.ConnInitContext.html) - Connection initialization context +- [`CreateConnStateContext`](/typedoc/interfaces/rivetkit.mod.CreateConnStateContext.html) - Context for creating connection state +- [`OnBeforeConnectContext`](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html) - Pre-connection lifecycle hook context +- [`OnConnectContext`](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html) - Post-connection lifecycle hook context +- [`ActorConn`](/typedoc/types/rivetkit.client_mod.ActorConn.html) - Typed connection from client side + +_Source doc path: /docs/actors/connections_ diff --git a/.agents/skills/chat-room/reference/actors/debugging.md b/.agents/skills/chat-room/reference/actors/debugging.md new file mode 100644 index 0000000..409b381 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/debugging.md @@ -0,0 +1,644 @@ +# Debugging + +> Source: `src/content/docs/actors/debugging.mdx` +> Canonical URL: https://rivet.dev/docs/actors/debugging +> Description: Inspect and debug running Rivet Actors, runners, and provider configs using management, runner, and actor inspector HTTP APIs. + +--- +## Connecting to Rivet + +All debugging endpoints in this guide are available both locally and in production. In local development, the base URL is `http://localhost:6420` with no authentication. In production (Rivet Cloud or self-hosted), you connect to your Rivet Engine endpoint with a token. + +### Setup + +All examples in this guide use these shell variables. Extract them from your `RIVET_ENDPOINT` (`https://:@`): + +```bash +# From RIVET_ENDPOINT=https://my-namespace:sk_abc123@api.rivet.dev +export RIVET_API="https://api.rivet.dev" +export RIVET_NAMESPACE="my-namespace" +export RIVET_TOKEN="sk_abc123" + +# For local development: +# export RIVET_API="http://localhost:6420" +``` + +Rivet Cloud issues two token types: `sk_` (secret key, server-side only) and `pk_` (public key, client-safe). For debugging, always use `sk_`. See [Endpoints](/docs/general/endpoints) for more details. + +## Management API + +The management API runs on the manager base path (default root path) and is used to list, create, and look up actors. + +### Authentication + +| Environment | Authentication | +|---|---| +| **Local development** | No authentication required. All endpoints are accessible without tokens. | +| **Self-hosted engine** | Set `RIVET_TOKEN` to enable authenticated access to restricted endpoints like KV. | +| **Rivet Cloud** | Authentication is enforced by your deployment entrypoint. For manager KV access, use the bearer token header below when enabled. | + +Restricted endpoints (like KV reads) require the `Authorization: Bearer` header when `RIVET_TOKEN` is configured: + +```bash +curl "$RIVET_API/actors/{actor_id}/kv/keys/{base64_key}" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +### List Actors + +```bash +# List all actors with a given name +curl "$RIVET_API/actors?name=my-actor&namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" + +# Look up one actor by key (name is required when key is provided) +curl "$RIVET_API/actors?name=my-actor&key=%5B%22my-key%22%5D&namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" + +# List actors by IDs (comma-separated) +curl "$RIVET_API/actors?actor_ids=id1,id2&namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Rules: + +- `key` requires `name`. +- `actor_ids` cannot be combined with `name` or `key`. + +Returns: + +```json +{ + "actors": [ + { + "actor_id": "abc123", + "name": "my-actor", + "key": "[\"default\"]", + "namespace_id": "default", + "create_ts": 1706000000000 + } + ] +} +``` + +### Create Actor + +`POST /actors` creates a new actor. + +```bash +curl -X POST "$RIVET_API/actors?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H 'Content-Type: application/json' \ + -d '{ + "name": "my-actor", + "runner_name_selector": "default", + "crash_policy": "restart" + }' +``` + +### Create or Get Actor + +`PUT /actors` creates an actor if it does not exist, otherwise returns the existing one. + +```bash +curl -X PUT "$RIVET_API/actors?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H 'Content-Type: application/json' \ + -d '{ + "name": "my-actor", + "key": "[\"default\"]", + "runner_name_selector": "default", + "crash_policy": "restart" + }' +``` + +Returns the actor object with its `actor_id`. + +### List Actor Names + +```bash +curl "$RIVET_API/actors/names?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns all registered actor names and their metadata. + +### Read Actor KV + +Requires authentication (see above). + +```bash +curl "$RIVET_API/actors/{actor_id}/kv/keys/{base64_key}" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns the value stored at the given key in the actor KV compatibility snapshot. After an actor has migrated to SQLite-backed runtime storage, this endpoint is stale for user KV and internal runtime records; it continues to expose the frozen pre-migration KV data. The inspector token key is the exception and remains mirrored for dashboard compatibility. + +See the [OpenAPI spec](https://github.com/rivet-dev/rivet/tree/main/rivetkit-openapi) for the full schema of all management endpoints. + +## Runner API + +Use the runner endpoints to debug scheduler capacity and provider configuration (for example serverless URL, headers, and limits) through the Rivet API. + +### List Runner Names + +```bash +curl "$RIVET_API/runners/names?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns the runner pools available in the namespace: + +```json +{ + "names": ["default", "gpu-workers"], + "pagination": { "cursor": null } +} +``` + +### List Runners in a Pool + +```bash +curl "$RIVET_API/runners?namespace=$RIVET_NAMESPACE&name=default&include_stopped=true&limit=100" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Useful fields when debugging: + +- `remaining_slots` / `total_slots` for capacity. +- `drain_ts` and `stop_ts` for shutdown behavior. +- `last_ping_ts` and `last_connected_ts` for connectivity. + +### Inspect Provider Config (Runner Config) + +```bash +curl "$RIVET_API/runner-configs?namespace=$RIVET_NAMESPACE&runner_name=default" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns the configured provider settings per datacenter and the latest pool error (if any): + +```json +{ + "runner_configs": { + "default": { + "datacenters": { + "dc-1": { + "serverless": { + "url": "https://your-deployment.example.com/rivet", + "headers": { "Authorization": "Bearer token" }, + "request_lifespan": 55, + "slots_per_runner": 1, + "max_runners": 10 + }, + "runner_pool_error": null + } + } + } + }, + "pagination": { "cursor": null } +} +``` + +`runner_pool_error` mirrors actor scheduling errors such as `serverless_http_error`, `serverless_connection_error`, and `serverless_stream_ended_early`. + +### Check Serverless Provider Health + +Use this to test whether Rivet can reach your serverless provider URL and read runner metadata: + +```bash +curl -X POST "$RIVET_API/runner-configs/serverless-health-check?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "url": "https://your-deployment.example.com/rivet", + "headers": { + "Authorization": "Bearer token" + } + }' +``` + +Possible responses: + +```json +{ "success": { "version": "1.2.3" } } +``` + +```json +{ + "failure": { + "error": { + "message": "non-success status from metadata endpoint", + "details": "received status 503" + } + } +} +``` + +### Refresh Provider Metadata + +If you deploy new actor code or routes and metadata has not updated yet, force a refresh: + +```bash +curl -X POST "$RIVET_API/runner-configs/default/refresh-metadata?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{}' +``` + +## Actor API + +All actor-level endpoints are accessed through the gateway. The gateway routes requests to the correct actor instance using the actor ID in the URL path: + +``` +{RIVET_API}/gateway/{actor_id}/{path} +``` + +The gateway only accepts actor IDs, not names. Use `GET /actors?name=...` from the management API to look up actor IDs first. + +### Authentication + +Standard actor endpoints (health, actions, requests) and inspector endpoints have separate authentication requirements. + +#### Standard Endpoints + +| Environment | Authentication | +|---|---| +| **Local development** | No authentication required. | +| **Self-hosted engine** | The Rivet Engine handles authentication at the gateway level. | +| **Rivet Cloud** | Authentication is handled by the Rivet Cloud platform at the gateway level. | + +#### Inspector Endpoints + +Each actor generates a unique inspector token on first start and persists it in internal SQLite storage. It is also mirrored to legacy KV key `0x03` (base64 `Aw==`) for dashboard compatibility. Pass it as a bearer token in the `Authorization` header. + +Inspector endpoints always require the actor's inspector token, including in local development. There is no local-development bypass. + +| Environment | Authentication | +|---|---| +| **Local development** | Bearer the actor's inspector token in the `Authorization` header. Fetch it through the management KV endpoint (see below). | +| **Self-hosted engine** | Bearer the actor's inspector token in the `Authorization` header. The Rivet dashboard fetches it automatically; for direct API access, fetch it through the management KV endpoint (see below). | +| **Rivet Cloud** | Bearer the actor's inspector token in the `Authorization` header. The Rivet dashboard fetches it automatically; for direct API access, fetch it through the management KV endpoint (see below). | + +```bash +curl "$RIVET_API/gateway/{actor_id}/inspector/summary" \ + -H 'Authorization: Bearer YOUR_INSPECTOR_TOKEN' +``` + +#### Retrieving the Inspector Token + +Each actor generates a unique inspector token on first start and persists it in internal SQLite storage. The token is also mirrored to the legacy KV key below so the Rivet dashboard can continue to retrieve it through the management KV endpoint. This applies in every environment, including local development. + +The inspector token is stored at internal KV key `0x03` (base64: `Aw==`). The response value is also base64-encoded. + +```bash +# Fetch the inspector token for a specific actor +ACTOR_ID="your-actor-id" + +RESPONSE=$(curl -s "$RIVET_API/actors/$ACTOR_ID/kv/keys/Aw==" \ + -H "Authorization: Bearer $RIVET_TOKEN") + +# Extract and decode the base64 value +INSPECTOR_TOKEN=$(echo "$RESPONSE" | jq -r '.value' | base64 -d) + +# Use it to call inspector endpoints +curl "$RIVET_API/gateway/$ACTOR_ID/inspector/summary" \ + -H "Authorization: Bearer $INSPECTOR_TOKEN" +``` + +### Standard Actor Endpoints + +These are the built-in actor endpoints available through the gateway: + +```bash +# Health check +curl $RIVET_API/gateway/{actor_id}/health + +# Metadata +curl $RIVET_API/gateway/{actor_id}/metadata + +# Call an action +curl -X POST $RIVET_API/gateway/{actor_id}/action/myAction \ + -H 'Content-Type: application/json' \ + -d '{"args": [1, 2, 3]}' + +# Send queue message (queue name in path) +curl -X POST $RIVET_API/gateway/{actor_id}/queue/jobs \ + -H 'Content-Type: application/json' \ + -d '{"body":{"id":"job-1"}}' + +# Send queue message and wait for completion (optional timeout in ms) +curl -X POST $RIVET_API/gateway/{actor_id}/queue/jobs \ + -H 'Content-Type: application/json' \ + -d '{"body":{"id":"job-1"},"wait":true,"timeout":5000}' + +# Forward an HTTP request to the actor's onRequest handler +curl $RIVET_API/gateway/{actor_id}/request/my/custom/path +``` + +Queue send responses always include a `status` field: + +```json +{ "status": "completed" } +``` + +The `response` field is only present when the queue handler returns a value: + +```json +{ "status": "completed", "response": { "result": "ok" } } +``` + +If `wait: true` and the timeout is reached, `status` is `"timedOut"`. + +### Inspector Endpoints + +The inspector HTTP API exposes JSON endpoints for querying and modifying actor internals at runtime. These are designed for agent-based debugging and tooling. + +Every inspector endpoint requires the actor's inspector token as a bearer token, including in local development. The examples below omit the `Authorization` header for brevity, but you must add `-H "Authorization: Bearer $INSPECTOR_TOKEN"` to each request. See [Retrieving the Inspector Token](#retrieving-the-inspector-token) above. + +#### Get State + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/state +``` + +Returns the actor's current persisted state: + +```json +{ + "state": { "count": 42, "users": [] }, + "isStateEnabled": true +} +``` + +#### Set State + +```bash +curl -X PATCH $RIVET_API/gateway/{actor_id}/inspector/state \ + -H 'Content-Type: application/json' \ + -d '{"state": {"count": 0, "users": []}}' +``` + +Returns: + +```json +{ "ok": true } +``` + +#### Get Connections + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/connections +``` + +Returns all active connections with their params, state, and metadata: + +```json +{ + "connections": [ + { + "type": "websocket", + "id": "conn-id", + "details": { + "type": "websocket", + "params": {}, + "stateEnabled": true, + "state": {}, + "subscriptions": 2, + "isHibernatable": true + } + } + ] +} +``` + +#### Get RPCs + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/rpcs +``` + +Returns a list of available actions: + +```json +{ "rpcs": ["increment", "getCount"] } +``` + +#### Execute Action + +```bash +curl -X POST $RIVET_API/gateway/{actor_id}/inspector/action/increment \ + -H 'Content-Type: application/json' \ + -d '{"args": [5]}' +``` + +Returns: + +```json +{ "output": 47 } +``` + +#### Get Queue Status + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/queue?limit=10 +``` + +Returns queue status with messages: + +```json +{ + "size": 3, + "maxSize": 1000, + "truncated": false, + "messages": [ + { "id": 1, "name": "process", "createdAtMs": 1706000000000 } + ] +} +``` + +#### Get Workflow History + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/workflow-history +``` + +Returns: + +```json +{ + "history": null, + "isWorkflowEnabled": false +} +``` + +#### Get Database Schema + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/database/schema +``` + +Returns discovered SQLite tables and views when the actor has `c.db` enabled: + +```json +{ + "schema": { + "tables": [ + { + "table": { "schema": "main", "name": "test_data", "type": "table" }, + "columns": [ + { "cid": 0, "name": "id", "type": "", "notnull": 0, "dflt_value": null, "pk": 0 } + ], + "foreignKeys": [], + "records": 2 + } + ] + } +} +``` + +#### Get Database Rows + +```bash +curl "$RIVET_API/gateway/{actor_id}/inspector/database/rows?table=test_data&limit=100&offset=0" +``` + +Returns paged rows for a specific SQLite table or view: + +```json +{ + "rows": [ + { + "id": 1, + "value": "Alice", + "payload": "", + "created_at": 1706000000000 + } + ] +} +``` + +#### Execute SQLite + +Run manual SQL against an actor's SQLite database. This supports both read-only queries and mutations. + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/database/execute \ + -H 'Content-Type: application/json' \ + -d '{ + "sql": "SELECT id, value FROM test_data WHERE value = ? ORDER BY id DESC", + "args": ["alpha"] + }' +``` + +Returns: + +```json +{ + "rows": [ + { "id": 2, "value": "alpha" } + ] +} +``` + +You can also use named SQLite bindings through a `properties` object: + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/database/execute \ + -H 'Content-Type: application/json' \ + -d '{ + "sql": "SELECT id, value FROM test_data WHERE value = :value ORDER BY id DESC", + "properties": { + "value": "alpha" + } + }' +``` + +For mutations, use `RETURNING` if you want rows back. Otherwise the statement still runs and `rows` is empty: + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/database/execute \ + -H 'Content-Type: application/json' \ + -d '{ + "sql": "INSERT INTO test_data (value, created_at) VALUES (?, ?) RETURNING id, value", + "args": ["beta", 1706000000000] + }' +``` + +For workflow-enabled actors, `history` is a JSON object with `nameRegistry`, `entries`, and `entryMetadata`. Step outputs, loop state, and message payloads are decoded from CBOR into normal JSON values. + +#### Replay Workflow From Step + +Reset a workflow to a specific step and restart execution immediately. Omitting `entryId` replays the workflow from the beginning. + +If the workflow is still running when you call replay, the endpoint rejects the request with `409 Conflict` and an `actor/workflow_in_flight` error instead of cancelling the live run for you. + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/workflow/replay \ + -H 'Content-Type: application/json' \ + -d '{"entryId":"workflow-step-id"}' +``` + +Returns the same JSON shape as `/inspector/workflow-history`: + +```json +{ + "history": { + "nameRegistry": ["step-one", "step-two"], + "entries": [], + "entryMetadata": {} + }, + "isWorkflowEnabled": true +} +``` + +While a workflow is in flight, the response shape is: + +```json +{ + "group": "actor", + "code": "workflow_in_flight", + "message": "Workflow replay is unavailable while the workflow is currently in flight.", + "metadata": null +} +``` + +#### Summary + +Get a full snapshot of the actor in a single request: + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/summary +``` + +Returns: + +```json +{ + "state": { "count": 42 }, + "connections": [], + "rpcs": ["increment", "getCount"], + "queueSize": 0, + "isStateEnabled": true, + "isDatabaseEnabled": false, + "isWorkflowEnabled": false, + "workflowHistory": null +} +``` + +When workflow history is present in `/inspector/summary`, `workflowHistory` is returned as the same decoded JSON shape as `/inspector/workflow-history`. + +### Polling + +Inspector endpoints are safe to poll. For live monitoring, poll at 1-5 second intervals. The `/inspector/summary` endpoint is useful for periodic snapshots since it returns all data in a single request. + +## OpenAPI Spec + +An OpenAPI specification covering many of the management and actor endpoints is available: + +- In the repository at [`rivetkit-openapi/openapi.json`](https://github.com/rivet-dev/rivet/tree/main/rivetkit-openapi) +- Served at `/doc` on the manager when running locally + +The checked-in spec does not yet list every endpoint documented on this page (for example the actor metadata and queue routes and the inspector database routes), so treat this page as the authoritative reference where they differ. + +_Source doc path: /docs/actors/debugging_ diff --git a/.agents/skills/chat-room/reference/actors/design-patterns.md b/.agents/skills/chat-room/reference/actors/design-patterns.md new file mode 100644 index 0000000..77ecb40 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/design-patterns.md @@ -0,0 +1,163 @@ +# Design Patterns + +> Source: `src/content/docs/actors/design-patterns.mdx` +> Canonical URL: https://rivet.dev/docs/actors/design-patterns +> Description: Common patterns and anti-patterns for building scalable actor systems. + +--- +## How Actors Scale + +Actors are inherently scalable because of how they're designed: + +- **Isolated state:** Each actor manages its own private data. No shared state means no conflicts and no locks, so actors run concurrently without coordination. +- **Actor-to-actor communication:** Actors interact through [actions](/docs/actors/actions) and [events](/docs/actors/events), so they don't need to coordinate access to shared data. This makes it easy to distribute them across machines. +- **Small, focused units:** Each actor handles a limited scope (a single user, document, or chat room), so load naturally spreads across many actors rather than concentrating in one place. +- **Horizontal scaling:** Adding more machines automatically distributes actors across them. + +These properties form the foundation for the patterns described below. + +## Actor Per Entity + +The core pattern is creating one actor per entity in your system. Each actor represents a single user, document, chat room, or other distinct object. This keeps actors small, independent, and easy to scale. + +**Good examples** + +- `User`: Manages user profile, preferences, and authentication +- `Document`: Handles document content, metadata, and versioning +- `ChatRoom`: Manages participants and message history + +**Bad examples** + +- `Application`: Too broad, handles everything +- `DocumentWordCount`: Too granular, should be part of Document actor + +## Coordinator & Data Actors + +Actors scale by splitting state into isolated entities. However, it's common to need to track and coordinate actors in a central place. This is where coordinator actors come in. + +**Data actors** handle the main logic in your application. Examples: chat rooms, user sessions, game lobbies. + +**Coordinator actors** track other actors. Think of them as an index of data actors. Examples: a list of chat rooms, a list of active users, a list of game lobbies. + +**Example: Chat Room Coordinator** + +### Actor + +### Client + +## Sharding + +Sharding splits a single actor's workload across multiple actors based on a key. Use this when one actor can't handle all the load or data for an entity. + +**How it works:** +- Partition data using a shard key (user ID, region, time bucket, or random) +- Requests are routed to shards based on the key +- Shards operate independently without coordination + +**Example: Sharding by Time** + +### Actor + +### Client + +**Example: Random Sharding** + +### Actor + +### Client + +Choose shard keys that distribute load evenly. Note that cross-shard queries require coordination. + +## Fan-In & Fan-Out + +Fan-in and fan-out are patterns for distributing work and aggregating results. + +**Fan-Out**: One actor spawns work across multiple actors. Use for parallel processing or broadcasting updates. + +**Fan-In**: Multiple actors send results to one aggregator. Use for collecting results or reducing data. + +**Example: Map-Reduce** + +### Actor + +### Client + +## Integrating With External Databases & APIs + +Actors can integrate with external resources like databases or external APIs. + +### Loading State + +Load external data during actor initialization using `createVars`. This keeps your actor's persisted state clean while caching expensive lookups. + +Use this when: + +- Fetching user profiles, configs, or permissions from a database +- Loading data that changes externally and shouldn't be persisted +- Caching expensive API calls or computations + +**Example: Loading User Profile** + +### Actor + +### Client + +### Syncing State Changes + +Use `onStateChange` to automatically sync actor state changes to external resources. This hook runs after state changes are flushed, which is coalesced to once per event loop tick rather than once per individual field mutation. + +Use this when: + +- You need to mirror actor state in an external database +- Triggering external side effects when state changes +- Keeping external systems in sync with actor state + +**Example: Syncing to Database** + +### Actor + +### Client + +`onStateChange` is called once per flush with the final coalesced state, ensuring external resources stay in sync. In the `updateEmail` example above, the two synchronous assignments produce a single `onStateChange` call. + +Do not mutate `c.state` inside `onStateChange`; re-entrant state mutation is rejected. + +## Anti-Patterns + +### "God" Actor + +Avoid creating a single actor that handles everything. This defeats the purpose of the actor model and creates a bottleneck. + +**Problem:** +```ts +import { actor } from "rivetkit"; + +// Bad: one actor doing everything +const app = actor({ + state: { users: {}, orders: {}, inventory: {}, analytics: {} }, + actions: { + createUser: (c, user) => { /* ... */ }, + processOrder: (c, order) => { /* ... */ }, + updateInventory: (c, item) => { /* ... */ }, + trackEvent: (c, event) => { /* ... */ }, + }, +}); +``` + +**Solution:** Split into focused actors per entity (User, Order, Inventory, Analytics). + +### Actor-Per-Request + +Actors are designed to maintain state across multiple requests. Creating a new actor for each request wastes resources and loses the benefits of persistent state. + +**Problem:** + +**Solution:** Use actors for entities that persist (users, sessions, documents), not for one-off operations. For stateless request handling, use regular functions. + +## API Reference + +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for pattern examples +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - Context usage patterns +- [`ActionContext`](/typedoc/interfaces/rivetkit.mod.ActionContext.html) - Action patterns + +_Source doc path: /docs/actors/design-patterns_ diff --git a/.agents/skills/chat-room/reference/actors/destroy.md b/.agents/skills/chat-room/reference/actors/destroy.md new file mode 100644 index 0000000..87e1b76 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/destroy.md @@ -0,0 +1,71 @@ +# Destroying Actors + +> Source: `src/content/docs/actors/destroy.mdx` +> Canonical URL: https://rivet.dev/docs/actors/destroy +> Description: Actors can be permanently destroyed. Common use cases include: + +--- +- User account deletion +- Ending a user session +- Closing a room or game +- Cleaning up temporary resources +- GDPR/compliance data removal + +Actors sleep when idle, so destruction is only needed to permanently remove data — not to save compute. + +## Destroying An Actor + +### Destroy via Action + +To destroy an actor, use `c.destroy()` like this: + +### Destroy via HTTP + +Send a DELETE request to destroy an actor. This requires a token for authentication: + +- **Rivet Cloud**: Use the service key (`sk_*`) from your `RIVET_ENDPOINT` URL. Find this in the dashboard under **Settings > Advanced > Backend Configuration** (e.g. the `sk_...` portion of `https://default:sk_abc123@api.rivet.dev`). +- **Self-hosted**: Use an admin token. + +```typescript +const actorId = "your-actor-id"; +const namespace = "default"; +const token = "your-token"; + +await fetch(`https://api.rivet.dev/actors/${actorId}?namespace=${namespace}`, { + method: "DELETE", + headers: { + Authorization: `Bearer ${token}`, + }, +}); +``` + +```bash +curl -X DELETE "https://api.rivet.dev/actors/{actorId}?namespace={namespace}" \ + -H "Authorization: Bearer {token}" +``` + +To find the actor ID, you can list actors first: + +```bash +curl "https://api.rivet.dev/actors?namespace={namespace}" \ + -H "Authorization: Bearer {token}" +``` + +### Destroy via Dashboard + +To destroy an actor via the dashboard, navigate to the actor and press the red "X" in the top right. + +## Lifecycle Hook + +Once destroyed, the `onDestroy` hook will be called. This can be used to clean up resources related to the actor. For example: + +## Accessing Actor After Destroy + +Once an actor is destroyed, any subsequent requests to it will fail with an `actor.not_found` error (`{ group: "actor", code: "not_found" }`). The actor's state is permanently deleted. + +## API Reference + +- [`ActorHandle`](/typedoc/types/rivetkit.client_mod.ActorHandle.html) - Has destroy methods +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - Context during destruction + +_Source doc path: /docs/actors/destroy_ diff --git a/.agents/skills/chat-room/reference/actors/errors.md b/.agents/skills/chat-room/reference/actors/errors.md new file mode 100644 index 0000000..af24c4c --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/errors.md @@ -0,0 +1,81 @@ +# Errors + +> Source: `src/content/docs/actors/errors.mdx` +> Canonical URL: https://rivet.dev/docs/actors/errors +> Description: Rivet provides robust error handling with security built in by default. Errors are handled differently based on whether they should be exposed to clients or kept private. + +--- +There are two types of errors: + +- **UserError**: Thrown from actors and safely returned to clients with full details +- **Internal errors**: All other errors that are converted to a generic error message for security + +## Throwing and Catching Errors + +`UserError` lets you throw custom errors that will be safely returned to the client. + +Throw a `UserError` with just a message: + +### Actor + +### Client (Connection) + +### Client (Stateless) + +## Error Codes + +Use error codes for explicit error matching in try-catch blocks: + +### Actor + +### Client (Connection) + +### Client (Stateless) + +## Errors With Metadata + +Include metadata to provide additional context for rich error handling: + +### Actor + +### Client (Connection) + +### Client (Stateless) + +## Internal Errors + +All errors that are not UserError instances are automatically converted to a generic "internal error" response. This prevents accidentally leaking sensitive information like stack traces, database details, or internal system information. + +### Actor + +### Client (Connection) + +### Client (Stateless) + +### Server-Side Logging + +**All internal errors are logged server-side with full details.** When an internal error occurs, the complete error message, stack trace, and context are written to your server logs. This is where you should look first when debugging internal errors in production. + +The client receives only a generic "Internal error" message for security, but you can find the full error details in your server logs including: + +- Complete error message +- Stack trace +- Request context (actor ID, action name, connection ID, etc.) +- Timestamp + +**Always check your server logs to see the actual error details when debugging internal errors.** + +### Exposing Errors to Clients (Development Only) + +**Warning:** Only enable error exposure in development environments. In production, this will leak sensitive internal details to clients. + +For faster debugging during development, you can expose internal error details to clients by setting `RIVET_EXPOSE_ERRORS=1`. + +With error exposure enabled, clients will see the full error message instead of the generic "Internal error" response: + +## API Reference + +- [`UserError`](/typedoc/classes/rivetkit.actor_errors.UserError.html) - User-facing error class +- [`ActorError`](/typedoc/classes/rivetkit.client_mod.ActorError.html) - Errors received by the client + +_Source doc path: /docs/actors/errors_ diff --git a/.agents/skills/chat-room/reference/actors/events.md b/.agents/skills/chat-room/reference/actors/events.md new file mode 100644 index 0000000..ec4a7d5 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/events.md @@ -0,0 +1,145 @@ +# Realtime + +> Source: `src/content/docs/actors/events.mdx` +> Canonical URL: https://rivet.dev/docs/actors/events +> Description: Events enable realtime communication from actors to clients. While clients use actions to send data to actors, events allow actors to push updates to connected clients instantly. + +--- +Events can be sent to clients connected using `.connect()`. They have no effect on [low-level WebSocket connections](/docs/actors/websocket-handler). + +For worked realtime patterns, see the cookbook: [Live Cursors and Presence](/cookbook/live-cursors/) and [Chat Room](/cookbook/chat-room/). + +## Publishing Events from Actors + +### Broadcasting to All Clients + +Define event names and payload types with `events` and `event()`, then use `c.broadcast(eventName, ...args)` to send events to all connected clients: + +### Sending to Specific Connections + +Send events to individual connections using `conn.send(eventName, ...args)`: + +Send events to all connections except the sender: + +## Subscribing to Events from Clients + +Clients must establish a connection to receive events from actors. Use `.connect()` to create a persistent connection, then listen for events. + +### Basic Event Subscription + +Use `connection.on(eventName, callback)` to listen for events: + +```tsx React @nocheck +import { useState } from "react"; +import { useActor } from "./rivetkit"; + +function ChatRoom() { + const [messages, setMessages] = useState>([]); + + const chatRoom = useActor({ + name: "chatRoom", + key: ["general"] + }); + + // Listen for events + chatRoom.useEvent("messageReceived", (message) => { + setMessages(prev => [...prev, message]); + }); + + // ...rest of component... +} +``` + +### One-time Event Listeners + +Use `connection.once(eventName, callback)` for events that should only trigger once: + +```tsx React @nocheck +import { useState, useEffect } from "react"; +import { useActor } from "./rivetkit"; + +function GameLobby() { + const [gameStarted, setGameStarted] = useState(false); + + const gameRoom = useActor({ + name: "gameRoom", + key: ["room-456"], + params: { + playerId: "player-789", + role: "player" + } + }); + + // Listen for game start (only once) + useEffect(() => { + if (!gameRoom.connection) return; + + const handleGameStart = () => { + console.log('Game has started!'); + setGameStarted(true); + }; + + gameRoom.connection.once('gameStarted', handleGameStart); + }, [gameRoom.connection]); + + // ...rest of component... +} +``` + +### Removing Event Listeners + +Use the callback returned from `.on()` to remove event listeners: + +```tsx React @nocheck +import { useState, useEffect } from "react"; +import { useActor } from "./rivetkit"; + +function ConditionalListener() { + const [isListening, setIsListening] = useState(false); + const [messages, setMessages] = useState([]); + + const chatRoom = useActor({ + name: "chatRoom", + key: ["general"] + }); + + useEffect(() => { + if (!chatRoom.connection || !isListening) return; + + // Add listener + const unsubscribe = chatRoom.connection.on('messageReceived', (message) => { + setMessages(prev => [...prev, message.text]); + }); + + // Cleanup - remove listener when component unmounts or listening stops + return () => { + unsubscribe(); + }; + }, [chatRoom.connection, isListening]); + + // ...rest of component... +} +``` + +## Debugging + +- `GET /inspector/connections` shows active connections and connection metadata. +- Use this to confirm clients are connected before expecting broadcasts. +- `GET /inspector/summary` provides connections, RPCs, and queue size in one response. +- In non-dev mode, inspector endpoints require authorization. + +## More About Connections + +For more details on actor connections, including connection lifecycle, authentication, and advanced connection patterns, see the [Connections documentation](/docs/actors/connections). + +## API Reference + +- [`RivetEvent`](/typedoc/interfaces/rivetkit.mod.RivetEvent.html) - Base event interface +- [`RivetMessageEvent`](/typedoc/interfaces/rivetkit.mod.RivetMessageEvent.html) - Message event type +- [`RivetCloseEvent`](/typedoc/interfaces/rivetkit.mod.RivetCloseEvent.html) - Close event type +- [`UniversalEvent`](/typedoc/interfaces/rivetkit.mod.UniversalEvent.html) - Universal event type +- [`UniversalMessageEvent`](/typedoc/interfaces/rivetkit.mod.UniversalMessageEvent.html) - Universal message event +- [`UniversalErrorEvent`](/typedoc/interfaces/rivetkit.mod.UniversalErrorEvent.html) - Universal error event +- [`EventUnsubscribe`](/typedoc/types/rivetkit.client_mod.EventUnsubscribe.html) - Unsubscribe function type + +_Source doc path: /docs/actors/events_ diff --git a/.agents/skills/chat-room/reference/actors/fetch-and-websocket-handler.md b/.agents/skills/chat-room/reference/actors/fetch-and-websocket-handler.md new file mode 100644 index 0000000..b8b0509 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/fetch-and-websocket-handler.md @@ -0,0 +1,10 @@ +# Fetch and WebSocket Handler + +> Source: `src/content/docs/actors/fetch-and-websocket-handler.mdx` +> Canonical URL: https://rivet.dev/docs/actors/fetch-and-websocket-handler +> Description: These docs have moved to [Low-Level WebSocket Handler](/docs/actors/websocket-handler) and [Low-Level Request Handler](/docs/actors/request-handler). + +--- + + +_Source doc path: /docs/actors/fetch-and-websocket-handler_ diff --git a/.agents/skills/chat-room/reference/actors/helper-types.md b/.agents/skills/chat-room/reference/actors/helper-types.md new file mode 100644 index 0000000..55555c7 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/helper-types.md @@ -0,0 +1,10 @@ +# Helper Types + +> Source: `src/content/docs/actors/helper-types.mdx` +> Canonical URL: https://rivet.dev/docs/actors/helper-types +> Description: This page has moved to [Types](/docs/actors/types). + +--- + + +_Source doc path: /docs/actors/helper-types_ diff --git a/.agents/skills/chat-room/reference/actors/http-api.md b/.agents/skills/chat-room/reference/actors/http-api.md new file mode 100644 index 0000000..1d8d5be --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/http-api.md @@ -0,0 +1,10 @@ +# Vanilla HTTP API + +> Source: `src/content/docs/actors/http-api.mdx` +> Canonical URL: https://rivet.dev/docs/actors/http-api +> Description: Use the low-level HTTP handler to send and receive requests from actors. + +--- +TODO + +_Source doc path: /docs/actors/http-api_ diff --git a/.agents/skills/chat-room/reference/actors/input.md b/.agents/skills/chat-room/reference/actors/input.md new file mode 100644 index 0000000..c5c5dde --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/input.md @@ -0,0 +1,51 @@ +# Input Parameters + +> Source: `src/content/docs/actors/input.mdx` +> Canonical URL: https://rivet.dev/docs/actors/input +> Description: Pass initialization data to actors when creating instances + +--- +Actors can receive input parameters when created, allowing for flexible initialization and configuration. Input is passed during actor creation and is available in lifecycle hooks. + +## Passing Input to Actors + +Input is provided when creating actor instances using the `input` property: + +## Accessing Input in Lifecycle Hooks + +Input is available as the second argument to the `createState` and `onCreate` lifecycle hooks: + +## Input Validation + +You can validate input parameters in the `createState` or `onCreate` hooks: + +## Input vs Connection Parameters + +Input parameters are different from connection parameters: + +- **Input**: + - Passed when creating the actor instance + - Use for actor-wide configuration + - Available in lifecycle hooks +- **Connection parameters**: + - Passed when connecting to an existing actor + - Used for connection-specific configuration + - Available in connection hooks + +## Input Best Practices + +### Use Type Safety + +Define input types to ensure type safety: + +### Store Input in State + +Input is only available in `createState` and `onCreate` lifecycle hooks. If you need to access input data later (in actions, timers, or other hooks), store it in the actor's state during creation. This is the recommended pattern because input shapes can evolve over time, and persisting input in state ensures you always have access to the values the actor was created with: + +## API Reference + +- [`CreateOptions`](/typedoc/interfaces/rivetkit.client_mod.CreateOptions.html) - Options for creating actors +- [`CreateRequest`](/typedoc/types/rivetkit.client_mod.CreateRequest.html) - Request type for creation +- [`ActorDefinition`](/typedoc/classes/rivetkit.mod.ActorDefinition.html) - Actor definition returned by `actor()` + +_Source doc path: /docs/actors/input_ diff --git a/.agents/skills/chat-room/reference/actors/inspector-tabs.md b/.agents/skills/chat-room/reference/actors/inspector-tabs.md new file mode 100644 index 0000000..34de206 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/inspector-tabs.md @@ -0,0 +1,251 @@ +# Custom Inspector Tabs + +> Source: `src/content/docs/actors/inspector-tabs.mdx` +> Canonical URL: https://rivet.dev/docs/actors/inspector-tabs +> Description: Ship your own UI tabs alongside a Rivet Actor — embedded directly in the dashboard inspector. + +--- +Custom inspector tabs let you embed your own UI directly in the Rivet +dashboard, next to the built-in tabs. Declare a tab on your actor, point +it at a folder of static files, and the dashboard picks it up +automatically. + +Common uses: + +- Domain-specific debugging panels (queue depth, connection maps, log + filters). +- Operational tools (admin buttons, drain controls, snapshot uploaders). +- Any author-defined view that ships with your actor. + +A runnable example lives at +[`examples/inspector-tabs`](https://github.com/rivet-dev/rivet/tree/main/examples/inspector-tabs). + +## Quickstart + +Declare a tab on your actor: + +Drop an `index.html` in the `source` directory: + +```html + + + + + + + +

Counter: …

+ + + +``` + +Open the dashboard and the "Counter" tab appears alongside the built-ins. + +## Configuration + +Each entry in `inspector.tabs[]` is either a **custom tab** or a +**hide modifier** for a built-in. + +### Custom tab + +```ts @nocheck +{ + id: string, // URL-safe id: /^[A-Za-z0-9_-]+$/ + label: string, // Shown in the tab strip + source: string, // Directory of static assets + icon?: string, // Optional icon id +} +``` + +- **`id`** — used as the URL segment and tab-strip key. Cannot collide + with a built-in id (`workflow`, `database`, `state`, `queue`, + `connections`, `console`). +- **`source`** — directory of static files. The bytes you put there are + the bytes the browser sees. Point it at a Vite/webpack `dist/` and + any framework works (React, Vue, Svelte, vanilla — all fine). +- **`icon`** — one of `workflow`, `database`, `state`, `queue`, `plug`, + `terminal`, `tag`, `logs`. Anything else falls back to a neutral icon. + +### Hide a built-in tab + +```ts @nocheck +{ + id: "workflow" | "database" | "state" | "queue" | "connections" | "console", + hidden: true, +} +``` + +Use this to clean up the strip when the actor doesn't use a given +subsystem — e.g. a counter actor with no queues: + +```ts +inspector: { tabs: [{ id: "queue", hidden: true }] } +``` + +Misconfigurations (missing directory, duplicate id, invalid characters, +empty label) throw at registry construction, so problems show up +immediately. + +## Talking to the dashboard + +The tab loads in an iframe and communicates with the dashboard via +`postMessage`. The contract is small. + +### From the dashboard + +The dashboard sends an `init` message on load and again whenever the +inspector token rotates. Always overwrite the cached token when it +arrives. + +```ts @nocheck +{ + type: "init", + v: 1, + actorId: string, + authToken: string, // Per-actor inspector bearer token + theme?: "light" | "dark", + activeTab?: string, // For multi-view tabs +} +``` + +Multi-view tabs can read the optional `activeTab` field on `init` to +seed their initial sub-view. The dashboard does not send a separate +message when the user switches custom tabs — it navigates the iframe +`src` instead, so the tab reloads and receives a fresh `init`. + +### From the tab + +Send `ready` once your message listener is registered: + +```ts @nocheck +{ type: "ready", v: 1 } +``` + +If a fetch returns 401, the token has rotated. Ask the dashboard for a +fresh one and wait for the next `init` — don't retry with the stale +token: + +```ts @nocheck +{ type: "token-refresh-needed", v: 1 } +``` + +### Security check + +Always reject messages whose `event.origin` doesn't match the +`?shellOrigin=` URL parameter. Without this check, any page that frames +your tab could forge an `init` and feed you a fake token. + +### TypeScript types + +If you build the tab with TypeScript, the message and response types +are exported as types-only: + +## Reading state and calling actions + +The tab can hit any inspector endpoint with the supplied bearer token. +Use relative paths so the tab doesn't need to know the engine origin or +actor id: + +```js +fetch("../../state", { headers: { Authorization: `Bearer ${token}` } }); +fetch("../../action/increment", { method: "POST", headers: { ... }, body: ... }); +fetch("../../rpcs", { headers: { Authorization: `Bearer ${token}` } }); +fetch("../../connections", { headers: { Authorization: `Bearer ${token}` } }); +fetch("../../queue", { headers: { Authorization: `Bearer ${token}` } }); +``` + +The action body shape is `{ args: [...] }` — the array is passed as +positional arguments to the action. + +Full endpoint reference: +[Debugging → Inspector Endpoints](/docs/actors/debugging#inspector-endpoints). + +For high-frequency UIs, prefer the inspector WebSocket +(`/inspector/connect`) over polling. + +## Styling + +A shared stylesheet matching the dashboard's design tokens is served at +`../../tab.css`: + +```html + +``` + +It defines `--rivet-*` tokens for colors, spacing, radius, and +typography, plus sensible defaults so a bare tab looks at home without +custom CSS: + +```css +.my-card { + background: var(--rivet-card); + color: var(--rivet-foreground); + border: 1px solid var(--rivet-border); + border-radius: var(--rivet-radius-md); + padding: var(--rivet-space-4); +} +``` + +Toggle dark mode by adding the `dark` class to `` — the dashboard +sends the active theme in the `init` message. + +Color tokens come in both pre-wrapped (`--rivet-card`) and raw HSL +(`--rivet-card-raw`) forms, so you can compose with alpha: + +```css +.overlay { background: hsl(var(--rivet-background-raw) / 0.6); } +``` + +You're free to skip the stylesheet entirely and bring your own. + +## Security + +The tab runs in an iframe at the engine origin and can call any +inspector endpoint with the supplied token. Treat the bundle like any +author code that ships with your actor: + +- **Don't inline secrets.** The bundle is fetchable by anyone who can + reach the actor. +- **Always validate `event.origin`.** Reject inbound messages from + anywhere other than the dashboard origin. +- **Never retry silently on 401.** Post `token-refresh-needed` and wait + for a fresh `init`. + +## See also + +- [Debugging](/docs/actors/debugging) — full inspector HTTP API +- [Actions](/docs/actors/actions) — actions your tab can invoke +- [State](/docs/actors/state) — state your tab can read +- [`examples/inspector-tabs`](https://github.com/rivet-dev/rivet/tree/main/examples/inspector-tabs) — runnable example + +_Source doc path: /docs/actors/inspector-tabs_ diff --git a/.agents/skills/chat-room/reference/actors/keys.md b/.agents/skills/chat-room/reference/actors/keys.md new file mode 100644 index 0000000..b8f1614 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/keys.md @@ -0,0 +1,51 @@ +# Actor Keys + +> Source: `src/content/docs/actors/keys.mdx` +> Canonical URL: https://rivet.dev/docs/actors/keys +> Description: Actor keys uniquely identify actor instances within each actor type. Keys are used for addressing which specific actor to communicate with. + +--- +## Key Format + +Actor keys can be either a string or an array of strings: + +### Compound Keys & User Data + +Array keys are useful when you need compound keys with user-provided data. Using arrays makes adding user data safe by preventing key injection attacks: + +This allows you to create hierarchical addressing schemes and organize actors by multiple dimensions. + +Don't build keys using string interpolation like `"foo:${userId}:bar"` when `userId` contains user data. If a user provides a value containing the delimiter (`:` in this example), it can break your key structure and cause key injection attacks. + +### Omitting Keys + +You can create actors without specifying a key in situations where there is a singleton actor (i.e. only one actor of a given type). For example: + +This pattern should be avoided, since a singleton actor usually means you have a single actor serving all traffic & your application will not scale. See [scaling documentation](/docs/actors/scaling) for more information. + +### Key Uniqueness + +Keys are unique within each actor name. Different actor types can use the same key: + +## Accessing Keys in Metadata + +Access the actor's key within the actor using the [metadata](/docs/actors/metadata) API: + +## Configuration Examples + +### Simple Configuration with Keys + +Use keys to provide basic actor configuration: + +### Complex Configuration with Input + +For more complex configuration, use [input parameters](/docs/actors/input): + +## API Reference + +- [`ActorKey`](/typedoc/types/rivetkit.mod.ActorKey.html) - Key type for actors +- [`ActorQuery`](/typedoc/types/rivetkit.mod.ActorQuery.html) - Query type using keys +- [`GetOptions`](/typedoc/interfaces/rivetkit.client_mod.GetOptions.html) - Options for getting by key +- [`QueryOptions`](/typedoc/interfaces/rivetkit.client_mod.QueryOptions.html) - Options for querying + +_Source doc path: /docs/actors/keys_ diff --git a/.agents/skills/chat-room/reference/actors/kv.md b/.agents/skills/chat-room/reference/actors/kv.md new file mode 100644 index 0000000..384769b --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/kv.md @@ -0,0 +1,44 @@ +# Low-Level KV Storage + +> Source: `src/content/docs/actors/kv.mdx` +> Canonical URL: https://rivet.dev/docs/actors/kv +> Description: Use the built-in key-value store on ActorContext for durable string and binary data alongside actor state. + +--- +KV is deprecated. It is a low-level escape hatch kept for backward compatibility. For new actors, prefer [in-memory state](/docs/actors/state) for small serializable values or [SQLite](/docs/actors/sqlite) for larger or queryable data. + +Every Rivet Actor includes a lightweight key-value store on `c.kv`. It is useful for dynamic keys, blobs, or data that does not fit well in structured state. + +If your data has a known schema, prefer [state](/docs/actors/state). KV is best for flexible or user-defined keys. + +## Basic Usage + +Keys and values default to `text`, so you can use strings without extra options. + +## Value Types + +You can store binary values by passing `Uint8Array` or `ArrayBuffer`. Use `type` on both reads and writes to get the right value type: `binary` for `Uint8Array` and `arrayBuffer` for `ArrayBuffer`. + +TypeScript returns a concrete type based on the option you pass in: + +## Key Types + +Keys accept either `string` or `Uint8Array`. String keys are encoded as UTF-8 by default. + +When listing by prefix, you can control how keys are decoded with `keyType`. Returned keys have the prefix removed. + +If you use binary keys, set `keyType: "binary"` so the returned keys stay as `Uint8Array`. + +## Range Operations + +Use `listRange(start, end)` to read an arbitrary half-open range `[start, end)`. Use `deleteRange(start, end)` to clear that same range efficiently. + +## Batch Operations + +KV supports batch operations for efficiency. `batchPut` and `batchGet` work on raw `Uint8Array` keys and values, so encode strings before passing them in. + +## API Reference + +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - `c.kv` is available on the context + +_Source doc path: /docs/actors/kv_ diff --git a/.agents/skills/chat-room/reference/actors/lifecycle.md b/.agents/skills/chat-room/reference/actors/lifecycle.md new file mode 100644 index 0000000..89955bb --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/lifecycle.md @@ -0,0 +1,388 @@ +# Lifecycle + +> Source: `src/content/docs/actors/lifecycle.mdx` +> Canonical URL: https://rivet.dev/docs/actors/lifecycle +> Description: Learn about actor lifecycle hooks for initialization, state management, and cleanup. + +--- +# Lifecycle + +Actors follow a well-defined lifecycle with hooks at each stage. Understanding these hooks is essential for proper initialization, state management, and cleanup. + +## Lifecycle + +Actors transition through several states during their lifetime. Each transition triggers specific hooks that let you initialize resources, manage connections, and clean up state. + +``` +Loading ──Start──▶ Ready ──spawn driver──▶ Started + │ + ┌────────────────────────────────────────┤ + │ │ + │ idle timer + can_sleep │ Destroy command + ▼ ▼ + SleepGrace ─── grace window closes ──▶ Destroying + │ │ + ▼ │ + SleepFinalize ──── stop sequence ───────────┤ + ▼ + Terminated +``` + +**On Create** (runs once per actor) + +1. `onMigrate` +2. `createState` +3. `onCreate` +4. `createVars` +5. `onWake` +6. `run` (background, does not block) + +**On Destroy** + +1. `onDestroy` + +**On Wake** (after sleep, restart, or crash) + +1. `onMigrate` +2. `createVars` +3. `onWake` +4. `run` (background, does not block) + +**On Sleep** (after idle period) + +1. Wait for `run` to complete (with timeout) +2. `onSleep` + +**On Connect** (per client) + +1. `onBeforeConnect` +2. `createConnState` +3. `onConnect` + +**On Disconnect** (per client) + +1. `onDisconnect` + +**On Inbound Action Invoke** (per action call) + +1. Action handler executes + +**On Inbound Queue Publish** (per `handle.send(...)`) + +1. `queues..canPublish` (if defined) +2. Queue message is enqueued + +**On Event Subscription Request** (per subscribe request) + +1. `events..canSubscribe` (if defined) +2. Subscription is applied + +## Lifecycle Hooks + +Actor lifecycle hooks are defined as functions in the actor configuration. + +### `state` + +The `state` constant defines the initial state of the actor. See [state documentation](/docs/actors/state) for more information. + +### `onMigrate` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onMigrate` hook runs on every actor start, before `createState`, `onCreate`, `createVars`, and `onWake`. Can be async. It runs early so that database migrations are applied before any other lifecycle hook accesses the database. The second parameter is `true` when the actor is being created for the first time. + +### `createState` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `createState` function dynamically initializes state based on input. Called only once when the actor is first created. Can be async. See [state documentation](/docs/actors/state) for more information. + +### `vars` + +The `vars` constant defines ephemeral variables for the actor. These variables are not persisted and are useful for storing runtime-only data. The value for `vars` must be clonable via `structuredClone`. See [ephemeral variables documentation](/docs/actors/state#ephemeral-variables) for more information. + +### `createVars` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `createVars` function dynamically initializes ephemeral variables. Can be async. Use this when you need to initialize values at runtime. See [ephemeral variables documentation](/docs/actors/state#ephemeral-variables) for more information. + +### `onCreate` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onCreate` hook is called when the actor is first created. Can be async. Use this hook for initialization logic that doesn't affect the initial state. + +### `onDestroy` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onDestroy` hook is called when the actor is being permanently destroyed. Can be async. Use this for final cleanup operations like closing external connections, releasing resources, or performing any last-minute state persistence. + +The actor is still fully functional when `onDestroy` runs. You can access the database, broadcast events, call `waitUntil`, send queue messages, and use `schedule.after`. State mutations made during `onDestroy` are persisted before the actor is torn down. + +### `onWake` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +This hook is called any time the actor is started (e.g. after restarting, upgrading code, or crashing). Can be async. + +This is called after the actor has been initialized but before any connections are accepted. + +Use this hook to set up any resources or start any background tasks, such as `setInterval`. + +### `onSleep` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +This hook is called when the actor is going to sleep. Can be async. Use this to clean up resources, close connections, or perform any shutdown operations. + +The actor is still fully functional when `onSleep` runs. You can access the database, broadcast events, call `waitUntil`, send queue messages, and use `schedule.after`. State mutations made during `onSleep` are persisted before the actor finishes sleeping. + +This hook may not always be called in situations like crashes or forced terminations. Don't rely on it for critical cleanup operations. + +Not supported on Cloudflare Workers. + +### `run` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `run` hook is called after the actor starts and runs in the background without blocking actor startup. This is ideal for long-running background tasks like: + +- Reading from message queues in a loop +- Tick loops for periodic work +- Custom workflow logic +- Background processing + +The handler exposes `c.aborted` for loop checks and `c.abortSignal` for canceling operations when the actor is stopping. You should always check or listen for shutdown to exit gracefully. + +**Important behavior:** +- The actor may go to sleep at any time during the `run` handler. Wrap work that must keep the actor awake with `c.keepAwake(promise)` to block idle sleep until the promise settles. +- If the `run` handler exits (returns), the actor follows its normal idle sleep timeout once it becomes idle +- If the `run` handler throws an error, the actor logs the error and then follows its normal idle sleep timeout once it becomes idle +- On shutdown, `c.abortSignal` fires so the `run` handler can exit within the graceful shutdown window. + +Finite `run` handlers leave the actor alive after they finish. If you want a one shot task to clean itself up when it is done, call `c.destroy()` before returning. + +### `onStateChange` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Called whenever the actor's state changes. Cannot be async. This is often used to broadcast state updates. + +Do not mutate `c.state` inside `onStateChange`; re-entrant state mutation is rejected. + +### `createConnState` and `connState` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +There are two ways to define the initial state for connections: +1. `connState`: Define a constant object that will be used as the initial state for all connections +2. `createConnState`: A function that dynamically creates initial connection state based on connection parameters. Can be async. + +### `onBeforeConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.BeforeConnectContext.html) + +The `onBeforeConnect` hook is called whenever a new client connects to the actor. Can be async. Clients can pass parameters when connecting, accessible via `params`. This hook is used for connection validation and can throw errors to reject connections. + +The `onBeforeConnect` hook does NOT return connection state - it's used solely for validation. + +Connections cannot interact with the actor until this method completes successfully. Throwing an error will abort the connection. This can be used for authentication - see [Authentication](/docs/actors/authentication) for details. + +### `onConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ConnectContext.html) + +Executed after the client has successfully connected. Can be async. Receives the connection object as a second parameter. + +Messages will not be processed for this actor until this hook succeeds. Errors thrown from this hook will cause the client to disconnect. + +### `canPublish` and `canSubscribe` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Use schema-level hooks to authorize queue publishes and event subscriptions. Both hooks can be async and must return booleans: + +- `queues..canPublish` runs before inbound queue publishes. +- `events..canSubscribe` runs before inbound event subscription requests. + +For actions, enforce authorization directly inside each action handler. + +Use deny-by-default rules for each hook and return `false` unless explicitly allowed. See [Access Control](/docs/actors/access-control) for full guidance. + +### `onDisconnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Called when a client disconnects from the actor. Can be async. Receives the connection object as a second parameter. Use this to clean up any connection-specific resources. + +### `onRequest` + +[API Reference](/typedoc/interfaces/rivetkit.mod.RequestContext.html) + +The `onRequest` hook handles HTTP requests sent to your actor at `/actors/{actorName}/http/*` endpoints. Can be async. It receives the request context and a standard `Request` object, and should return a `Response` object. + +See [Request Handler](/docs/actors/request-handler) for more details. + +### `onWebSocket` + +[API Reference](/typedoc/interfaces/rivetkit.mod.WebSocketContext.html) + +The `onWebSocket` hook handles WebSocket connections to your actor. Can be async. It receives the actor context and a `WebSocket` object. Use this to set up WebSocket event listeners and handle real-time communication. + +See [WebSocket Handler](/docs/actors/websocket-handler) for more details. + +### `onBeforeActionResponse` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onBeforeActionResponse` hook is called before sending an action response to the client. Can be async. Use this hook to modify or transform the output of an action before it's sent to the client. This is useful for formatting responses, adding metadata, or applying transformations to the output. + +## Sleeping + +Actors automatically sleep after a period of inactivity to free up resources. When a request arrives for a sleeping actor, it wakes up, restores its state, and handles the request. + +### When Actors Sleep + +#### Idle Timeout + +An actor is considered idle and eligible to sleep when **all** of the following are true: + +- No active HTTP requests +- No active connections (unless they are hibernatable WebSockets) +- No active `run` handler (unless it is waiting on a queue) +- No outstanding `c.keepAwake(promise)` promises +- No pending disconnect callbacks +- No async `onWebSocket` event handlers (eg `open`, `message`, `close`) still running + +Once the actor becomes idle, the sleep timer starts. After `sleepTimeout` (default 30 seconds) of continuous inactivity, the actor begins the sleep process. Any activity resets the timer. + +Outbound requests (e.g. `fetch` calls) do not count as activity and will not keep the actor awake. Wrap them with `c.waitUntil()` if they must complete before the actor sleeps. + +#### Upgrades & Eviction + +The platform may force an actor to migrate to a new machine during version upgrades or when a serverless request is about to timeout. The same [shutdown sequence](#shutdown-sequence) runs, then the actor is rescheduled on a new machine and wakes up with its persisted state. + +Use `onSleep`, `waitUntil`, or `keepAwake` to control the length of the grace period before the actor moves to another machine. + +### Manual Lifecycle Controls + +You can also trigger lifecycle transitions from the Rivet Cloud API. These endpoints are useful for operational workflows, debugging, and forcing an actor to move through the same sleep or reschedule path that the platform would normally trigger. + +```bash +curl -X POST \ + "https://cloud-api.rivet.dev/actors/$ACTOR_ID/sleep?namespace=$NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{}' +``` + +```bash +curl -X POST \ + "https://cloud-api.rivet.dev/actors/$ACTOR_ID/reschedule?namespace=$NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{}' +``` + +`/sleep` asks the actor to enter the normal sleep shutdown sequence. `/reschedule` asks the platform to allocate the actor again, which is useful after crashes or when you need to force a fresh placement. Both endpoints require the actor ID and namespace. + +### Skip Ready Wait + +The gateway normally holds requests until the actor is ready. The actor is not ready during startup (before `onWake` finishes) or during the sleep grace period (while `onSleep` and `waitUntil` are running). Probes and readiness checks can opt out with `skipReadyWait` to reach the actor's `onRequest` or `onWebSocket` handler in either window. + +See [Skip Ready Wait](/docs/clients/javascript#skip-ready-wait) on the JavaScript client page for usage. + +### Keeping the Actor Awake + +RivetKit gives you two primitives for holding the actor awake across background work. Both take a `Promise` and differ in how they interact with idle sleep and the grace period. + +| Method | Accepts | Blocks idle sleep | Blocks grace finalize | Use case | +| --- | --- | --- | --- | --- | +| `c.keepAwake(promise)` | `Promise` (returns same promise) | Yes | Yes | Critical work that must keep the actor running end to end (for example a turn in a game, an ongoing tool call). | +| `c.waitUntil(promise)` | `Promise` (returns void) | No | Yes | Best-effort finalization work that may complete during the grace window (for example analytics flushes, cleanup writes). | + +`c.keepAwake(promise)` is the preferred primitive for long-running work the actor should not sleep through. It holds a keep-awake counter until the promise settles, which blocks both idle sleep and the grace finalize step. The promise is returned unchanged, so you can `await` it if you need the value. + +`setPreventSleep(enabled)` is deprecated and now a no-op. Wrap the work you want to keep alive with `c.keepAwake(promise)` instead. + +### On Sleep Hook + +The [`onSleep`](#onsleep) hook runs during shutdown for cleanup like clearing intervals or closing connections. It is best-effort and will not run if the actor crashes. + +### Wait Before Sleep + +`c.waitUntil(promise)` registers a background promise that must resolve before the actor finishes sleeping. Use this to flush data or finish in-flight work during shutdown without blocking the main execution flow. + +The actor waits up to `sleepGracePeriod` for graceful sleep work during the [shutdown sequence](#shutdown-sequence). That single budget covers `onSleep`, `waitUntil`, `keepAwake`, async raw WebSocket handlers such as `message` and `close`. By default, this graceful sleep window is 15 seconds total. If the timeout is exceeded, the actor proceeds with sleep anyway. + +### Sleep Timeouts + +| Option | Default | Description | +|--------|---------|-------------| +| `sleepTimeout` | 30 seconds | Time of inactivity before the actor begins sleeping. | +| `sleepGracePeriod` | 15 seconds | Total graceful shutdown window for hooks, `waitUntil`, `keepAwake`, async raw WebSocket handlers, and disconnects. | + +Rivet enforces a hard limit of **30 minutes** for the entire stop process. These can be configured in the [options](#options). + +### WebSocket Hibernation + +WebSocket connections are preserved across sleep cycles by default and transparently migrated to the new actor instance. Client stays connected and sees no interruption. Actor migration is very fast, realtime workloads are not interrupted. + +### Shutdown Sequence + +When an actor sleeps or is destroyed, it enters the graceful shutdown window: + +1. `c.abortSignal` fires and `c.aborted` becomes `true`. New connections and dispatch are rejected. Alarm timeouts are cancelled. On sleep, scheduled events are persisted and will be re-armed when the actor wakes. +2. `onSleep` or `onDestroy` and `onDisconnect` for each closing connection run during the same window. User `waitUntil` promises and async raw WebSocket handlers are drained. Hibernatable WebSocket connections are preserved on sleep and closed on destroy. +3. Once graceful work has completed, state is saved and final cleanup runs. + +The entire window is bounded by `sleepGracePeriod` on both sleep and destroy. Defaults to 15 seconds. If the window is exceeded, the actor proceeds to state save anyway. + +#### Graceful shutdown window + +During steps 1 through 6, the actor is still fully functional. Database access, `broadcast`, `waitUntil`, `queue.send`, and `schedule.after` all work. State mutations are persisted at step 7. Actions invoked by pre-existing connections or lifecycle hooks continue to execute normally. + +New connections and raw WebSocket upgrades are rejected as soon as the shutdown sequence begins. New requests that arrive during shutdown are held until the actor wakes up again. The caller does not need to retry. + +If `schedule.after` is called during shutdown, the event is persisted so it survives the sleep/wake cycle, but no local timeout is scheduled. The event will fire after the actor wakes. + +In-flight actions are **not** waited on during shutdown. If an action must complete before the actor stops, wrap the critical work with `c.waitUntil()`. + +## Options + +The `options` object allows you to configure various timeouts and behaviors for your actor. + +| Option | Default | Description | +|--------|---------|-------------| +| `createVarsTimeout` | 5000ms | Timeout for `createVars` function | +| `createConnStateTimeout` | 5000ms | Timeout for `createConnState` function | +| `onConnectTimeout` | 5000ms | Timeout for `onConnect` hook | +| `sleepGracePeriod` | 15000ms | Total graceful shutdown window for both sleep and destroy | +| `stateSaveInterval` | 1000ms | Interval for persisting state | +| `actionTimeout` | 60000ms | Timeout for action execution | +| `connectionLivenessTimeout` | 2500ms | Timeout for connection liveness check | +| `connectionLivenessInterval` | 5000ms | Interval for connection liveness check | +| `sleepTimeout` | 30000ms | Time before actor sleeps due to inactivity | +| `canHibernateWebSocket` | false | Whether WebSockets can hibernate (experimental) | + +## Advanced + +### Actor Shutdown Abort Signal + +The `c.abortSignal` provides an `AbortSignal` that fires when the actor is stopping, and `c.aborted` is the shorthand boolean for loop checks. Use these to cancel ongoing operations when the actor sleeps or is destroyed. + +The abort signal fires at the very start of the [shutdown sequence](#shutdown-sequence), before `onSleep` or `onDestroy` runs. This means `c.aborted` is already `true` inside those lifecycle hooks. The signal fires early so that the `run` handler can exit promptly, but the actor remains fully functional throughout the graceful shutdown window. + +See [Canceling Long-Running Actions](/docs/actors/actions#canceling-long-running-actions) for manually canceling operations on-demand. + +### Using `ActorContext` Type Externally + +When extracting logic from lifecycle hooks or actions into external functions, you'll often need to define the type of the context parameter. Rivet provides helper types that make it easy to extract and pass these context types to external functions. + +See [Types](/docs/actors/types) for more details on using `ActorContextOf`. + +## Full Example + +_Source doc path: /docs/actors/lifecycle_ diff --git a/.agents/skills/chat-room/reference/actors/limits.md b/.agents/skills/chat-room/reference/actors/limits.md new file mode 100644 index 0000000..57d7194 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/limits.md @@ -0,0 +1,169 @@ +# Limits + +> Source: `src/content/docs/actors/limits.mdx` +> Canonical URL: https://rivet.dev/docs/actors/limits +> Description: Limits and constraints for Rivet Actors. + +--- +This page documents the limits for Rivet Actors. + +There are two types of limits: + +- **Soft Limit**: Application-level limit, configurable in RivetKit. These cannot exceed the hard limit. +- **Hard Limit**: Infrastructure-level limit that cannot be configured. + +Soft limits are configured in two places. Registry-level WebSocket message-size limits are passed to `setup`: + +Per-actor limits such as queue sizes and lifecycle timeouts are passed to `actor(...)` via `options`: + +## Limits + +### WebSocket + +These limits affect actions that use `.connect()` and [low-level WebSockets](/docs/actors/websocket-handler). + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max incoming message size | 64 KiB | 32 MiB | Maximum size of incoming WebSocket messages. Soft limit configurable via `maxIncomingMessageSize`; hard limit configurable in self-hosted engine config via `guard.websocket_max_message_size`. | +| Max outgoing message size | 1 MiB | 32 MiB | Maximum size of outgoing WebSocket messages. Soft limit configurable via `maxOutgoingMessageSize`; hard limit configurable in self-hosted engine config via `guard.websocket_max_message_size`. | +| Max WebSocket frame size | — | 32 MiB | Maximum size of a single WebSocket frame accepted by Rivet's transport edge. Configurable in self-hosted engine config via `guard.websocket_max_frame_size`. This is not configurable by browser clients and is not negotiated during the WebSocket handshake. | +| WebSocket open timeout | — | 15 seconds | Time allowed for WebSocket connection to be established, including `onBeforeConnect` and `createConnState` hooks. Connection is closed if exceeded. | +| Message ack timeout | — | 30 seconds | Time allowed for message acknowledgment before connection is closed. Only relevant in the case of a network issue and does not affect your application. | + +### Hibernating WebSocket + +Hibernating WebSockets allow actors to sleep while keeping client connections alive. All WebSocket limits above also apply to hibernating WebSockets. See [WebSocket Hibernation](/docs/actors/websocket-handler#web-socket-hibernation) for details. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max pending buffer size | — | 128 MiB | Total size of all buffered messages per connection while actor is sleeping. | +| Max pending message count | — | 65,535 | Maximum number of buffered messages per connection while actor is sleeping. | +| Hibernation timeout | — | 90 seconds | Maximum time an actor has to wake up before the client is disconnected. Only relevant if something is wrong with starting actors. | + +### HTTP + +These limits affect actions that do not use `.connect()` and [low-level HTTP requests](/docs/actors/request-handler). + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max request body size | — | 20 MiB | Maximum size of HTTP request bodies. | +| Max response body size | — | 20 MiB | Maximum size of HTTP response bodies. | +| Request timeout | 60 seconds | — | Maximum time for an `onRequest` handler to complete. Defaults to `actionTimeout`; configure with `actionTimeout`. | + +### Networking + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Connection ping timeout | — | 30 seconds | Connection is closed if a ping is not acknowledged within this time. Applies to both HTTP and WebSocket. Only relevant in the case of a network issue and does not affect your application. | + +### Queue + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max queue size | 1,000 messages | — | Maximum number of messages in the queue before new messages are rejected. Configurable via `maxQueueSize`. | +| Max queue message size | 64 KiB | 128 KiB (effective) | Maximum size of each individual queue message. Configurable via `maxQueueMessageSize`. Actual payload is slightly lower after queue serialization overhead. | + +### Actor KV Storage + +These limits apply to the low-level KV storage interface powering Rivet Actors. They likely do not affect your application, but are documented for completeness. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max key size | — | 2 KiB | Maximum size of a single key. | +| Max value size | — | 128 KiB | Maximum size of a single value. | +| Max keys per operation | — | 128 | Maximum number of keys in a single batch get/put/delete operation. Does not apply to range operations (`listRange`, `deleteRange`). | +| Max batch put payload size | — | 976 KiB | Maximum total size of all key-value pairs in a single batch put operation. | +| Max storage size per actor | — | 10 GiB | Maximum total KV storage size for a single actor. | +| List default limit | — | 16,384 | Default maximum number of keys returned by a list operation. | + +### Actor SQLite Storage + +These limits apply to the [SQLite database](/docs/actors/state#sqlite-database) available via `this.sql`. SQLite data is stored through the KV layer, so the storage limit is shared with KV storage. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max storage size per actor | — | 10 GiB | Maximum total storage size for a single actor. This limit is shared with KV storage. | +| Max dirty data per commit | — | 1,310,720 bytes | Maximum raw SQLite page data that can be written in a single commit. This is 320 dirty pages at 4 KiB per page. | +| Transaction deadline | 60 seconds | — | Safety backstop for `db.transaction()`. Configure per transaction with `{ timeout: milliseconds }`; there is no product-level maximum. | +| Transaction coordinator queue | — | 128 operations | Maximum admitted SQLite operations waiting behind an active coordinated transaction. Additional operations fail with `sqlite.transaction_queue_full`. | + +SQLite commit deltas are compressed and split into internal chunks before storage, but all chunks for one commit are published atomically. The commit limit is therefore based on raw dirty page bytes before compression, not the compressed delta size. + +Avoid `VACUUM` inside actor databases. It rewrites the database in one transaction and can exceed the dirty-page commit limit even when ordinary incremental writes fit. + +### Actor Runtime Socket + +The experimental [Actor Runtime Socket](/docs/actors/actor-runtime-socket) negotiates its active frame limit during the handshake. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Frame payload size | 32 MiB | — | Default maximum request or response payload. Self-hosted native runtimes can configure `RIVET_ACTOR_RUNTIME_SOCKET_MAX_FRAME_BYTES`; oversized responses return `ResponseTooLarge`. | + +### KV Preloading + +When an actor starts, the engine can pre-fetch KV data declared in the actor name metadata and deliver it alongside the start command. This removes round-trips to storage during actor startup. RivetKit emits the preload manifest from its own key layout and exposes per-actor overrides via `options`. Operators can still enforce a global cap in the [engine config](/docs/self-hosting/configuration) with `pegboard.preload_max_total_bytes`. In serverless mode, this data is serialized into the `/api/rivet/start` request body along with actor config and protocol metadata, so the accepted body size must be larger than the preload budget. RivetKit defaults `serverless.maxStartPayloadBytes` to 16 MiB to leave margin for the default 1 MiB preload budget and larger SQLite startup page preloads. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max total preload size | 1 MiB | — | Maximum total size of all preloaded KV data sent with the start command. Configurable via `pegboard.preload_max_total_bytes`. Setting to 0 disables all preloading. | +| Max workflow preload size | 128 KiB | — | Default maximum size of preloaded workflow data for RivetKit actors. Configurable per actor via `options.preloadMaxWorkflowBytes`. Setting to 0 disables workflow preloading for that actor. | +| Max connections preload size | 64 KiB | — | Default maximum size of preloaded connection data for RivetKit actors. Configurable per actor via `options.preloadMaxConnectionsBytes`. Setting to 0 disables connections preloading for that actor. | + +### Actor Input + +See [Actor Input](/docs/actors/input) for details. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max actor input size | — | 4 MiB | Maximum size of the input passed when creating an actor. | +| Max connection params size | — | 4 KiB | Maximum size of connection parameters passed when connecting to an actor. | +| Max actor key component size | — | 128 bytes | Maximum size of each component in an actor key array. | +| Max actor key total size | — | 1,024 bytes | Maximum total size of the serialized actor key string. | +| Max actor name length | — | 64 characters | Maximum length for actor and project identifiers. | + +### Rate Limiting + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Rate limit | — | 1200 requests/minute | Default rate limit per actor per IP address with a 1 minute time bucket. | +| Max in-flight requests | — | 32 | Default maximum concurrent requests to an actor per IP address. | + +### Timeouts + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Action timeout | 60 seconds | — | Timeout for RPC actions. Configurable via `actionTimeout`. | +| On request timeout | 60 seconds | — | Timeout for raw `onRequest` handlers. Defaults to `actionTimeout`; configure with `actionTimeout`. | +| On before connect timeout | 5 seconds | — | Timeout for the `onBeforeConnect` hook. Configurable via `onBeforeConnectTimeout`. | +| Create vars timeout | 5 seconds | — | Timeout for `createVars` hook. Configurable via `createVarsTimeout`. | +| Create conn state timeout | 5 seconds | — | Timeout for `createConnState` hook. Configurable via `createConnStateTimeout`. | +| On connect timeout | 5 seconds | — | Timeout for `onConnect` hook. Configurable via `onConnectTimeout`. | +| On migrate timeout | 30 seconds | — | Timeout for `onMigrate` hook. Configurable via `onMigrateTimeout`. | +| Sleep grace period | 15 seconds | — | Total graceful shutdown budget for both sleep and destroy. Covers `onSleep`/`onDestroy`, run handler shutdown, `waitUntil`, `keepAwake`, async raw WebSocket handlers, and connection cleanup. Configurable via `sleepGracePeriod`. | +| Sleep timeout | 30 seconds | — | Time of inactivity before actor hibernates. Configurable via `sleepTimeout`. | +| State save interval | 1 second | — | Interval between automatic state saves. Configurable via `stateSaveInterval`. | +| Connection liveness timeout | 2.5 seconds | — | Time a stateful connection can miss liveness checks before RivetKit treats it as unhealthy. Configurable via `connectionLivenessTimeout`. | +| Connection liveness interval | 5 seconds | — | Interval between stateful connection liveness checks. Configurable via `connectionLivenessInterval`. | + +### Serverless Shutdown + +These timeouts control how actors are shut down when a serverless request reaches its lifespan limit. See [Shutdown Sequence](/docs/general/runtime-modes#shutdown-sequence) for details. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Request lifespan | 3600 seconds (60 min) | — | Total lifespan of a serverless request before drain begins. Configurable via `requestLifespan` in [`configurePool`](/docs/general/registry-configuration). | +| Runner config drain grace period | — | 30 minutes | Time a serverless runner reserves for actors to stop gracefully. Configurable via `drainGracePeriod` in [`configurePool`](/docs/general/registry-configuration). | +| Engine serverless drain fallback | — | 10 seconds | Engine-level fallback used when no per-runner config applies. Configurable via [engine config](/docs/self-hosting/configuration) (`pegboard.serverless_drain_grace_period`). | + +### Actor Lifecycle + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Actor start threshold | — | 30 seconds | Maximum time for an actor to start before it is considered lost and rescheduled. | +| Actor stop threshold | — | 30 minutes | Maximum time for an actor to stop before it is considered lost. | + +## Increasing Limits + +These limits are sane defaults designed to protect your application from exploits and accidental runaway bugs. If you have a use case that requires different limits, [contact us](https://rivet.dev/contact) to discuss your requirements. + +_Source doc path: /docs/actors/limits_ diff --git a/.agents/skills/chat-room/reference/actors/metadata.md b/.agents/skills/chat-room/reference/actors/metadata.md new file mode 100644 index 0000000..d3dcc24 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/metadata.md @@ -0,0 +1,39 @@ +# Metadata + +> Source: `src/content/docs/actors/metadata.mdx` +> Canonical URL: https://rivet.dev/docs/actors/metadata +> Description: Metadata provides information about the currently running actor. + +--- +## Actor ID + +Get the unique instance ID of the actor: + +## Actor Name + +Get the actor type name: + +This is useful when you need to know which actor type is running, especially if you have generic utility functions that are shared between different actor implementations. + +## Actor Key + +Get the actor key used to identify this actor instance: + +The key is used to route requests to the correct actor instance and can include parameters passed when creating the actor. + +Learn more about using keys for actor addressing and configuration in the [keys documentation](/docs/actors/keys). + +## Region + +Region can be accessed from the context object via `c.region`. + +`c.region` is only supported on Rivet at the moment. + +## Example Usage + +## API Reference + +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining metadata +- [`CreateOptions`](/typedoc/interfaces/rivetkit.client_mod.CreateOptions.html) - Options for creating an actor, including `region` and `input` + +_Source doc path: /docs/actors/metadata_ diff --git a/.agents/skills/chat-room/reference/actors/queues.md b/.agents/skills/chat-room/reference/actors/queues.md new file mode 100644 index 0000000..8ebeb7b --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/queues.md @@ -0,0 +1,122 @@ +# Queues & Run Loops + +> Source: `src/content/docs/actors/queues.mdx` +> Canonical URL: https://rivet.dev/docs/actors/queues +> Description: Use actor-local durable queues for serial run loops and request/response workflows. + +--- +## What are queues? + +- **Realtime**: messages are delivered to a live actor as soon as possible. +- **Durable**: messages are persisted and survive actor sleep/restart. +- **Request/response**: clients can wait for a queue completion response. +- **Scalable**: queues absorb large bursts and handle heavy backpressure safely. +- **Local per actor**: each actor instance has its own queue storage (scoped by actor key/id). + +Queues are commonly referred to as "mailboxes" in other actor frameworks. + +For a worked queue-driven pattern, see the cookbook: [AI Agent](/cookbook/ai-agent/). + +## What are queues good for? + +- Great for any task that changes actor state. +- Helps avoid race conditions by handling work in order. +- Makes complex behavior easier to organize. + +## Basic queue + +This is the default pattern. Define queue names in `queues`, process them in `run`, and publish from the client with `handle.send(...)`. + +## Completable messages + +Use this when you want explicit completion/ack semantics but do not need to return data. + +- `message.complete()` resolves a sender waiting on `wait: true` (or `enqueueAndWait`). It does not change durability: messages are removed from queue storage when they are received, not when they are completed. +- If processing fails before `message.complete()`, the message is not redelivered, and any waiting sender times out instead of receiving a completion. +- `status: "timedOut"` means sender timeout elapsed before `message.complete(...)`. + +## Request/reply pattern + +Use this when the sender needs data back from queued work. + +## Queue messages from within an actor + +Queueing is useful from inside actor logic too, not just from clients. + +- Use actions as entrypoints, then enqueue into the run loop to keep mutations serialized. +- You can also call `c.queue.send(...)` from other parts of `run` when needed. +- `c.queue.send(...)` confirms durable enqueue. It does not wait for processing to finish. + +## Defining queue schemas + +You can define queue types with `queue()` or with schema objects. Schema objects support [Standard Schema](https://standardschema.dev/) validators, including [Zod](https://zod.dev/). + +## Pull messages with `next` and `nextBatch` + +Use `next` when you want to wait for one queue message. +Use `nextBatch` when you want to wait for multiple queue messages. + +- Waits until messages are available unless timeout is hit. +- Omit `timeout` to wait indefinitely. + +## Poll messages + +Use `tryNext` when you need one non-blocking read. +Use `tryNextBatch` for non-blocking batch reads. + +- Returns immediately and never waits. + +## Abort signals + +Use `signal` when your receive loop needs external cancellation semantics in addition to actor shutdown behavior. + +## Multiple queues + +Multiple queues let you separate message flows by purpose. By default, receive calls race across all queues when `names` is not specified. In this pattern, prompt messages run through a streaming loop while stop messages act as control signals on a separate receive path. + +Use `iter({ names: ["prompt"] })` as the main stream and `next({ names: ["stop"] })` as a stop signal. + +## Sleeping behavior + +If an actor has a `run` handler, it does not sleep while that handler is actively doing work. It only can sleep when the run loop is blocked waiting for queue entries (for example inside `iter(...)` or `next(...)`). + +This means you can run normal code in `run` without worrying about sleep interrupting it mid-call. + +## Debugging + +- `GET /inspector/queue?limit=50` returns queue size and pending message metadata. +- `GET /inspector/summary` includes `queueSize` for quick queue health checks. +- `POST /queue/:name` with `wait: true` is useful to verify completable/request-response behavior. +- In non-dev mode, inspector endpoints require authorization. + +## Recommendations + +- Actions are for getting data, queue entries are for mutating data. +- Implement connection auth in `onBeforeConnect`. See [Authentication](/docs/actors/authentication). +- Route most state changes through one queue loop so ordering stays predictable. +- If you need more complex multi-step run loops, consider using workflows. +- Use `c.aborted` and `c.abortSignal` for actor shutdown. Use your own `AbortController` for earlier loop cancellation. +- Add `timeout` when callers need bounded wait behavior. +- Use `wait: true` only when the caller actually needs a response. + +## Pitfalls + +### Avoid `wait: true` between actors + +`wait: true` blocks the sender's run loop until the receiver finishes. Between actors, this adds unnecessary overhead and risks deadlocks, especially if the target actor needs to communicate back. If an actor sends a `wait: true` message to *itself*, it is a guaranteed deadlock because the run loop is already busy processing the current message. + +Reserve `wait: true` for external callers (HTTP handlers, CLI tools, client apps). For actor-to-actor communication, send a queue message to the other actor without `wait: true`, then have that actor send a queue message back when the work is done. + +## Tips + +### Message TTL + +Every queue message includes a `createdAt` timestamp. Use this to skip or discard stale messages in your run loop: + +### Delayed delivery + +Use [`c.schedule`](/docs/actors/schedule) to enqueue messages at a future time instead of processing them immediately: + +See [Schedule](/docs/actors/schedule) for the full scheduling API. + +_Source doc path: /docs/actors/queues_ diff --git a/.agents/skills/chat-room/reference/actors/quickstart/backend.md b/.agents/skills/chat-room/reference/actors/quickstart/backend.md new file mode 100644 index 0000000..86cbdf2 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/quickstart/backend.md @@ -0,0 +1,64 @@ +# Node.js & Bun Quickstart + +> Source: `src/content/docs/actors/quickstart/backend.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/backend +> Description: Get started with Rivet Actors in Node.js and Bun + +--- +Prefer to start from a complete project? See the runnable [`hello-world`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world) example. + +## Steps + +### Add Rivet Skill to Coding Agent (Optional) + +If you're using an AI coding assistant (like Claude Code, Cursor, Windsurf, etc.), add Rivet skills for enhanced development assistance: + +```sh +npx skills add rivet-dev/skills +``` + +### Install Rivet + +```sh +npm install rivetkit +``` + +### Create Actors and Start Server + +Create a file with your actors, set up the registry, and start the server: + +### Run Server + +```sh Node.js +npx tsx --watch index.ts +``` + +```sh Bun +bun --watch index.ts +``` + +```sh Deno +deno run --allow-net --allow-read --allow-env --watch index.ts +``` + +Your server is now running on `http://localhost:6420`. Clients connect directly to the Rivet Engine on this port. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend: + +### TypeScript + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### React + +See the [React documentation](/docs/clients/react) for more information. + +### Deploy + +## Configuration Options + +_Source doc path: /docs/actors/quickstart/backend_ diff --git a/.agents/skills/chat-room/reference/actors/quickstart/cloudflare.md b/.agents/skills/chat-room/reference/actors/quickstart/cloudflare.md new file mode 100644 index 0000000..e39cbe4 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/quickstart/cloudflare.md @@ -0,0 +1,165 @@ +# Cloudflare Workers Quickstart + +> Source: `src/content/docs/actors/quickstart/cloudflare.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/cloudflare +> Description: Set up a Rivet project locally targeting Cloudflare Workers. + +--- +Set up a Rivet project locally that runs on Cloudflare Workers. The `@rivetkit/cloudflare-workers` package wires the WebAssembly runtime for you. + +Prefer to start from a complete project? See the runnable [`hello-world-cloudflare-workers`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-cloudflare-workers) example (with [Hono](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-cloudflare-workers-hono) and [raw router](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-cloudflare-workers-raw) variants). + +## Steps + +### Install Packages + +```sh +npm install rivetkit @rivetkit/cloudflare-workers +npm install --save-dev wrangler +``` + +### Configure Wrangler + +```toml wrangler.toml +name = "rivetkit-cloudflare" +main = "src/index.ts" +compatibility_date = "2025-04-01" +compatibility_flags = ["nodejs_compat"] +``` + +The `nodejs_compat` flag is required so the runtime can read its connection config from `process.env`. + +### Create the Worker + +`createHandler` serves the Rivet manager API on `/api/rivet`. Pick how you want to handle your own routes: + +- **Default**: Rivet handles everything. +- **Hono**: Mount a [Hono](https://hono.dev) app for your routes (`npm install hono`). +- **Raw**: Provide a `fetch` and route requests yourself. + +```ts Default @nocheck +import { actor } from "rivetkit"; +import { createHandler } from "@rivetkit/cloudflare-workers"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +export default createHandler({ use: { counter } }); +``` + +```ts Hono @nocheck +import { actor } from "rivetkit"; +import { createClient } from "rivetkit/client"; +import { createHandler, setup } from "@rivetkit/cloudflare-workers"; +import { Hono } from "hono"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +// `setup` returns a typed registry, so the client below is fully typed. +const registry = setup({ use: { counter } }); + +const app = new Hono(); + +app.get("/", (c) => c.text("Hello from Hono + Rivet Actors!")); + +app.post("/increment/:name", async (c) => { + // `createClient` reads RIVET_ENDPOINT from the environment (passed by `rivet + // dev`, or set as a Worker secret in production). + const client = createClient(); + const count = await client.counter.getOrCreate(c.req.param("name")).increment(1); + return c.json({ count }); +}); + +// Rivet keeps `/api/rivet`; Hono handles everything else. +export default createHandler(registry, { fetch: app.fetch }); +``` + +```ts Raw @nocheck +import { actor } from "rivetkit"; +import { createClient } from "rivetkit/client"; +import { createHandler, setup } from "@rivetkit/cloudflare-workers"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +// `setup` returns a typed registry, so the client below is fully typed. +const registry = setup({ use: { counter } }); + +// Rivet keeps `/api/rivet`; your `fetch` handles everything else. +export default createHandler(registry, { + fetch: async (request: Request) => { + const url = new URL(request.url); + + if (url.pathname === "/") { + return new Response("Hello from a raw Rivet Worker router!"); + } + + const increment = url.pathname.match(/^\/increment\/(.+)$/); + if (request.method === "POST" && increment) { + // `createClient` reads RIVET_ENDPOINT from the environment (passed by + // `rivet dev`, or set as a Worker secret in production). + const client = createClient(); + const count = await client.counter.getOrCreate(increment[1]).increment(1); + return Response.json({ count }); + } + + return new Response("Not found", { status: 404 }); + }, +}); +``` + +### Run Locally + +Start Rivet. The CLI runs the local engine and spawns `wrangler dev` for you: + +```sh +npx @rivetkit/cli dev --provider cloudflare +``` + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend. It connects directly to the local engine on `http://localhost:6420`: + +### TypeScript + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### React + +See the [React documentation](/docs/clients/react) for more information. + +### Deploy + +Ready to ship? See [Deploying to Cloudflare Workers](/docs/deploy/cloudflare). + +## Related + +- [Quickstart](/docs/actors/quickstart) +- [Deploying to Cloudflare Workers](/docs/deploy/cloudflare) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/actors/quickstart/cloudflare_ diff --git a/.agents/skills/chat-room/reference/actors/quickstart/effect.md b/.agents/skills/chat-room/reference/actors/quickstart/effect.md new file mode 100644 index 0000000..fc252e9 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/quickstart/effect.md @@ -0,0 +1,239 @@ +# Effect.ts Quickstart (Beta) + +> Source: `src/content/docs/actors/quickstart/effect.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/effect +> Description: Build a Rivet Actor with the Effect SDK + +--- +Effect support is in beta. The `@rivetkit/effect` API may change between releases. See the [`hello-world-effect`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-effect) and [`chat-room-effect`](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room-effect) examples for complete runnable projects. + +## Steps + +### Install Rivet + +Add `rivetkit`, the Effect SDK, and its Effect peers: + +```sh +npm install rivetkit @rivetkit/effect effect @effect/platform-node +``` + +### Define Your Actor + +Split each actor into a public contract and a server-only implementation so the contract can be imported from client code without leaking server details. + +The contract declares the actor and its actions. Actions are standalone values with explicit [`effect/Schema`](https://effect.website/docs/schema/introduction/) payloads and successes, validated end to end: + +```ts src/actors/counter/api.ts @nocheck +import { Action, Actor } from "@rivetkit/effect"; +import { Schema } from "effect"; + +export const Increment = Action.make("Increment", { + payload: { amount: Schema.Number }, + success: Schema.Number, +}); + +export const GetCount = Action.make("GetCount", { + success: Schema.Number, +}); + +export const Counter = Actor.make("Counter", { + actions: [Increment, GetCount], +}); +``` + +The implementation registers the actor with `.toLayer`. The wake function runs once when the actor awakes and returns the action handlers. Persisted state is accessed through a `SubscriptionRef`-like `State` API: + +```ts src/actors/counter/live.ts @nocheck +import { Actor, State } from "@rivetkit/effect"; +import { Effect, Schema } from "effect"; +import { Counter } from "./api.ts"; + +export const CounterLive = Counter.toLayer( + Effect.fnUntraced(function* ({ rawRivetkitContext, state }) { + return Counter.of({ + Increment: Effect.fnUntraced(function* ({ payload }) { + const next = yield* State.updateAndGet(state, (current) => ({ + count: current.count + payload.amount, + })).pipe(Effect.orDie); + + // Broadcast the new value to every connected client. + rawRivetkitContext.broadcast("newCount", next.count); + + return next.count; + }), + GetCount: () => + State.get(state).pipe( + Effect.map((current) => current.count), + Effect.orDie, + ), + }); + }), + { + state: { + schema: Schema.Struct({ count: Schema.Number }), + initialValue: () => ({ count: 0 }), + }, + name: "Counter", + icon: "calculator", + }, +); +``` + +### Serve The Registry + +Compose the actor layers and serve them with `Registry.serve`. `Registry.layer()` reads engine config from the environment, and the actor layer is provided a `Client` so actors can call other actors: + +```ts src/main.ts @nocheck +import { NodeRuntime } from "@effect/platform-node"; +import { Client, Registry } from "@rivetkit/effect"; +import { Layer } from "effect"; +import { CounterLive } from "./actors/counter/live.ts"; + +const endpoint = process.env.RIVET_ENDPOINT ?? "http://127.0.0.1:6420"; + +const ActorsLayer = CounterLive.pipe(Layer.provide(Client.layer({ endpoint }))); + +const MainLayer = Registry.serve(ActorsLayer).pipe(Layer.provide(Registry.layer())); + +// Keeps the layer alive. Tears down on SIGINT/SIGTERM. +Layer.launch(MainLayer).pipe(NodeRuntime.runMain); +``` + +### Run The Server + +Set `RIVET_RUN_ENGINE=1` to spawn a local Rivet Engine alongside the server. The engine binary is downloaded and cached the first time you run, so there is nothing else to install: + +```sh +RIVET_RUN_ENGINE=1 npx tsx --watch src/main.ts +``` + +Your server now connects to the Rivet Engine on `http://localhost:6420`. Clients connect directly to the engine on this port. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +To point at a remote engine instead, set `RIVET_ENDPOINT=https://...` and omit `RIVET_RUN_ENGINE`. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend: + +### Effect + +The Effect client imports the same actor contract from your registry. `Counter.client` yields a typed accessor backed by the client layer: + +```ts src/client.ts @nocheck +import { NodeRuntime } from "@effect/platform-node"; +import { Client } from "@rivetkit/effect"; +import { Effect } from "effect"; +import { Counter } from "./actors/counter/api.ts"; + +const program = Effect.gen(function* () { + const counter = (yield* Counter.client).getOrCreate("my-counter"); + + const count = yield* counter.Increment({ amount: 3 }); + yield* Effect.log(`New count: ${count}`); + + const total = yield* counter.GetCount(); + yield* Effect.log(`Total: ${total}`); +}); + +const ClientLayer = Client.layer({ endpoint: "http://localhost:6420" }); + +program.pipe(Effect.provide(ClientLayer), NodeRuntime.runMain); +``` + +With the server still running, start the client in another terminal: + +```sh +npx tsx src/client.ts +``` + +See the [`chat-room-effect`](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room-effect) example for a larger project with typed errors and actor-to-actor calls. + +### TypeScript + +A plain RivetKit client can call your Effect actor by name through the same engine. Actor and action names are resolved at runtime, so the client is untyped here: + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient("http://localhost:6420"); + +const counter = client.Counter.getOrCreate(["my-counter"]); + +const count = await counter.Increment({ amount: 3 }); +console.log("New count:", count); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### Deploy + +## Feature Support + +The Effect SDK wraps the most common actor features with typed, schema-validated APIs. Everything else is still fully usable through the raw RivetKit context (see [Raw Escape Hatch](#raw-escape-hatch) below), so no feature is off limits, it just isn't typed yet. + +| Feature | Effect-native API | Access | +| --- | --- | --- | +| Actor contract & actions | `Actor.make`, `Action.make` | Typed | +| Persisted state | `State.get` / `set` / `update` / `updateAndGet` / `changes` | Typed | +| Typed client | `Actor.client`, `Client.layer` | Typed | +| Typed errors | `RivetError` | Typed | +| Logging | `RivetLogger` | Typed | +| Sleep request | `Actor.Sleep` | Typed | +| Actor address (`actorId` / `name` / `key`) | `Actor.CurrentAddress` | Typed | +| Registry serve / test / web handler | `Registry` | Typed | +| [Events & broadcast](/docs/actors/events) | Not yet wrapped | `rawRivetkitContext.broadcast(...)` | +| [Schedule](/docs/actors/schedule) | Not yet wrapped | `rawRivetkitContext.schedule.*` | +| [Embedded SQLite](/docs/actors/sqlite) | Not yet wrapped | `rawRivetkitContext.db.execute(...)` | +| [Destroy](/docs/actors/lifecycle) | Not yet wrapped | `rawRivetkitContext.destroy()` | +| Queues, connections, vars, alarms | Not yet wrapped | `rawRivetkitContext.*` | +| Lifecycle hooks (`onSleep` / `onDestroy`) | Not yet wrapped | `rawRivetkitContext.*` | +| Raw HTTP / WebSocket handlers | Not yet wrapped | `rawRivetkitContext.*` | + +### Raw Escape Hatch + +Every wake function receives `rawRivetkitContext`, the underlying RivetKit [actor context](/docs/actors). Reach for it to use any feature that does not have a typed wrapper yet. The typed `state` argument and the raw context point at the same actor, so you can mix both: + +```ts src/actors/counter/live.ts @nocheck +export const CounterLive = Counter.toLayer( + Effect.fnUntraced(function* ({ rawRivetkitContext, state }) { + return Counter.of({ + Increment: Effect.fnUntraced(function* ({ payload }) { + // Typed state wrapper + const next = yield* State.updateAndGet(state, (current) => ({ + count: current.count + payload.amount, + })).pipe(Effect.orDie); + + // Untyped features run through the raw context + rawRivetkitContext.broadcast("newCount", next.count); + rawRivetkitContext.schedule.after(1_000, "tick", {}); + + return next.count; + }), + }); + }), + { + state: { + schema: Schema.Struct({ count: Schema.Number }), + initialValue: () => ({ count: 0 }), + }, + name: "Counter", + }, +); +``` + +Calls through `rawRivetkitContext` are not validated by `effect/Schema` and their payloads are typed as they are in the base RivetKit API. + +## Next Steps + + +- [Actions](/docs/actors/actions) — Define the RPC surface clients call on your actor. + + +- [State](/docs/actors/state) — Persist and load actor state across sleeps and restarts. + + +- [Events](/docs/actors/events) — Broadcast realtime updates to connected clients. + +_Source doc path: /docs/actors/quickstart/effect_ diff --git a/.agents/skills/chat-room/reference/actors/quickstart/next-js.md b/.agents/skills/chat-room/reference/actors/quickstart/next-js.md new file mode 100644 index 0000000..f621606 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/quickstart/next-js.md @@ -0,0 +1,117 @@ +# Next.js Quickstart + +> Source: `src/content/docs/actors/quickstart/next-js.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/next-js +> Description: Get started with Rivet Actors in Next.js + +--- +### Add Rivet Skill to Coding Agent (Optional) + +If you're using an AI coding assistant (like Claude Code, Cursor, Windsurf, etc.), add Rivet skills for enhanced development assistance: + +```sh +npx skills add rivet-dev/skills +``` + +### Create a Next.js App + +```sh +npx create-next-app@latest my-app +cd my-app +``` + +### Install RivetKit + +### Create an Actor + +Create a file at `src/rivet/registry.ts` with a simple counter actor: + +### Setup Rivet API route + +Create a file at `src/app/api/rivet/[...all]/route.ts` to setup the API routes: + +```ts src/app/api/rivet/[...all]/route.ts @nocheck +import { toNextHandler } from "@rivetkit/next-js"; +import { registry } from "@/rivet/registry"; + +export const maxDuration = 300; + +export const { GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS } = toNextHandler(registry); +``` + +### Use the Actor in a component + +Create a Counter component and add it to your page: + +```tsx src/components/Counter.tsx @nocheck +"use client"; + +import { createRivetKit } from "@rivetkit/next-js/client"; +import type { registry } from "@/rivet/registry"; +import { useState } from "react"; + +export const { useActor } = createRivetKit({ + endpoint: + process.env.NEXT_PUBLIC_RIVET_ENDPOINT ?? "http://localhost:3000/api/rivet", + namespace: process.env.NEXT_PUBLIC_RIVET_NAMESPACE, + token: process.env.NEXT_PUBLIC_RIVET_TOKEN, +}); + +export function Counter() { + const [count, setCount] = useState(0); + + // Get or create a counter actor for the key "my-counter" + const counter = useActor({ + name: "counter", + key: ["my-counter"] + }); + + // Listen to realtime events + counter.useEvent("newCount", (x: number) => setCount(x)); + + const increment = async () => { + // Call actions + await counter.connection?.increment(1); + }; + + return ( +
+

Count: {count}

+ +
+ ); +} +``` + +```tsx src/app/page.tsx @nocheck +import { Counter } from "@/components/Counter"; + +export default function Home() { + return ( +
+

My App

+ +
+ ); +} +``` + +For information about the Next.js client API, see the [React Client API Reference](/docs/clients/react). + +### Run Locally + +Start the Next.js dev server. Rivet auto-starts a local engine alongside it: + +```sh +npm run dev +``` + +Open `http://localhost:3000` in your browser to use the app. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Deploy to Vercel + +See the [Vercel deployment guide](/docs/deploy/vercel) for detailed instructions on deploying your Rivet app to Vercel. + +_Source doc path: /docs/actors/quickstart/next-js_ diff --git a/.agents/skills/chat-room/reference/actors/quickstart/react.md b/.agents/skills/chat-room/reference/actors/quickstart/react.md new file mode 100644 index 0000000..8722fed --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/quickstart/react.md @@ -0,0 +1,82 @@ +# React Quickstart + +> Source: `src/content/docs/actors/quickstart/react.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/react +> Description: Build realtime React applications with Rivet Actors + +--- +## Steps + +### Add Rivet Skill to Coding Agent (Optional) + +If you're using an AI coding assistant (like Claude Code, Cursor, Windsurf, etc.), add Rivet skills for enhanced development assistance: + +```sh +npx skills add rivet-dev/skills +``` + +### Install Dependencies + +```sh +npm install rivetkit @rivetkit/react +``` + +### Create Backend Actor and Start Server + +Create your actor registry on the backend and start the server: + +### Create React Frontend + +Set up your React application: + +For detailed information about the React client API, see the [React Client API Reference](/docs/clients/react). + +### Setup Vite Configuration + +Configure Vite for development: + +```ts vite.config.ts @nocheck +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [react()], + server: { + port: 5173, + }, +}) +``` + +### Run Your Application + +Start both the backend and frontend: + +**Terminal 1**: Start the backend + +```sh Node.js +npx tsx --watch backend/index.ts +``` + +```sh Bun +bun --watch backend/index.ts +``` + +```sh Deno +deno run --allow-net --allow-read --allow-env --watch backend/index.ts +``` + +**Terminal 2**: Start the frontend + +```sh Frontend +npx vite +``` + +Open `http://localhost:5173` in your browser. Try opening multiple tabs to see realtime sync in action. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Deploy + +## Configuration Options + +_Source doc path: /docs/actors/quickstart/react_ diff --git a/.agents/skills/chat-room/reference/actors/quickstart/rust.md b/.agents/skills/chat-room/reference/actors/quickstart/rust.md new file mode 100644 index 0000000..1e55471 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/quickstart/rust.md @@ -0,0 +1,249 @@ +# Rust Quickstart (Beta) + +> Source: `src/content/docs/actors/quickstart/rust.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/rust +> Description: Build a Rivet Actor in Rust + +--- +Rust support is in beta. The supported public Rust API is `rivetkit` and `rivetkit-client`; lower-level crates are internal implementation details and do not carry a stability guarantee. See the full API reference on [docs.rs/rivetkit](https://docs.rs/rivetkit), or the runnable [`hello-world-rust`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-rust) example. + +## Steps + +### Add Rivet + +Add the `rivetkit` crate and its companions: + +```sh +cargo add rivetkit anyhow async-trait +cargo add serde --features derive +cargo add tokio --features full +``` + +### Define Your Actor + +Put the actor in `src/lib.rs` so both your server and your client can share the same types. An actor is a type that implements `Actor`, plus one `Handles` implementation for each action. Persisted state lives in `type State`; ephemeral runtime state is just fields on your actor struct. + +```rust src/lib.rs +use std::{future::Future, pin::Pin, sync::Arc}; + +use async_trait::async_trait; +use rivetkit::prelude::*; +use serde::{Deserialize, Serialize}; + +type BoxFuture = Pin> + Send>>; + +pub struct Counter; + +#[derive(Default, Serialize, Deserialize)] +pub struct CounterState { + pub count: i64, +} + +#[derive(Serialize, Deserialize)] +pub struct Increment { + pub amount: i64, +} + +impl Action for Increment { + type Output = i64; + + const NAME: &'static str = "increment"; +} + +#[derive(Serialize, Deserialize)] +pub struct NewCount { + pub count: i64, +} + +impl Event for NewCount { + const NAME: &'static str = "newCount"; +} + +#[async_trait] +impl Actor for Counter { + type State = CounterState; + type Input = (); + type Actions = (Increment,); + type Events = (NewCount,); + type Queue = (); + type ConnParams = (); + type ConnState = (); + type Action = action::Raw; + + async fn create_state(_ctx: &Ctx, _input: Self::Input) -> Result { + Ok(CounterState::default()) + } + + async fn create(_ctx: &Ctx) -> Result { + Ok(Self) + } +} + +impl Handles for Counter { + type Future = BoxFuture; + + fn handle(self: Arc, ctx: Ctx, action: Increment) -> Self::Future { + Box::pin(async move { + let count = { + let mut state = ctx.state_mut(); + state.count += action.amount; + state.count + }; + ctx.emit(NewCount { count })?; + Ok(count) + }) + } +} + +pub fn registry() -> Registry { + let mut registry = Registry::new(); + registry.register_actor::("counter"); + registry +} +``` + +### Serve The Registry + +Your `src/main.rs` just starts the registry from the library: + +```rust src/main.rs +#[tokio::main] +async fn main() -> anyhow::Result<()> { + counter::registry().start().await +} +``` + +Replace `counter` with your crate name (the package `name` in `Cargo.toml`, with dashes as underscores). + +### Run The Server + +The Rust runtime connects to the Rivet Engine. Setting `RIVETKIT_ENGINE_AUTO_DOWNLOAD=1` lets the runtime download and cache a matching engine binary the first time you run, so there is nothing else to install: + +```sh +RIVETKIT_ENGINE_AUTO_DOWNLOAD=1 cargo run +``` + +Your server now connects to the Rivet Engine on `http://localhost:6420`. Clients connect directly to the engine on this port. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +Already have an engine binary? Set `RIVET_ENGINE_BINARY_PATH=/path/to/rivet-engine` to point at it instead. If you are working inside the [Rivet monorepo](https://github.com/rivet-dev/rivet), a local `cargo build -p rivet-engine` is discovered automatically from `target/debug`. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend: + +### Rust + +Add a `src/bin/client.rs` that imports the same actor types from your library. There is no need to redefine the actor on the client. + +```rust src/bin/client.rs +use counter::{Counter, Increment, NewCount}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + let count = counter.send(Increment { amount: 3 }).await?; + println!("New count: {count}"); + + let connection = counter.connect(); + connection + .on::(|event| println!("Count changed: {}", event.count)) + .await; + connection.send(Increment { amount: 1 }).await?; + + Ok(()) +} +``` + +With the server still running, start the client in another terminal: + +```sh +cargo run --bin client +``` + +See the [`hello-world-rust`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-rust) example for a complete runnable counter. + +### TypeScript + +A TypeScript client can call your Rust actor by name through the same engine. Actor and action names are resolved at runtime, so the client is untyped here: + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient("http://localhost:6420"); + +const counter = client.counter.getOrCreate(["my-counter"]); + +const counterConnection = counter.connect(); +counterConnection.on("newCount", (event) => { + console.log("Event count:", event.count); +}); + +const count = await counterConnection.increment(3); +console.log("New count:", count); + +await counterConnection.increment(1); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### React + +```tsx Counter.tsx @nocheck +import { createRivetKit } from "@rivetkit/react"; +import { useState } from "react"; + +const { useActor } = createRivetKit("http://localhost:6420"); + +function Counter() { + const [count, setCount] = useState(0); + + const counter = useActor({ + name: "counter", + key: ["my-counter"], + }); + + const increment = async () => { + await counter.connection?.increment(1); + }; + + counter.useEvent("newCount", (event) => { + setCount(event.count); + }); + + return ( +
+

Count: {count}

+ +
+ ); +} +``` + +See the [React documentation](/docs/clients/react) for more information. + +### Deploy + +## Next Steps + + +- [API Reference](https://docs.rs/rivetkit) — Full `rivetkit` crate documentation on docs.rs. + + +- [Actions](/docs/actors/actions) — Define the RPC surface clients call on your actor. + + +- [State](/docs/actors/state) — Persist and load actor state across sleeps and restarts. + + +- [Events](/docs/actors/events) — Broadcast realtime updates to connected clients. + +_Source doc path: /docs/actors/quickstart/rust_ diff --git a/.agents/skills/chat-room/reference/actors/quickstart/supabase.md b/.agents/skills/chat-room/reference/actors/quickstart/supabase.md new file mode 100644 index 0000000..20b59d0 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/quickstart/supabase.md @@ -0,0 +1,109 @@ +# Supabase Functions Quickstart + +> Source: `src/content/docs/actors/quickstart/supabase.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/supabase +> Description: Set up a Rivet project locally targeting Supabase Edge Functions. + +--- +Set up a Rivet project locally that runs on Supabase Edge Functions. The `@rivetkit/supabase` package wires the WebAssembly runtime for you. + +Prefer to start from a complete project? See the runnable [`hello-world-supabase-functions`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-supabase-functions) example. + +## Steps + +### Prerequisites + +- [Node.js](https://nodejs.org/) +- [Supabase CLI](https://supabase.com/docs/guides/cli) +- Docker, for Supabase's local Edge Runtime + +The CLI runs the local Rivet engine as a bundled native binary, so Docker is only needed for Supabase itself. A Supabase project is only needed to deploy. + +### Create the Function + +```sh +npx supabase functions new rivet +``` + +Add the packages used by the function: + +```sh +npm install rivetkit @rivetkit/supabase +``` + +### Configure the Function + +Call `serve` from `@rivetkit/supabase`. It loads the WebAssembly runtime and serves the Rivet handler. + +```ts supabase/functions/rivet/index.ts @nocheck +import { actor } from "rivetkit"; +import { serve, setup } from "@rivetkit/supabase"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +// `setup` returns a typed registry, so a client can type itself with +// `typeof registry`. +export const registry = setup({ use: { counter } }); + +await serve(registry); +``` + +Add a `deno.json` next to the function so the deploy bundles only the WebAssembly runtime. It points `rivetkit` at the pre-bundled `@rivetkit/supabase`, keeping the deploy small. Without it, the deploy pulls Rivet's native engine and 413s. + +```json supabase/functions/rivet/deno.json +{ + "imports": { + "rivetkit": "npm:@rivetkit/supabase", + "@rivetkit/supabase": "npm:@rivetkit/supabase" + } +} +``` + +Your function code keeps importing from `rivetkit` as usual. The import map only changes how Deno resolves it at bundle time. + +### Run Locally + +Start Rivet. The CLI runs the local engine, spawns `supabase functions serve` for you, and populates the connection values: + +```sh +npx @rivetkit/cli dev --provider supabase +``` + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Call the Actor + +Connect to your actor from a client. This connects directly to the local engine on `http://localhost:6420`: + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./supabase/functions/rivet/index"; + +const client = createClient("http://localhost:6420"); + +const counter = client.counter.getOrCreate(["my-counter"]); +const count = await counter.increment(3); +console.log("New count:", count); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### Deploy + +Ready to ship? See [Deploying to Supabase Functions](/docs/deploy/supabase). + +## Related + +- [Quickstart](/docs/actors/quickstart) +- [Deploying to Supabase Functions](/docs/deploy/supabase) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/actors/quickstart/supabase_ diff --git a/.agents/skills/chat-room/reference/actors/request-handler.md b/.agents/skills/chat-room/reference/actors/request-handler.md new file mode 100644 index 0000000..0536b9c --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/request-handler.md @@ -0,0 +1,79 @@ +# Low-Level HTTP Request Handler + +> Source: `src/content/docs/actors/request-handler.mdx` +> Canonical URL: https://rivet.dev/docs/actors/request-handler +> Description: Actors can handle HTTP requests through the `onRequest` handler. + +--- +For most use cases, [actions](/docs/actors/actions) provide high-level API powered by HTTP that's easier to work with than low-level HTTP. However, low-level handlers are required when implementing custom use cases or integrating external libraries that need direct access to the underlying HTTP `Request`/`Response` objects or WebSocket connections. + +## Handling HTTP Requests + +The `onRequest` handler processes HTTP requests sent to your actor. It receives the actor context and a standard `Request` object and returns a `Response` object. + +### Raw HTTP + +### Hono + +See also the [raw fetch handler example](https://github.com/rivet-dev/rivet/tree/main/examples/raw-fetch-handler). + +## Sending Requests To Actors + +### Via RivetKit Client + +Use the `.fetch()` method on an actor handle to send HTTP requests to the actor's `onRequest` handler. This can be executed from either your frontend or backend. + +### Via getGatewayUrl + +Use `.getGatewayUrl()` to get the raw gateway URL for the actor. This is useful when you need to use the URL with external tools or custom HTTP clients. + +### Via HTTP API + +This handler can be accessed with raw HTTP using `https://api.rivet.dev/gateway/{actorId}/request/{...path}`. + +For example, to call `POST /increment` on the counter actor above: + +```bash +curl -X POST "https://api.rivet.dev/gateway/{actorId}/request/increment" \ + -H "x-rivet-token: {token}" +``` + +The request is routed to the actor's `onRequest` handler where: + +- `request.method` is `"POST"` +- `request.url` ends with `/increment` (the path after `/request/`) +- Headers, body, and other request properties are passed through unchanged + +See the [HTTP API reference](/docs/actors/http-api) for more information on HTTP routing and authentication. + +### Via Proxying Requests + +You can proxy HTTP requests from your own server to actor handlers using the RivetKit client. This is useful when you need to add custom authentication, rate limiting, or request transformation before forwarding to actors. + +## Connection & Lifecycle Hooks + +`onRequest` will trigger the `onBeforeConnect`, `onConnect`, and `onDisconnect` hooks. Read more about [lifecycle hooks](/docs/actors/lifecycle). + +Requests in flight will be listed in `c.conns`. Read more about [connections](/docs/actors/connections). + +## WinterTC Compliance + +The `onRequest` handler is WinterTC compliant and will work with existing libraries using the standard `Request` and `Response` types. + +## Limitations + +- Does not support streaming responses & server-sent events at the moment. See the [tracking issue](https://github.com/rivet-dev/rivet/issues/3529). +- `OPTIONS` requests currently are handled by Rivet and are not passed to `onRequest` + +## Advanced + +### Skip Ready Wait + +Requests are normally held at the gateway until the actor is ready. Pass `skipReadyWait: true` on `handle.fetch()` to deliver immediately, including while the actor is still starting or in the [sleep grace period](/docs/actors/lifecycle#shutdown-sequence). See [Skip Ready Wait](/docs/clients/javascript#skip-ready-wait) for details. + +## API Reference + +- [`RequestContext`](/typedoc/interfaces/rivetkit.mod.RequestContext.html) - Context for HTTP request handlers +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining request handlers + +_Source doc path: /docs/actors/request-handler_ diff --git a/.agents/skills/chat-room/reference/actors/scaling.md b/.agents/skills/chat-room/reference/actors/scaling.md new file mode 100644 index 0000000..b597115 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/scaling.md @@ -0,0 +1,10 @@ +# Scaling & Concurrency + +> Source: `src/content/docs/actors/scaling.mdx` +> Canonical URL: https://rivet.dev/docs/actors/scaling +> Description: This page has moved to [design patterns](/docs/actors/design-patterns). + +--- + + +_Source doc path: /docs/actors/scaling_ diff --git a/.agents/skills/chat-room/reference/actors/schedule.md b/.agents/skills/chat-room/reference/actors/schedule.md new file mode 100644 index 0000000..8dfdb1f --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/schedule.md @@ -0,0 +1,40 @@ +# Actor Scheduling + +> Source: `src/content/docs/actors/schedule.mdx` +> Canonical URL: https://rivet.dev/docs/actors/schedule +> Description: Schedule actor actions in the future with persistent timers that survive restarts and upgrades. + +--- +Scheduling is used to trigger events in the future. The actor scheduler is like `setTimeout`, except the timeout will persist even if the actor restarts, upgrades, or crashes. + +For a pattern guide to durable recurring jobs, see the cookbook: [Cron Jobs and Scheduled Tasks](/cookbook/cron-jobs/). + +## Use Cases + +Scheduling is helpful for long-running timeouts like month-long billing periods or account trials. + +## Scheduling + +### `c.schedule.after(duration, actionName, ...args)` + +Schedules a function to be executed after a specified duration. This function persists across actor restarts, upgrades, or crashes. + +Parameters: + +- `duration` (number): The delay in milliseconds. +- `actionName` (string): The name of the action to be executed. +- `...args` (unknown[]): Additional arguments to pass to the function. + +### `c.schedule.at(timestamp, actionName, ...args)` + +Schedules a function to be executed at a specific timestamp. This function persists across actor restarts, upgrades, or crashes. + +Parameters: + +- `timestamp` (number): The exact time in milliseconds since the Unix epoch when the function should be executed. +- `actionName` (string): The name of the action to be executed. +- `...args` (unknown[]): Additional arguments to pass to the function. + +## Full Example + +_Source doc path: /docs/actors/schedule_ diff --git a/.agents/skills/chat-room/reference/actors/sharing-and-joining-state.md b/.agents/skills/chat-room/reference/actors/sharing-and-joining-state.md new file mode 100644 index 0000000..1fe0683 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/sharing-and-joining-state.md @@ -0,0 +1,10 @@ +# Sharing and Joining State + +> Source: `src/content/docs/actors/sharing-and-joining-state.mdx` +> Canonical URL: https://rivet.dev/docs/actors/sharing-and-joining-state +> Description: This page has moved to [design patterns](/docs/actors/design-patterns). + +--- + + +_Source doc path: /docs/actors/sharing-and-joining-state_ diff --git a/.agents/skills/chat-room/reference/actors/sqlite-drizzle.md b/.agents/skills/chat-room/reference/actors/sqlite-drizzle.md new file mode 100644 index 0000000..f0184d9 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/sqlite-drizzle.md @@ -0,0 +1,248 @@ +# SQLite + Drizzle + +> Source: `src/content/docs/actors/sqlite-drizzle.mdx` +> Canonical URL: https://rivet.dev/docs/actors/sqlite-drizzle +> Description: Use Drizzle ORM with embedded SQLite in Rivet Actors. + +--- +Use Drizzle when you want typed schema, typed queries, and generated migrations on top of actor-local SQLite. + +For a high-level overview of where to store actor data, see [State & Storage](/docs/actors/state). For a worked multi-tenant pattern, see the cookbook: [Database per Tenant](/cookbook/per-tenant-database/). + +## What is Drizzle good for? + +- **Typed schema**: define tables in TypeScript and get typed query results. +- **Typed query builder**: write SQL-like queries with autocompletion. +- **Migration workflow**: generate SQL migration files from schema changes. +- **Raw SQL escape hatch**: use `c.db.execute(...)` for direct SQLite when needed. + +## Project structure + +Use one folder per actor database: + +```txt +src/ + actors/ + todo-list/ + index.ts + schema.ts + drizzle.config.ts + drizzle/ + 0000_init.sql + migrations.js + migrations.d.ts + meta/ + _journal.json +``` + +- `index.ts` is the actor implementation. +- `drizzle/` holds the SQL migrations (`*.sql`) and `meta/_journal.json` generated by `drizzle-kit`. +- `migrations.js` is a small RivetKit glue file you maintain by hand. It imports the journal and each `*.sql` file and exports a `{ journal, migrations }` object keyed by migration (for example `m0000`). Add a new entry here whenever `db:generate` produces a new migration. +- Commit the generated migration files and `migrations.js` to source control. + +## Basic setup + +```json package.json +{ + "scripts": { + "db:generate": "find src/actors -name drizzle.config.ts -exec drizzle-kit generate --config {} \\;" + }, + "dependencies": { + "rivetkit": "*", + "drizzle-orm": "^0.44.2" + }, + "devDependencies": { + "drizzle-kit": "^0.31.2" + } +} +``` + +```ts vite.config.ts @nocheck +import { defineConfig, type Plugin } from "vite"; +import { readFileSync } from "node:fs"; + +function sqlRawPlugin(): Plugin { + return { + name: "sql-raw", + transform(_code, id) { + if (id.endsWith(".sql")) { + const content = readFileSync(id, "utf-8"); + return { code: `export default ${JSON.stringify(content)};` }; + } + }, + }; +} + +export default defineConfig({ + plugins: [sqlRawPlugin()], +}); +``` + +```ts drizzle.config.ts @nocheck +import { defineConfig } from "rivetkit/db/drizzle"; + +export default defineConfig({ + schema: "./src/actors/todo-list/schema.ts", + out: "./src/actors/todo-list/drizzle", +}); +``` + +```sql 0000_init.sql +CREATE TABLE `todos` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `title` text NOT NULL, + `created_at` integer NOT NULL +); +``` + +```json _journal.json +{ + "version": "7", + "dialect": "sqlite", + "entries": [ + { + "idx": 0, + "version": "7", + "when": 1735689600000, + "tag": "0000_init", + "breakpoints": true + } + ] +} +``` + +```ts migrations.js @nocheck +import journal from "./meta/_journal.json"; +import m0000 from "./0000_init.sql"; + +export default { + journal, + migrations: { + m0000, + }, +}; +``` + +```ts index.ts @nocheck +import { actor } from "rivetkit"; +import { db } from "rivetkit/db/drizzle"; +import migrations from "./drizzle/migrations.js"; +import { schema, todos } from "./schema.ts"; + +export const todoList = actor({ + db: db({ schema, migrations }), + actions: { + addTodo: async (c, title: string) => { + const rows = await c.db + .insert(todos) + .values({ title, createdAt: Date.now() }) + .returning(); + return rows[0]; + }, + getTodos: async (c) => { + return await c.db.select().from(todos).orderBy(todos.id); + }, + getTodoCount: async (c) => { + const rows = (await c.db.execute( + "SELECT COUNT(*) AS count FROM todos", + )) as { count: number }[]; + return rows[0]?.count ?? 0; + }, + }, +}); +``` + +```ts index.ts @nocheck +import { setup } from "rivetkit"; +import { todoList } from "./todo-list/index.ts"; + +export const registry = setup({ use: { todoList } }); +registry.start(); +``` + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const todoList = client.todoList.getOrCreate(["main"]); + +await todoList.addTodo("Write Drizzle docs"); + +const todos = await todoList.getTodos(); +const count = await todoList.getTodoCount(); + +console.log(todos, count); +``` + +## Queries + +### Query builder + +Use Drizzle's typed query APIs for most reads and writes. + +```ts @nocheck +import { eq } from "drizzle-orm"; + +await c.db.insert(todos).values({ title, createdAt: Date.now() }); + +const rows = await c.db + .select() + .from(todos) + .where(eq(todos.title, title)); +``` + +### Raw SQL + +`rivetkit/db/drizzle` also exposes raw SQLite access through `c.db.execute(...)`. + +```ts @nocheck +await c.db.execute( + "CREATE INDEX IF NOT EXISTS idx_todos_created_at ON todos(created_at)", +); +``` + +## Queues + +Use queues for ordered mutations and keep actions read-only. Import `queue` alongside `actor` from `rivetkit`. + +```ts @nocheck +import { actor, queue } from "rivetkit"; + +// ... + +queues: { + addTodo: queue<{ title: string }>(), +}, +run: async (c) => { + for await (const message of c.queue.iter()) { + if (message.name === "addTodo") { + await c.db.insert(todos).values({ + title: message.body.title, + createdAt: Date.now(), + }); + } + } +}, +actions: { + getTodos: async (c) => await c.db.select().from(todos), +}, +``` + +## Recommendations + +- Prefer Drizzle query APIs for app code and use raw SQL for advanced SQLite features. +- Keep one `drizzle.config.ts` per actor folder. +- Re-run `db:generate` after schema changes and commit generated migration files. +- Use queues for writes and actions for reads. +- Keep related writes in one action or queue message to reduce interleaved query risk. + +## Read more + +- [Drizzle SQLite quickstart](https://orm.drizzle.team/docs/get-started-sqlite) +- [Drizzle `drizzle-kit generate`](https://orm.drizzle.team/docs/drizzle-kit-generate) +- [Drizzle + Cloudflare D1](https://orm.drizzle.team/docs/deploy-cloudflare-d1) +- [Drizzle + Cloudflare Durable Objects](https://orm.drizzle.team/docs/deploy-cloudflare-do) +- [Cloudflare Durable Objects SQLite storage](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/) + +_Source doc path: /docs/actors/sqlite-drizzle_ diff --git a/.agents/skills/chat-room/reference/actors/sqlite.md b/.agents/skills/chat-room/reference/actors/sqlite.md new file mode 100644 index 0000000..fb55998 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/sqlite.md @@ -0,0 +1,127 @@ +# SQLite + +> Source: `src/content/docs/actors/sqlite.mdx` +> Canonical URL: https://rivet.dev/docs/actors/sqlite +> Description: Use embedded SQLite in Rivet Actors with raw SQL queries. + +--- +For a high-level overview of where to store actor data, including when to use `c.state` versus SQLite, see [State & Storage](/docs/actors/state). For a worked multi-tenant pattern, see the cookbook: [Database per Tenant](/cookbook/per-tenant-database/). + +## What is SQLite? + +- **Database per actor**: each actor instance has its own SQLite database, scoped to that actor. +- **High performance**: Rivet Actors keep compute and storage together, so queries avoid network round trips to an external database. +- **Larger-than-memory storage**: SQLite stores data on disk, so you can work with datasets that do not fit in actor memory. +- **Embedded relational database**: use tables, indexes, and SQL queries directly inside actor logic. + +### SQLite features + +- **Indexes**: speed up lookups on frequently queried fields. +- **Search and filtering**: use `WHERE`, `LIKE`, and `ORDER BY` instead of manual in-memory loops. +- **Relationships**: use multiple tables and `JOIN` queries for connected data. +- **Constraints**: use primary keys, unique constraints, and foreign keys for data integrity. +- **Transactions**: apply multiple writes atomically when changes must stay consistent. + +## Raw SQL vs ORM (Drizzle) + +Rivet supports both raw SQL and [Drizzle](https://orm.drizzle.team/) for actor-local SQLite. + +Use **raw SQL** when you want direct query control and minimal abstraction. + +```ts @nocheck +await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); +const rows = await c.db.execute("SELECT id, title FROM todos ORDER BY id DESC"); +``` + +Use **Drizzle** when you want typed schema and typed query APIs. + +```ts @nocheck +await c.vars.drizzle.insert(todos).values({ title }); +const rows = await c.vars.drizzle.select().from(todos).orderBy(desc(todos.id)); +``` + +You can mix both in the same actor. + +For Drizzle setup, see [SQLite + Drizzle](/docs/actors/sqlite-drizzle). + +## Basic setup + +Define `db: db({ onMigrate })` on your actor, create your schema in `onMigrate`, and execute SQL with `c.db.execute(...)`. + +RivetKit wraps `onMigrate` in a SQLite savepoint, so migration steps are atomic. If `onMigrate` throws, all SQL run by that hook is rolled back before the actor starts. + +## Queries + +`c.db.execute(...)` returns an array of row objects for `SELECT` queries. + +```ts @nocheck +const rows = await c.db.execute( + "SELECT id, title FROM todos WHERE title LIKE ?", + `%${query}%`, +); +``` + +### Parameterized queries + +Use `?` placeholders for dynamic values and pass parameters in order after the SQL string. + +```ts @nocheck +await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); +``` + +You can also use named SQLite bindings by passing a single properties object. + +```ts @nocheck +const rows = await c.db.execute( + "SELECT id, title FROM todos WHERE title = :title", + { title: "Write SQLite docs" }, +); +``` + +### Transactions + +Use transactions when multiple writes must succeed or fail together. + +```ts @nocheck +await c.db.transaction(async (tx) => { + await tx.execute("INSERT INTO todos (title) VALUES (?)", title); + await tx.execute( + "INSERT INTO comments (todo_id, body) VALUES (last_insert_rowid(), ?)", + body, + ); +}); +``` + +RivetKit commits when the callback resolves and rolls back when it throws. Other transactions and ordinary actor SQL queue in FIFO order until the callback finishes. Transactions have a 60-second safety timeout by default; increase it for legitimately long work with `{ timeout: 120_000 }`. + +Always use the callback's `tx` value inside the transaction. Starting another transaction or using the outer `c.db` from the callback waits behind the active transaction and eventually reaches the safety timeout; the resulting error points to this possible deadlock. + +Manual `BEGIN`/`COMMIT` calls remain supported for compatibility, but cannot protect against interleaving callers. RivetKit logs a warning recommending `db.transaction()`. Set `warnOnManualTransactions: false` in `db(...)` to disable the warning; the warning itself mentions this flag. + +## Queues + +It's recommended to use queues for mutations and actions for read-only queries. This is the same code structure as the basic setup, but mutation writes are routed through queues. + +## Debugging + +- `GET /inspector/summary` includes `isDatabaseEnabled` so you can confirm SQLite is configured. +- `GET /inspector/database/schema` returns the tables and views discovered in the actor's SQLite database. +- `GET /inspector/database/rows?table=...&limit=100&offset=0` returns paged rows for a specific table or view. +- `POST /inspector/database/execute` lets you run ad-hoc SQL for debugging and data fixes with positional `args` or named `properties`. +- Keep a small read-only action for quick query verification while debugging. +- In non-dev mode, inspector endpoints require authorization. + +## Recommendations + +- Keep schema creation and migration steps in `onMigrate`; RivetKit runs them atomically inside a SQLite savepoint. +- Use `?` placeholders for dynamic values. +- Prefer queue-driven writes for ordered or background work. +- Use transactions for related multi-step mutations when atomicity matters. + +## Read more + +- [SQLite + Drizzle in Rivet Actors](/docs/actors/sqlite-drizzle) +- [SQLite docs](https://sqlite.org/docs.html) +- [SQLite SQL language reference](https://sqlite.org/lang.html) + +_Source doc path: /docs/actors/sqlite_ diff --git a/.agents/skills/chat-room/reference/actors/state.md b/.agents/skills/chat-room/reference/actors/state.md new file mode 100644 index 0000000..559b49c --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/state.md @@ -0,0 +1,270 @@ +# In-Memory State + +> Source: `src/content/docs/actors/state.mdx` +> Canonical URL: https://rivet.dev/docs/actors/state +> Description: Actors store state in memory for instant reads and writes. State can be persisted automatically or kept ephemeral. + +--- +## Types of State + +There are three ways to store data in an actor, depending on what it looks like and whether it needs to survive restarts. + +### Durable + +Simple, serializable data on `c.state` that is automatically persisted and restored across restarts. The default starting point. + +### Ephemeral + +Live objects on `c.vars` like database connections, API clients, and event emitters, or data loaded from an external source. Never persisted. + +```typescript @nocheck External database +import { actor } from "rivetkit"; +import { Pool } from "pg"; + +// One shared pool for the whole process, created once and reused by every actor +const pool = new Pool({ connectionString: process.env.DATABASE_URL }); + +const userActor = actor({ + state: { profile: null as Record | null }, + + // Load this actor's row from the shared pool on each start + createVars: async (c) => { + const { rows } = await pool.query("SELECT * FROM users WHERE id = $1", [c.key[0]]); + return { profile: rows[0] }; + }, + + actions: { + updateEmail: async (c, email: string) => { + await pool.query("UPDATE users SET email = $1 WHERE id = $2", [email, c.key[0]]); + } + } +}); +``` + +### SQLite + +Rivet also provides an embedded SQLite database (`c.db`) for when your data needs to be queried, requires safe schema migrations, or grows too large to hold in memory. See [SQLite](/docs/actors/sqlite). + +```typescript @nocheck Basic +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +const todoList = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL + ); + `); + }, + }), + + actions: { + add: async (c, title: string) => { + await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); + }, + + list: async (c) => { + return (await c.db.execute( + "SELECT id, title FROM todos ORDER BY id DESC", + )) as { id: number; title: string }[]; + }, + }, +}); +``` + +```typescript @nocheck Load into memory +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +const counter = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS counter ( + id INTEGER PRIMARY KEY CHECK (id = 1), + count INTEGER NOT NULL + ); + `); + await db.execute("INSERT OR IGNORE INTO counter (id, count) VALUES (1, 0)"); + }, + }), + + // Load the count from SQLite into memory on every start + createVars: async (c) => { + const rows = (await c.db.execute( + "SELECT count FROM counter WHERE id = 1", + )) as { count: number }[]; + return { count: rows[0].count }; + }, + + actions: { + get: (c) => c.vars.count, + + increment: async (c) => { + // Update the in-memory value and write it back to SQLite + c.vars.count += 1; + await c.db.execute("UPDATE counter SET count = ? WHERE id = 1", c.vars.count); + return c.vars.count; + }, + }, +}); +``` + +## State Isolation + +Each actor's state is fully isolated. Other actors and clients can't touch it directly; all reads and writes go through the actor's own [Actions](/docs/actors/actions). To share state across actors, see [sharing and joining state](/docs/actors/sharing-and-joining-state). + +## Durable State + +`c.state` lives in memory and is persisted automatically, so reads and writes have no added latency while the data still survives sleeps, restarts, upgrades, and crashes. Use it for small, simple values like counters, flags, and small maps. + +`createState` runs once when the actor is first created. On later starts, state is loaded from storage instead of recreated. See [Lifecycle](/docs/actors/lifecycle). + +### When state saves + +Mutating `c.state` schedules a save automatically. Rapid mutations are batched into a single write on a throttle (`stateSaveInterval`, default 1 second). Reads never trigger a save, saves aren't tied to action or handler boundaries, and state is also flushed when the actor sleeps or shuts down. + +To force a save mid-action, call `c.saveState()`: + +- `c.saveState({ immediate: true })` writes immediately and resolves once the write completes. +- `c.saveState()` schedules a throttled save and returns right away, without waiting for the write. + +Force an immediate save before a risky side effect so a crash can't lose progress: + +### Supported types + +State must be serializable. + +- `null`, `undefined`, `boolean`, `string`, `number`, `BigInt` +- `Date`, `RegExp`, `Error` +- `ArrayBuffer` and typed arrays (`Uint8Array`, `Int8Array`, `Float32Array`, etc.) +- `Map`, `Set`, `Array` +- Plain objects + +When data grows large or needs querying, store it in [Embedded SQLite](#embedded-sqlite) instead. + +## Ephemeral State + +`c.vars` holds data that exists only while the actor runs and is never saved. Use it for live objects that can't be serialized (connections, clients, emitters) or for data loaded from an external source. Most actors use both: `state` for durable data, `vars` for live objects. + +`createVars` runs on every actor start, unlike `createState` which runs once. That makes it the place to open connections and load data each time the actor wakes. + +### Runtime objects + +Build non-serializable objects in `createVars` and use them from actions: + +### Loading from external sources + +Create the connection pool once at module scope and share it across all actors, then use `createVars` (which can be `async`) to load this actor's data from it on each start: + +```typescript @nocheck +import { actor } from "rivetkit"; +import { Pool } from "pg"; + +// One shared pool for the whole process, not one per actor +const pool = new Pool({ connectionString: process.env.DATABASE_URL }); + +const profile = actor({ + state: { cachedName: "" }, + + createVars: async (c) => { + const { rows } = await pool.query("SELECT * FROM users WHERE id = $1", [c.key[0]]); + return { user: rows[0] }; + }, + + actions: { + updateEmail: async (c, email: string) => { + await pool.query("UPDATE users SET email = $1 WHERE id = $2", [email, c.key[0]]); + } + } +}); +``` + +When the actor owns its data, prefer [durable state](#durable-state) or [SQLite](#embedded-sqlite), which need no external infrastructure. + +### Cleanup + +`vars` is dropped when the actor stops, but per-actor resources like timers, subscriptions, and dedicated connections aren't cleaned up for you. Release them in `onSleep` and `onDestroy`. A shared pool stays open for the whole process, so don't close it per actor. + +```typescript @nocheck +const poller = actor({ + state: { ticks: 0 }, + + // Per-actor timer started on each wake + createVars: (c) => ({ timer: setInterval(() => c.state.ticks++, 5000) }), + + // Clear it before the actor sleeps or is destroyed + onSleep: (c) => clearInterval(c.vars.timer), + onDestroy: (c) => clearInterval(c.vars.timer), + + actions: { /* ... */ } +}); +``` + +## Embedded SQLite + +`c.db` is a SQLite database scoped to each actor and stored on disk. Use it for queryable, relational, or larger-than-memory data. Because compute and storage live together, queries run locally with no network round trips. + +A common pattern is to treat SQLite as the source of truth and keep a working copy in `c.vars`: load rows in `createVars`, serve reads from memory, and write changes back to `c.db`. + +```typescript @nocheck +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +const leaderboard = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS scores ( + player TEXT PRIMARY KEY, + score INTEGER NOT NULL + ); + `); + }, + }), + + // Load the table into memory once per start + createVars: async (c) => { + const rows = (await c.db.execute("SELECT player, score FROM scores")) as { + player: string; + score: number; + }[]; + return { scores: new Map(rows.map((r) => [r.player, r.score])) }; + }, + + actions: { + top: (c) => [...c.vars.scores].sort((a, b) => b[1] - a[1]).slice(0, 10), + + record: async (c, player: string, score: number) => { + c.vars.scores.set(player, score); + // Write through to SQLite + await c.db.execute( + "INSERT INTO scores (player, score) VALUES (?, ?) ON CONFLICT(player) DO UPDATE SET score = ?", + player, score, score, + ); + }, + }, +}); +``` + +For the full query API, schema migrations, transactions, and the Drizzle ORM, see: + +- [SQLite](/docs/actors/sqlite): raw SQL against the embedded per-actor database. +- [SQLite + Drizzle](/docs/actors/sqlite-drizzle): typed schema and query APIs. + +## Debugging + +- `GET /inspector/state` returns the actor's current state and `isStateEnabled`. +- `PATCH /inspector/state` lets you set state directly while debugging. +- In non-dev mode, inspector endpoints require authorization. + +## API Reference + +- [`CreateContext`](/typedoc/types/rivetkit.mod.CreateContext.html) - Context available during actor state creation +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - Context available throughout actor lifecycle +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining actors with state + +_Source doc path: /docs/actors/state_ diff --git a/.agents/skills/chat-room/reference/actors/statuses.md b/.agents/skills/chat-room/reference/actors/statuses.md new file mode 100644 index 0000000..cccf52a --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/statuses.md @@ -0,0 +1,36 @@ +# Actor Statuses + +> Source: `src/content/docs/actors/statuses.mdx` +> Canonical URL: https://rivet.dev/docs/actors/statuses +> Description: Understand the lifecycle statuses of Rivet Actors, what they mean, how they appear in the API, and how to troubleshoot common issues. + +--- +## Statuses + +These are the statuses you can see in the dashboard for each actor. + +| Status | Description | +|---|---| +| **Starting** | The actor has been created but has not yet become connectable. | +| **Running** | The actor is live and accepting connections. | +| **Destroyed** | The actor has been gracefully destroyed. | +| **Crashed** | The actor failed to start or encountered a fatal error. See [Troubleshooting](/docs/actors/troubleshooting#actor-status-is-crashed) for common failure reasons. | +| **Sleeping** | The actor has been put to sleep from inactivity. It will be woken up automatically when a new request arrives. | +| **Pending** | The actor is waiting to be allocated to a runner. This happens when no runner is available to handle the actor. See [Troubleshooting](/docs/actors/troubleshooting#actor-status-is-pending) for common causes. | +| **Crash Loop Backoff** | The actor failed to allocate and is waiting to retry with a backoff. This typically means repeated allocation failures. The backoff prevents overloading your infrastructure in the case of a widespread misconfiguration in your backend. See [Troubleshooting](/docs/actors/troubleshooting#actor-status-is-crashed) for common failure reasons. | + +## API Representation + +The actor object returned by the full engine API (used by the dashboard) includes the following timestamp fields used to derive status: + +| Field | Description | +|---|---| +| `createTs` | When the actor was first created. Always present. | +| `connectableTs` | When the actor became connectable. Null if not yet running. | +| `destroyTs` | When the actor was destroyed. | +| `sleepTs` | When the actor entered a sleeping state. | +| `pendingAllocationTs` | When the actor started waiting for an allocation. | +| `rescheduleTs` | When the actor will retry allocation after a failure. | +| `error` | Error details if the actor failed. | + +_Source doc path: /docs/actors/statuses_ diff --git a/.agents/skills/chat-room/reference/actors/testing.md b/.agents/skills/chat-room/reference/actors/testing.md new file mode 100644 index 0000000..5afe658 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/testing.md @@ -0,0 +1,51 @@ +# Testing + +> Source: `src/content/docs/actors/testing.mdx` +> Canonical URL: https://rivet.dev/docs/actors/testing +> Description: Rivet provides a straightforward testing framework to build reliable and maintainable applications. This guide covers how to write effective tests for your actor-based services. + +--- +## Setup + +To set up testing with Rivet: + +```bash +# Install Vitest +npm install -D vitest + +# Run tests +npm test +``` + +## Basic Testing Setup + +Rivet includes a test helper called `setupTest` that starts your registry in test mode and returns a client connected to it. This allows for fast, isolated tests without external dependencies. + +## Testing Actor State + +State persists within each test, allowing you to verify that your actor correctly maintains state between operations. + +## Testing Events + +For actors that emit events, you can verify events are correctly triggered by subscribing to them: + +## Testing Schedules + +Rivet's schedule functionality can be tested by scheduling work and waiting for it to run: + +Use a short real-time delay to wait for scheduled work to run. `setupTest` does not install fake timers, so if you want to use `vi.useFakeTimers()` you must enable it yourself and confirm it works with your selected runtime. + +## Best Practices + +1. **Isolate tests**: Each test should run independently, avoiding shared state. +2. **Test edge cases**: Verify how your actor handles invalid inputs, concurrent operations, and error conditions. +3. **Test scheduled operations**: Use short real-time delays to wait for scheduled work to run. +4. **Use realistic data**: Test with data that resembles production scenarios. + +`setupTest` starts the registry and disposes the returned client when the test finishes, so you can focus on writing effective tests for your business logic. + +## API Reference + +- [`setupTest`](/typedoc/functions/rivetkit.test_mod.setupTest.html) - Test setup helper function + +_Source doc path: /docs/actors/testing_ diff --git a/.agents/skills/chat-room/reference/actors/troubleshooting.md b/.agents/skills/chat-room/reference/actors/troubleshooting.md new file mode 100644 index 0000000..65b234d --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/troubleshooting.md @@ -0,0 +1,154 @@ +# Troubleshooting + +> Source: `src/content/docs/actors/troubleshooting.mdx` +> Canonical URL: https://rivet.dev/docs/actors/troubleshooting +> Description: Common issues with Rivet Actors and how to resolve them. + +--- +## Common Steps + +Before diving into specific errors, try these general troubleshooting steps: + +- Check your server logs for `level=ERROR` or `level=WARN` messages. +- Check if any of your backend processes have crashed or restarted unexpectedly. +- If you need more diagnostics, set `RIVET_LOG_LEVEL=DEBUG` for verbose logging. See [Logging](/docs/general/logging) for more options. + +## Reporting Issues + +If you're stuck, reach out on [Discord](https://rivet.dev/discord) or file an issue on [GitHub](https://github.com/rivet-dev/rivet/issues). + +When reporting, please include: + +- **Symptoms** + - Whether this is happening in local dev, deployed, or both + - The error you're seeing (screenshot or error message) + - Relevant source code related to the issue +- **What you've tried to solve it** +- **Environment** + - RivetKit version + - Runtime (Node, Bun, etc.) including version + - If applicable, provider in use (e.g. Vercel, Railway, Cloudflare) + - If applicable, HTTP router in use (e.g. Hono, Express, Elysia) + +## Actor status is crashed + +See [Actor Statuses](/docs/actors/statuses) for more about this status. + +The dashboard will show the specific failure reason. Common errors include: + +### `crashed` + +The actor's `run` handler threw an unhandled exception or exited unexpectedly. Check your actor logs for the error message and stack trace. + +### `no_capacity` + +No server was available to run your actor. The cause depends on your [runtime mode](/docs/general/runtime-modes): + +**Serverless**: + +- Your provider configuration does not have the region enabled that the actor is trying to run in. This is uncommon and usually only happens if an actor was created and then the provider config was updated to remove the region. +- There is an issue connecting to your backend. If the engine is hitting `/api/rivet/start` and failing, check your backend logs for errors. + +**Runners**: + +- You don't have enough runners online. Check your runner list in the dashboard to verify runners are visible and connected. +- Your runners are full. Each runner has a limited number of actor slots (configured via `RIVET_TOTAL_SLOTS`, default: 100,000). Check the dashboard to see if your runners have available capacity and scale up if needed. + +### `runner_no_response` + +The server running your actor did not respond in time. This can happen if your server is overloaded or experienced a network issue. Try restarting your server or checking its health. + +### `runner_connection_lost` + +The server running your actor lost its connection to Rivet. This is usually caused by a network interruption or your server restarting. + +### `runner_draining_timeout` + +Your server is shutting down and the actor did not finish in time. Consider handling graceful shutdown in your actor or increasing your shutdown timeout. + +### `concurrent_actor_limit_reached` + +The actor could not be allocated because the concurrent actor limit was reached. Reduce the number of concurrently running actors or increase your limit. + +### `no_envoys` + +No server was available to run your actor. This is equivalent to `no_capacity` on the current allocation path. See the `no_capacity` section above for the causes and fixes for your [runtime mode](/docs/general/runtime-modes). + +### `envoy_no_response` + +The server running your actor did not respond in time. This can happen if your server is overloaded or experienced a network issue. Try restarting your server or checking its health. + +### `envoy_connection_lost` + +The server running your actor lost its connection to Rivet. This is usually caused by a network interruption or your server restarting. + +### `serverless_http_error` + +Your serverless endpoint returned an HTTP error. Common causes: + +- Your backend is returning an error before the actor can start. Check your server logs. +- Your endpoint is behind authentication or a firewall that is blocking Rivet's requests. +- Your serverless function crashed during startup. Check your platform's function logs (e.g. Vercel, Cloudflare). + +### `serverless_connection_error` + +Rivet was unable to connect to your serverless endpoint. Check that: + +- Your backend is deployed and the endpoint URL is correct. +- Your server is publicly reachable from the internet. +- There are no DNS or firewall issues blocking the connection. + +### `serverless_stream_ended_early` + +The connection to your serverless endpoint was terminated before the actor finished. This usually means your serverless function hit its execution time limit. Ensure that your Rivet provider's request lifespan is configured to match the max duration of your serverless platform. + +### `serverless_invalid_sse_payload` + +Rivet received an unexpected response from your serverless endpoint. This typically means something is intercepting or modifying the request before it reaches your RivetKit handler. Check that: + +- Your server routes requests to `registry.start()`, `registry.serve()`, or `registry.handler()` correctly. +- No middleware is modifying the request or response body. + +### `internal_error` + +An unexpected error occurred within Rivet. If this persists, please [contact support](https://rivet.dev/docs). + +## Actors crashing immediately on startup + +If your actors are being created and then immediately destroyed or crashing, there is likely an error being thrown in your `createState` or `onCreate` lifecycle hooks. These hooks run during actor initialization before the actor is marked as ready. + +Check your server logs for the error message and stack trace. Common causes include: + +- An exception thrown in `createState` (e.g. invalid input, failed validation, or a runtime error when computing initial state) +- An exception thrown in `onCreate` (e.g. a failing external API call, missing configuration, or invalid setup logic) + +Fix the error in the relevant lifecycle hook and redeploy. + +## Actors not upgrading to new code + +If your actors are still running old code after deploying a new version, your [versioning](/docs/actors/versions) is likely not configured correctly. + +Without versioning, Rivet has no way to distinguish old deployments from new ones. The behavior depends on your [runtime mode](/docs/general/runtime-modes): + +- **Serverless**: Old requests may still be open from the previous deployment, so actors continue running on the old version's connection until those requests close. +- **Runners**: The old runner container is still running and will continue accepting new actors. New actors may be scheduled on the old runner instead of the new one. + +To fix this, configure a version number in your [registry configuration](/docs/general/registry-configuration). When a new version is deployed, Rivet will allocate new actors to the latest version and optionally drain old actors to migrate them. + +## Actor status is pending + +See [Actor Statuses](/docs/actors/statuses) for more about this status. + +An actor stays in "pending" status when Rivet is waiting for a server to accept it. The cause depends on your [runtime mode](/docs/general/runtime-modes): + +**Serverless**: + +- A region may have been removed from your provider configuration while an existing actor still lives in that region. The actor has no available server to start on because no provider serves that region anymore. Re-add the region to your provider config or destroy the affected actors. +- Check your backend logs for errors on the `/api/rivet/start` endpoint. + +**Runners**: + +- You don't have enough runners online. Check the dashboard to verify your runners are connected. +- Your runners may be at capacity. Check the dashboard to see if runners have available actor slots and scale up if needed. + +_Source doc path: /docs/actors/troubleshooting_ diff --git a/.agents/skills/chat-room/reference/actors/types.md b/.agents/skills/chat-room/reference/actors/types.md new file mode 100644 index 0000000..3e8f9b0 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/types.md @@ -0,0 +1,46 @@ +# Types + +> Source: `src/content/docs/actors/types.mdx` +> Canonical URL: https://rivet.dev/docs/actors/types +> Description: TypeScript types for working with Rivet Actors. This page covers context types used in lifecycle hooks and actions, as well as helper types for extracting types from actor definitions. + +--- +## Context Types + +Context types define what properties and methods are available in different parts of the actor lifecycle. + +### Extracting Context Types + +When writing helper functions that work with actor contexts, use context extractor types like `CreateContextOf` or `ActionContextOf` to extract the appropriate context type from your actor definition. + +### All Context Types + +Each lifecycle hook and handler has a corresponding `*ContextOf` type, exported from `"rivetkit"`. Pass `typeof myActor` as the type parameter. + +| Hook / Handler | Context Type | +|---|---| +| `createState` | `CreateContextOf` | +| `onCreate` | `CreateContextOf` | +| `createVars` | `CreateVarsContextOf` | +| `createConnState` | `CreateConnStateContextOf` | +| `onBeforeConnect` | `BeforeConnectContextOf` | +| `onConnect` | `ConnectContextOf` | +| `onDisconnect` | `DisconnectContextOf` | +| `onDestroy` | `DestroyContextOf` | +| `onMigrate` | `MigrateContextOf` | +| `onWake` | `WakeContextOf` | +| `onSleep` | `SleepContextOf` | +| `onStateChange` | `StateChangeContextOf` | +| `onBeforeActionResponse` | `BeforeActionResponseContextOf` | +| `actions.*` | `ActionContextOf` | +| `run` | `RunContextOf` | +| `workflow` orchestration helpers (root, `loop`, `try`, `race`, `join` branches) | `WorkflowContextOf` | +| `workflow` `step` / `tryStep` run + rollback helpers | `WorkflowStepContextOf` | +| `onRequest` | `RequestContextOf` | +| `onWebSocket` | `WebSocketContextOf` | + +`ActorContextOf`, `ConnContextOf`, and `ConnInitContextOf` are general-purpose base context types useful for helper functions that don't correspond to a specific hook. + +Workflow context extractors are exported from both `"rivetkit"` and `"rivetkit/workflow"`. + +_Source doc path: /docs/actors/types_ diff --git a/.agents/skills/chat-room/reference/actors/versions.md b/.agents/skills/chat-room/reference/actors/versions.md new file mode 100644 index 0000000..1b45129 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/versions.md @@ -0,0 +1,241 @@ +# Versions & Upgrades + +> Source: `src/content/docs/actors/versions.mdx` +> Canonical URL: https://rivet.dev/docs/actors/versions +> Description: When you deploy new code, Rivet ensures actors are upgraded seamlessly without downtime. + +--- +## How Versions Work + +Each runner has a **version number**. When you deploy new code with a new version, Rivet handles the transition automatically: + +- **New actors go to the newest version**: When allocating actors, Rivet always prefers runners with the highest version number +- **Multiple versions can coexist**: Old actors continue running on old versions while new actors are created on the new version +- **Drain old actors**: When enabled, a runner connecting with a newer version number will gracefully stop old actors to be rescheduled to the new version + +Versions are not configured by default. See [Registry Configuration](/docs/general/registry-configuration) to learn how to configure the runner version. + +`RIVET_ENVOY_VERSION` is only needed when self-hosting or using a custom runner. Rivet Compute handles versioning automatically. + +### Example Scenario + +### Drain Enabled + +When a new version is deployed, existing actors are gracefully stopped on the old runner and rescheduled onto the new version. + +```mermaid +sequenceDiagram + participant R1 as Runner v1 + participant R2 as Runner v2 + + Note over R1: Currently running + Note over R2: Deployed + R2->>R1: Drain old actors + R1->>R2: Reschedule actors + Note over R1: Shut down when all actors stopped +``` + +### Drain Disabled + +When a new version is deployed, both versions coexist. New actors are created on the new version while existing actors continue running on the old version until. + +```mermaid +sequenceDiagram + participant R1 as Runner v1 + participant R2 as Runner v2 + + Note over R1: Currently running + Note over R2: Deployed + Note over R1: Actor 1 sleeps from inactivity + Note over R2: Actor 1 wakes up when prompted +``` + +## Configuration + +### Setting the Version + +Configure the runner version using an environment variable or programmatically: + +```bash {{"title": "Environment Variable"}} +RIVET_ENVOY_VERSION=2 +``` + +The version **must** be set at build time, not at runtime. Do not use `Date.now()` or similar runtime values in your registry setup code. This would assign a different version every time the server starts, causing actors to be drained and rescheduled on every restart instead of only on new deployments. + +### Example Configurations + +We recommend injecting a build-time value that increments with every deployment. Here are concrete examples for common setups: + +### Dockerfile + +Generate the version at build time and bake it into the image as an environment variable: + +```bash @nocheck +docker build --build-arg RIVET_ENVOY_VERSION=$(date +%s) . +``` + +```dockerfile @nocheck +FROM node:20-slim +ARG RIVET_ENVOY_VERSION +ENV RIVET_ENVOY_VERSION=$RIVET_ENVOY_VERSION +WORKDIR /app +COPY . . +RUN npm install && npm run build +CMD ["node", "dist/server.js"] +``` + +All containers from this image will share the same version. + +### Next.js + +Set the version in `next.config.ts`. Next.js evaluates this file once at build time and inlines the value into the bundle: + +```typescript @nocheck +import type { NextConfig } from "next"; + +const nextConfig: NextConfig = { + env: { + RIVET_ENVOY_VERSION: String(Math.floor(Date.now() / 1000)), + }, +}; + +export default nextConfig; +``` + +### Vite + +Use `define` in your Vite config. This is evaluated once at build time and inlined into the bundle: + +```typescript @nocheck +import { defineConfig } from "vite"; + +export default defineConfig({ + define: { + "process.env.RIVET_ENVOY_VERSION": JSON.stringify( + String(Math.floor(Date.now() / 1000)) + ), + }, +}); +``` + +### CI/CD + +Set the version from your CI pipeline: + +```yaml @nocheck +# GitHub Actions +env: + RIVET_ENVOY_VERSION: ${{ github.run_number }} +``` + +```bash @nocheck +# Railway / Render / generic CI +export RIVET_ENVOY_VERSION=$(date +%s) +``` + +```bash @nocheck +# Git commit count +export RIVET_ENVOY_VERSION=$(git rev-list --count HEAD) +``` + +### Build Script + +Generate a version file during your build step and import it: + +```json @nocheck +{ + "scripts": { + "build": "echo \"export const BUILD_VERSION = $(date +%s);\" > src/build-version.ts && tsc" + } +} +``` + +```typescript @nocheck +import { actor, setup } from "rivetkit"; +import { BUILD_VERSION } from "./build-version"; + +const myActor = actor({ state: {}, actions: {} }); + +const registry = setup({ + use: { myActor }, + envoy: { + version: BUILD_VERSION, + }, +}); +``` + +### Drain on Version Upgrade + +The `drainOnVersionUpgrade` option controls whether old actors are stopped when a new version is deployed. This is configured in the Rivet dashboard under your runner configuration. See [Pool Configuration](/docs/general/pool-configuration) for the full set of pool options, including how to rate-limit actor eviction during the drain. + +| Value | Behavior | +|-------|----------| +| `false` | Old actors continue running. New actors go to new version. Versions coexist. | +| `true` (default) | Old actors receive stop signal and have 30m to finish gracefully. | + +## Upgrading Actor State + +When you deploy a new version, existing actors may need to handle schema changes in their persisted data. + +### SQLite (recommended for complex schemas) + +**Drizzle (recommended)** + +Use [Drizzle](/docs/actors/sqlite-drizzle) for typed schemas with generated migrations. Drizzle generates versioned `.sql` migration files from your TypeScript schema and applies them in order automatically. This is the recommended approach when your schema evolves frequently. + +**Raw SQL** + +For actors using [raw SQLite](/docs/actors/sqlite), migrations run automatically via the `onMigrate` hook on every actor start. RivetKit wraps the hook in a SQLite savepoint, so the migration is fully atomic. Use SQLite's `user_version` pragma to track which migrations have run: + +### In-memory state (`c.state`) + +If you use `c.state` for persistence, you are responsible for handling schema changes yourself. If you add, remove, or rename fields between versions, your code must handle the old shape gracefully. + +**Manual defaults in `onWake`** + +Apply defaults for missing fields: + +**Zod schema coercion** + +Use [Zod](https://zod.dev/) to parse persisted state on wake. Zod's `.default()` fills in missing fields automatically, so old actor state is coerced to the current schema: + +For anything beyond simple defaults, consider moving to [SQLite](/docs/actors/sqlite) where you get proper migration tooling. + +## Advanced + +### How Version Upgrade Detection Works + +When `drainOnVersionUpgrade` is enabled, Rivet uses two mechanisms to detect version changes: + +- **New runner connection**: When a runner connects with a newer version number, the engine immediately drains all older runners with the same name. This is the primary mechanism for [runner mode](/docs/general/runtime-modes) deployments. +- **Metadata polling** (serverless only): In [serverless mode](/docs/general/runtime-modes), runners periodically poll the engine to check for newer versions and self-drain if one is found. This ensures old runners drain even if no new requests trigger a runner connection. + +### SIGTERM Handling + +When a runner process receives SIGTERM, it gracefully stops all actors before exiting: + +- Each actor's `onSleep` hook is called, giving it time to save state +- Actors are rescheduled to other available runners +- The runner waits up to **30 minutes** for all actors to finish stopping +- If the process is force-killed before actors finish (e.g. SIGKILL), actors are rescheduled with a crash backoff penalty instead of a clean handoff + +Actors have a maximum of 30 minutes to clean up during shutdown. Ensure your platform's drain grace period is at most 30 minutes. + +### Shutdown Timeouts + +Several timeouts control how long each part of the shutdown process can take: + +| Timeout | Default | Description | Configuration | +|---------|---------|-------------|---------------| +| `actor_stop_threshold` | 30m | Engine-side limit on how long each actor has to stop before being marked lost | [Engine config](/docs/self-hosting/configuration) (`pegboard.actor_stop_threshold`) | +| `sleepGracePeriod` | 15s | Total graceful sleep budget for `onSleep`, `waitUntil`, `keepAwake`, and async raw WebSocket handlers | [Actor options](/docs/actors/lifecycle#options) | +| `runner_lost_threshold` | 15s | Fallback detection if the runner dies without graceful shutdown | [Engine config](/docs/self-hosting/configuration) (`pegboard.runner_lost_threshold`) | + +Rivet has a max shutdown grace period of 30 minutes that cannot be configured. + +## Related + +- [Runtime Modes](/docs/general/runtime-modes): Serverless vs runner deployment modes +- [Lifecycle](/docs/actors/lifecycle): Actor lifecycle hooks including `onSleep` + +_Source doc path: /docs/actors/versions_ diff --git a/.agents/skills/chat-room/reference/actors/websocket-handler.md b/.agents/skills/chat-room/reference/actors/websocket-handler.md new file mode 100644 index 0000000..f94499d --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/websocket-handler.md @@ -0,0 +1,201 @@ +# Low-Level WebSocket Handler + +> Source: `src/content/docs/actors/websocket-handler.mdx` +> Canonical URL: https://rivet.dev/docs/actors/websocket-handler +> Description: Actors can handle WebSocket connections through the `onWebSocket` handler. + +--- +For most use cases, [actions](/docs/actors/actions) and [events](/docs/actors/events) provide high-level connection handling powered by WebSockets that's easier to work with than low-level WebSockets. However, low-level handlers are required when implementing custom use cases. + +## Handling WebSocket Connections + +The `onWebSocket` handler manages low-level WebSocket connections. It receives the actor context and a `WebSocket` object. + +See also the [raw WebSocket handler example](https://github.com/rivet-dev/rivet/tree/main/examples/raw-websocket-handler). + +## Connecting To Actors + +### Via RivetKit Client + +Use the `.webSocket()` method on an actor handle to open a WebSocket connection to the actor's `onWebSocket` handler. This can be executed from either your frontend or backend. + +```typescript index.ts @hide @nocheck +import { actor, setup } from "rivetkit"; + +export const chat = actor({ + state: { messages: [] as string[] }, + onWebSocket: (c, websocket) => { + websocket.addEventListener("message", (event) => { + c.state.messages.push(event.data as string); + }); + }, + actions: {} +}); + +export const registry = setup({ use: { chat } }); +registry.start(); +``` + +```typescript client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +const actor = client.chat.getOrCreate(["my-chat"]); + +// Open WebSocket connection +const ws = await actor.webSocket("/"); + +// Listen for messages +ws.addEventListener("message", (event) => { + const message = JSON.parse(event.data as string); + console.log("Received:", message); +}); + +// Send messages +ws.send(JSON.stringify({ type: "chat", text: "Hello!" })); +``` + +The `.webSocket()` method returns a standard WebSocket. + +### Via getGatewayUrl + +Use `.getGatewayUrl()` to get the raw gateway URL for the actor. This is useful when you need to use the URL with external tools or custom WebSocket clients. + +```typescript index.ts @hide @nocheck +import { actor, setup } from "rivetkit"; + +export const chat = actor({ + state: { messages: [] as string[] }, + onWebSocket: (c, websocket) => { + websocket.addEventListener("message", (event) => { + c.state.messages.push(event.data as string); + }); + }, + actions: {} +}); + +export const registry = setup({ use: { chat } }); +registry.start(); +``` + +```typescript client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +const actor = client.chat.getOrCreate(["my-chat"]); + +// Get the raw gateway URL +const gatewayUrl = await actor.getGatewayUrl(); +// gatewayUrl = "https://...rivet.dev/..." + +// Convert to WebSocket URL and connect +const wsUrl = gatewayUrl.replace("http://", "ws://").replace("https://", "wss://"); +const ws = new WebSocket(`${wsUrl}/websocket/`); + +ws.addEventListener("message", (event) => { + const message = JSON.parse(event.data as string); + console.log("Received:", message); +}); + +ws.addEventListener("open", () => { + ws.send(JSON.stringify({ type: "chat", text: "Hello!" })); +}); +``` + +### Via HTTP API + +This handler can be accessed with raw WebSockets using `wss://api.rivet.dev/gateway/{actorId}@{token}/websocket/{...path}`. + +For example, to connect to the chat actor above: + +```typescript +// Replace with your actor ID and token +const actorId = "your-actor-id"; +const token = "your-token"; + +const ws = new WebSocket( + `wss://api.rivet.dev/gateway/${actorId}@${token}/websocket/` +); + +ws.addEventListener("message", (event) => { + const message = JSON.parse(event.data as string); + console.log("Received:", message); +}); + +ws.addEventListener("open", () => { + ws.send(JSON.stringify({ type: "chat", text: "Hello!" })); +}); +``` + +```bash +wscat -c "wss://api.rivet.dev/gateway/{actorId}@{token}/websocket/" +``` + +The path after `/websocket/` is passed to your `onWebSocket` handler and can be used to route to different functionality within your actor. For example, to connect with a custom path `/admin`: + +```typescript +// Replace with your actor ID and token +const actorId = "your-actor-id"; +const token = "your-token"; + +const ws = new WebSocket( + `wss://api.rivet.dev/gateway/${actorId}@${token}/websocket/admin` +); +``` + +```bash +wscat -c "wss://api.rivet.dev/gateway/{actorId}@{token}/websocket/admin" +``` + +See the [HTTP API reference](/docs/actors/http-api) for more information on WebSocket routing and authentication. + +### Via Proxying Connections + +You can proxy WebSocket connections from your own server to actor handlers using the RivetKit client. This is useful when you need to add custom authentication or connection management before forwarding to actors. + +See also the [raw WebSocket handler with proxy example](https://github.com/rivet-dev/rivet/tree/main/examples/raw-websocket-handler-proxy). + +## Connection & Lifecycle Hooks + +`onWebSocket` will trigger the `onBeforeConnect`, `onConnect`, and `onDisconnect` hooks. Read more about [lifecycle hooks](/docs/actors/lifecycle). + +Open WebSockets will be listed in `c.conns`. `conn.send` and `c.broadcast` have no effect on low-level WebSocket connections. Read more about [connections](/docs/actors/connections). + +## WinterTC Compliance + +The `onWebSocket` handler uses standard WebSocket APIs and will work with existing libraries expecting WinterTC-compliant WebSocket objects. + +## Advanced + +## WebSocket Hibernation + +WebSocket hibernation allows actors to go to sleep while keeping WebSocket connections alive. Actors automatically wake up when a message is received or the connection closes. + +Enable hibernation by setting `canHibernateWebSocket: true`. You can also pass a function `(request) => boolean` for conditional control. + +Since `open` only fires once when the client first connects, use `c.conn.state` to store per-connection data that persists across sleep cycles. See [connections](/docs/actors/connections) for more details. + +### Accessing the Request + +The underlying HTTP request is available via `c.request`. This is useful for accessing the path or query parameters. + +### Skip Ready Wait + +Connections are normally held at the gateway until the actor is ready. Pass `skipReadyWait: true` on `handle.webSocket()` to connect immediately, including while the actor is still starting or in the [sleep grace period](/docs/actors/lifecycle#shutdown-sequence). See [Skip Ready Wait](/docs/clients/javascript#skip-ready-wait) for details. + +### Async Handlers + +The `onWebSocket` handler can be async, allowing you to perform async code before setting up event listeners: + +## API Reference + +- [`WebSocketContext`](/typedoc/interfaces/rivetkit.mod.WebSocketContext.html) - Context for WebSocket handlers +- [`UniversalWebSocket`](/typedoc/interfaces/rivetkit.mod.UniversalWebSocket.html) - Universal WebSocket interface +- [`handleRawWebSocketHandler`](/typedoc/functions/rivetkit.mod.handleRawWebSocketHandler.html) - Function to handle raw WebSocket +- [`UpgradeWebSocketArgs`](/typedoc/interfaces/rivetkit.mod.UpgradeWebSocketArgs.html) - Arguments for WebSocket upgrade + +_Source doc path: /docs/actors/websocket-handler_ diff --git a/.agents/skills/chat-room/reference/actors/workflows.md b/.agents/skills/chat-room/reference/actors/workflows.md new file mode 100644 index 0000000..9c59975 --- /dev/null +++ b/.agents/skills/chat-room/reference/actors/workflows.md @@ -0,0 +1,228 @@ +# Workflows + +> Source: `src/content/docs/actors/workflows.mdx` +> Canonical URL: https://rivet.dev/docs/actors/workflows +> Description: Build durable, replayable run loops in Rivet Actors with steps, queue waits, timers, and rollback. + +--- +Use workflows for durable, multi-step execution with replay safety. + +## What are workflows? + +A workflow is a durable, replayable run handler for a Rivet Actor. + +- Survives restarts: workflow progress is saved automatically. +- Re-runs safely: replay follows the same recorded steps. +- Event-driven: workflows can pause for queue messages, then continue. + +## Getting started + +### Simple workflow + +Use this when you need a short multi-step sequence. + +### Loops + +This is the recommended workflow shape for most actor workloads. + +- Use a queue wait inside the loop to receive the next unit of work. +- Keep actor state changes in a single workflow loop. +- This gives you one durable workflow that manages all actor progress. + +### Setup & teardown + +Use this when the workflow should initialize resources, process queued commands, then clean up. + +## Features + +### Queue + +Use this for fire-and-forget commands where the client does not need a reply. + +Use the `Loops` example above as the baseline pattern. + +### Request/response (using queue) + +Use this when the caller needs a response from queued processing. + +### Timers + +Use queue messages as the trigger source, then sleep durably inside the workflow. + +### Join + +Use `join` when several independent tasks can run in parallel. + +### Race + +Use `race` when you need first-winner behavior. + +### Timeouts + +Use step timeouts and retries for slow or flaky dependencies. + +Step timeouts are critical by default and fail immediately. Set `retryOnTimeout: true` if a timeout should retry like any other error using `maxRetries`. + +Workflows use roll-forward semantics everywhere. When a step throws, any `state` or `vars` mutations it made before failing are never rolled back, whether the step retries or the failure is caught by `tryStep` or `try`. The next attempt observes whatever the failed attempt already wrote, so write steps idempotently: check before you increment, or move the mutation after the fallible work. + +### Handling terminal failures as data + +Use `tryStep` when a step failure should produce data instead of failing the whole workflow. + +Use `try` when you want to recover from terminal `step`, `join`, or `race` failures inside a named block. + +```ts +async function runPaymentFlow(ctx: any) { + return await ctx.try("payment-flow", async (blockCtx: any) => { + const auth = await blockCtx.step("authorize", async (blockCtx) => + authorizeOrder("order-123"), + ); + const capture = await blockCtx.step("capture", async (blockCtx) => + captureOrder("order-123"), + ); + return { auth, capture }; + }); +} + +async function authorizeOrder(orderId: string): Promise { + return `auth-${orderId}`; +} + +async function captureOrder(orderId: string): Promise { + return `capture-${orderId}`; +} +``` + +- `tryStep` and `try` only catch terminal failures. Retry backoff, sleeps, queue waits, eviction, and history divergence still rethrow. +- Catching a failure does not undo it. `state` and `vars` mutations made before the failure remain visible after `tryStep` or `try` returns, so use explicit compensating steps when a caught failure needs cleanup. +- `RollbackError` is not caught by default. Pass `catch: ["rollback"]` when you want rollback failures returned as data. + +### Error hooks + +Use `onError` when you want a best-effort notification for workflow failures. + +- Step failures include the attempt number, retry counts, whether the step will retry, and the next retry delay. +- Workflow failures also include terminal errors outside steps, such as rollback failures or code/history mismatches. +- The hook is observational. It is not part of workflow replay, so use it for logging, metrics, or updating non-critical actor state. +- This is also a good place to forward workflow failures to Sentry or another error reporting pipeline. + +### Rollback + +Use rollback checkpoints before steps that have compensating actions. + +## Patterns + +### Store workflow progress in state + broadcast + +Store progress in `state` so replay and recovery always restore it. Broadcast state changes so clients can render progress in realtime. + +### Cron (queue-driven) + +Rivet scheduling triggers actions. For cron-like workflows, use a small scheduled action as a bridge that enqueues work, then process that work in the workflow loop. + +These are common workflow shapes used in production systems. + +### Queue-driven worker + +Use this when external systems enqueue work and the actor should process each item durably. + +### Setup & teardown + +Use this when you need one-time initialization before a long-lived loop, plus cleanup when the actor stops sleeping or is destroyed. + +### Human approval gate + +Use this when an operation must pause for a user or system decision before continuing. + +### Fan-out / fan-in (join) + +Use this when independent work items can run in parallel and you need a single merged result. + +### Batch drainer + +Use this when throughput matters and handling one message at a time is too expensive. + +### Coordinator -> worker RPC + +Use this when one actor orchestrates work by calling actions on other actors. + +### Request/response over queue (async RPC) + +Use this when you want decoupled actor-to-actor communication with durable waits and explicit completion. + +### Scatter-gather across actors + +Use this when multiple actors can process independent parts of a request in parallel, then return a merged response. + +### Timeout + fallback actor + +Use this when a primary actor call might be slow or unavailable and you need a deterministic fallback path. + +### Cross-actor saga (compensating actions) + +Use this when a workflow spans multiple actors and each side effect may need compensation. + +### Signal-driven control loop + +Use this when workflow progress should be triggered by commands/events instead of fixed polling intervals. + +### Poll + backoff loop + +Use this when an external dependency has variable availability and retries should slow down after failures. + +### Child worker orchestration + +Use this when one workflow coordinates many child workers (actors or worker workflows) and manages their lifecycle. + +### Bounded drain + concurrency cap + +Use this when inbound work can spike and you need predictable per-iteration limits. + +### Versioned workflow evolution + +Use this when workflow structure changes across deployments and old histories must still replay. + +### Version gates with `getVersion` + +Use `ctx.getVersion(name, latest)` to branch behavior when you change a workflow's logic while old instances are still in flight. It returns the version this instance is pinned to at that point: + +- A fresh instance resolves to `latest`. +- An instance that already executed past this point under older code resolves to `1` (the implicit floor). + +The resolved version is recorded in history, so replays are deterministic and each instance stays on the branch it started on. Inside a loop, every iteration resolves independently, so in-flight iterations finish on the old branch while new iterations pick up `latest`. + +`latest` must be an integer `>= 1`, and the gate name must be unique within its scope like any other entry. Once every old instance has drained, retire the gate by replacing the call with `ctx.removed(name, "version_check")`. + +### Checkpoint-friendly loop design + +Use this when you need reliable replay and resume semantics across crashes and restarts. + +## Migrations + +- Keep workflow entry names stable once deployed. +- If an old entry was removed or renamed, call `ctx.removed(name, originalType)`. +- To change behavior at a point while old instances are still running, gate it with `ctx.getVersion(name, latest)` (see [Version gates](#version-gates-with-getversion)). +- This keeps replay compatible across deployments. + +## Step-only access to actor APIs + +`state`, `vars`, `db`, `client()`, and connection/event APIs are only valid inside `ctx.step(...)` callbacks. + +Use non-step workflow code for orchestration only: queue waits, sleeps, loops, joins, races, and rollback boundaries. Keep actor-local side effects in steps. + +## Debugging + +- `GET /inspector/workflow-history` returns workflow history status for an actor. +- Response includes `isWorkflowEnabled` and `history`. +- In non-dev mode, inspector endpoints require authorization. + +## Recommendations + +- Prefer queue-driven loops for long-lived workflows. +- Structure long-lived workflows with setup and teardown around the main loop. +- Keep actor state changes and side effects inside steps. +- Store workflow progress in `state` and broadcast updates as progress changes. +- Use timeouts and rollback for external side effects. +- Write step bodies idempotently. `state` and `vars` mutations from a failed attempt are never rolled back, whether the step retries or `tryStep`/`try` catches the failure. + +_Source doc path: /docs/actors/workflows_ diff --git a/.agents/skills/chat-room/reference/cli.md b/.agents/skills/chat-room/reference/cli.md new file mode 100644 index 0000000..34880ea --- /dev/null +++ b/.agents/skills/chat-room/reference/cli.md @@ -0,0 +1,103 @@ +# CLI + +> Source: `src/content/docs/cli.mdx` +> Canonical URL: https://rivet.dev/docs/cli +> Description: Reference for the optional rivet CLI: deploy to Rivet Compute and run local dev for serverless platforms. + +--- +The `rivet` CLI (`@rivetkit/cli`) is optional. You only need it for: + +| Use case | Command | +| --- | --- | +| Deploy to Rivet Compute | `rivet deploy` | +| Local dev for serverless platforms (Cloudflare, Supabase) | `rivet dev --provider ` | + +Run it with your package runner: + +```bash +npx @rivetkit/cli +``` + +| Command | Description | +| --- | --- | +| `rivet dev` | Run a local engine and your handler's dev server. | +| `rivet deploy` | Build and deploy the project to Rivet Cloud. | +| `rivet engine` | Run the bundled `rivet-engine` binary directly. | +| `rivet setup-ci` | Install the GitHub Actions deploy workflow. | + +## `rivet dev` + +Starts a local engine, spawns your dev server, and registers the serverless runner pointing at it. The engine keeps running across restarts; Ctrl-C stops only the dev server. + +```bash +rivet dev [--provider ] [--port N] [--fn-name NAME] [--url URL] [-- ...] +``` + +`--provider` selects how the dev server is launched. Anything after `--` is appended to the preset command (or is the command to run when no provider is set). + +| `--provider` | Spawns | Port | +| --- | --- | --- | +| _(omitted)_ | your `-- ` (needs `--port`) | from `--port` | +| `serverless` | your `-- ` (gets `PORT`) | auto | +| `cloudflare` | `wrangler dev` | `8787` | +| `supabase` | `supabase functions serve` | `54321` | +| `none` | nothing (engine only) | — | + +For `cloudflare`, the CLI also passes the engine endpoint as `--var RIVET_ENDPOINT:...`, so the Worker connects back with no `wrangler.toml` config. + +| Flag | Description | +| --- | --- | +| `--port` | Handler port. Required without a provider unless `--url` is set. | +| `--fn-name` | Supabase function name (default `rivet`). | +| `--url` | Explicit handler URL, overriding port and path. | +| `--engine-binary` | Path to a `rivet-engine` binary. | + +## `rivet deploy` + +Builds and pushes your project's Docker image and upserts the managed pool, printing the dashboard URL. See [Deploying to Rivet Compute](/docs/deploy/rivet-compute). + +```bash +rivet deploy --token cloud_api_xxxxx +``` + +The token is saved to `~/.rivet/credentials` (also read from `RIVET_CLOUD_TOKEN`), so later deploys can omit it. + +| Flag | Default | Description | +| --- | --- | --- | +| `--token` | env / credentials | Rivet Cloud API token. | +| `--namespace` | `production` | Cloud namespace. | +| `--project` / `--org` | from token | Override project/org. | +| `--dockerfile` | `Dockerfile` | Dockerfile to build. | +| `--build-context` | `.` | Docker build context. | +| `--env KEY=VAL` | — | Environment override, repeatable. | +| `--image` | project slug | Image repository name. | +| `--tag` | git short SHA | Image tag. | + +## `rivet engine` + +Runs the bundled `rivet-engine` binary directly, against the same local database and ports as `rivet dev`. Arguments are forwarded verbatim. + +```bash +rivet engine nuke # wipe local engine state +rivet engine wf list # inspect workflows +``` + +## `rivet setup-ci` + +Installs `.github/workflows/rivet-deploy.yml`, which deploys to Rivet Cloud on push and pull request. Add `--force` to overwrite. Then set the token secret: + +```bash +gh secret set RIVET_CLOUD_TOKEN +``` + +## Engine binary resolution + +`rivet dev` and `rivet engine` resolve the `rivet-engine` binary from, in order: `--engine-binary`, `RIVET_ENGINE_BINARY_PATH`, a binary bundled next to the CLI, a local `target/{debug,release}` build, then an auto-downloaded release. Set `RIVETKIT_ENGINE_AUTO_DOWNLOAD=0` to require a local binary. + +## Related + +- [Deploying to Rivet Compute](/docs/deploy/rivet-compute) +- [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) +- [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) + +_Source doc path: /docs/cli_ diff --git a/.agents/skills/chat-room/reference/clients/javascript.md b/.agents/skills/chat-room/reference/clients/javascript.md new file mode 100644 index 0000000..689d79b --- /dev/null +++ b/.agents/skills/chat-room/reference/clients/javascript.md @@ -0,0 +1,120 @@ +# Node.js & Bun + +> Source: `src/content/docs/clients/javascript.mdx` +> Canonical URL: https://rivet.dev/docs/clients/javascript +> Description: Connect JavaScript apps to Rivet Actors. + +--- +## Getting Started + +See the [backend quickstart guide](/docs/actors/quickstart/backend) for getting started. + +## Minimal Client + +## Stateless vs Stateful + +## Getting Actors + +## Connection Parameters + +Use `params` for static connection parameters. Use `getParams` when the value can change between connection attempts, such as refreshing a JWT before each `.connect()` or reconnect. + +## Subscribing to Events + +## Connection Lifecycle + +## Low-Level HTTP & WebSocket + +For actors that implement `onRequest` or `onWebSocket`, call them directly: + +```ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("history"); +const history = await response.json(); + +const ws = await handle.webSocket("stream"); +ws.addEventListener("message", (event) => { + console.log("message:", event.data); +}); +ws.send("hello"); +``` + +## Calling from Backend + +## Error Handling + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`createClient()` automatically reads: + +- `RIVET_ENDPOINT` (endpoint) +- `RIVET_NAMESPACE` +- `RIVET_TOKEN` +- `RIVET_RUNNER` + +Defaults to `http://localhost:6420` when unset. RivetKit runs on port 6420 by default. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, use your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## Advanced + +### Skip Ready Wait + +Requests are normally held at the gateway until the actor is ready to accept traffic. An actor is not ready while it's still starting (before `onWake` finishes) or while it's in the [sleep grace period](/docs/actors/lifecycle#shutdown-sequence) (running `onSleep`, `waitUntil`, and pending disconnects). + +Pass `skipReadyWait: true` on the [low-level HTTP and WebSocket APIs](#low-level-http--websocket) to deliver immediately and reach the actor's `onRequest` / `onWebSocket` handler in either window: + +```ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("/healthz", { + skipReadyWait: true, +}); + +const ws = await handle.webSocket("probe", undefined, { + skipReadyWait: true, +}); +``` + +Requests can still return transient lifecycle or gateway errors. Retry once the actor is available again. + +- `actor.stopping`: the actor has fully stopped, i.e. the sleep grace period has ended but it has not yet restarted. +- `guard.actor_stopped_while_waiting`: the request reached the actor tunnel, but the actor stopped before the gateway received a response. +- `guard.tunnel_request_aborted`: the actor tunnel aborted the request before a response started. +- `guard.tunnel_message_timeout`: the gateway dropped the in-flight tunnel request after its tunnel message timeout. +- `guard.tunnel_response_closed`: the actor tunnel closed before sending a response. +- `guard.gateway_response_start_timeout`: the gateway timed out waiting for the actor response to start. + +## API Reference + +**Package:** [rivetkit](https://www.npmjs.com/package/rivetkit) + +See the [RivetKit client overview](/docs/clients). + +- [`createClient`](/typedoc/functions/rivetkit.client_mod.createClient.html) - Create a client +- [`Client`](/typedoc/types/rivetkit.mod.Client.html) - Client type + +_Source doc path: /docs/clients/javascript_ diff --git a/.agents/skills/chat-room/reference/clients/react.md b/.agents/skills/chat-room/reference/clients/react.md new file mode 100644 index 0000000..9b976e2 --- /dev/null +++ b/.agents/skills/chat-room/reference/clients/react.md @@ -0,0 +1,88 @@ +# React + +> Source: `src/content/docs/clients/react.mdx` +> Canonical URL: https://rivet.dev/docs/clients/react +> Description: Connect React apps to Rivet Actors. + +--- +## Getting Started + +See the [React quickstart guide](/docs/actors/quickstart/react) for getting started. + +## Install + +## Minimal Client + +## Stateless vs Stateful + +## Getting Actors + +## Connection Parameters + +## Subscribing to Events + +## Connection Lifecycle + +## Low-Level HTTP & WebSocket + +Use the JavaScript client for raw HTTP and WebSocket access: + +```tsx @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("history"); +const history = await response.json(); + +const ws = await handle.webSocket("stream"); +ws.addEventListener("message", (event) => { + console.log("message:", event.data); +}); +ws.send("hello"); +``` + +## Calling from Backend + +Use the JavaScript client on your backend (Node.js/Bun). See the [JavaScript client docs](/docs/clients/javascript). + +## Error Handling + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`createRivetKit()` (and the underlying `createClient()` instance) automatically read: + +- `RIVET_ENDPOINT` +- `RIVET_NAMESPACE` +- `RIVET_TOKEN` +- `RIVET_RUNNER` + +Defaults to `http://localhost:6420` when unset. RivetKit runs on port 6420 by default. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, use your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## API Reference + +**Package:** [@rivetkit/react](https://www.npmjs.com/package/@rivetkit/react) + +- [`createRivetKit`](/docs/clients/react) - Create hooks for React +- [`useActor`](/docs/clients/react) - Hook for actor instances + +_Source doc path: /docs/clients/react_ diff --git a/.agents/skills/chat-room/reference/clients/rust.md b/.agents/skills/chat-room/reference/clients/rust.md new file mode 100644 index 0000000..32bebfc --- /dev/null +++ b/.agents/skills/chat-room/reference/clients/rust.md @@ -0,0 +1,367 @@ +# Rust (Beta) + +> Source: `src/content/docs/clients/rust.mdx` +> Canonical URL: https://rivet.dev/docs/clients/rust +> Description: Connect Rust apps to Rivet Actors. + +--- +Rust support is in beta. The supported public Rust API is `rivetkit` and `rivetkit::client`; lower-level crates are internal implementation details and do not carry a stability guarantee. See the full API reference on [docs.rs/rivetkit](https://docs.rs/rivetkit), or the runnable [`hello-world-rust`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-rust) example. + +## Getting Started + +See the [Rust quickstart guide](/docs/actors/quickstart/rust) for getting started. + +## Install + +Add the `rivetkit` crate and its companions: + +```sh +cargo add rivetkit anyhow async-trait +cargo add serde --features derive +cargo add tokio --features full +``` + +The Rust client is strongly typed. It shares the same action and event types as your actor, so define your actor in `src/lib.rs` and import those types from both your server and your client. There is no need to redefine the actor on the client. See [Define Your Actor](/docs/actors/quickstart/rust#define-your-actor) in the quickstart for the actor definition this page builds on. + +## Minimal Client + +```rust @nocheck +use counter::{Counter, Increment}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + let count = counter.send(Increment { amount: 1 }).await?; + println!("New count: {count}"); + + Ok(()) +} +``` + +`counter` here is your crate name (the package `name` in `Cargo.toml`, with dashes as underscores). `Counter` and `Increment` are the types you defined alongside your actor. + +## Stateless vs Stateful + +```rust @nocheck +use counter::{Counter, Increment, NewCount}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + + // Stateless: each call is independent + counter.send(Increment { amount: 1 }).await?; + + // Stateful: keep a connection open for realtime events + let connection = counter.connect(); + connection + .on::(|event| println!("count: {}", event.count)) + .await; + connection.send(Increment { amount: 1 }).await?; + + connection.disconnect().await; + Ok(()) +} +``` + +A stateless call on the handle opens a short-lived request per action. A connection keeps a WebSocket open so you can receive events and reuse it across calls. + +## Getting Actors + +```rust @nocheck +use counter::Counter; +use rivetkit::{ + client::{Client, ClientConfig, GetOrCreateOptions}, + prelude::*, + TypedClientExt, +}; +use serde_json::json; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + // Get or create an actor + let room = client.get_or_create_typed_default::("counter", ["room-42"])?; + + // Get an existing actor handle (fails when used if the actor does not exist) + let existing = client.get_typed_default::("counter", ["room-42"])?; + + // Create a new actor with input + let created = client.get_or_create_typed::( + "counter", + ["game-1"], + GetOrCreateOptions { + create_with_input: Some(json!({ "mode": "ranked" })), + ..Default::default() + }, + )?; + + // Get an actor handle by ID + let by_id = client.get_for_id("counter", "actor-id", Default::default())?; + + // Resolve the actor ID + let resolved_id = room.inner().resolve().await?; + println!("Resolved ID: {resolved_id}"); + + Ok(()) +} +``` + +`get_typed_default` / `get_or_create_typed_default` use default options. The non-default variants (`get_typed` / `get_or_create_typed`) take `GetOptions` / `GetOrCreateOptions` for connection parameters, input, and region. + +## Connection Parameters + +Pass connection parameters through the handle options. They are delivered to the actor's `create_conn_state` callback: + +```rust @nocheck +use counter::Counter; +use rivetkit::{ + client::{Client, ClientConfig, GetOrCreateOptions}, + prelude::*, + TypedClientExt, +}; +use serde_json::json; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + let chat = client.get_or_create_typed::( + "counter", + ["general"], + GetOrCreateOptions { + params: Some(json!({ "authToken": "jwt-token-here" })), + ..Default::default() + }, + )?; + + let connection = chat.connect(); + connection.disconnect().await; + Ok(()) +} +``` + +## Subscribing to Events + +`on` registers a typed callback for an event and returns once the subscription is registered: + +```rust @nocheck +use counter::{Counter, NewCount}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let connection = client + .get_or_create_typed_default::("counter", ["general"])? + .connect(); + + connection + .on::(|event| println!("count changed: {}", event.count)) + .await; + + Ok(()) +} +``` + +Event callbacks are synchronous and run for every matching event. The actor's emitted event type (here `NewCount`) is decoded into the typed value for you. + +## Connection Lifecycle + +The lower-level connection exposes lifecycle callbacks and the current status. Reach it with `connection.inner()`: + +```rust @nocheck +use counter::Counter; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let connection = client + .get_or_create_typed_default::("counter", ["general"])? + .connect(); + let inner = connection.inner().clone(); + + inner.on_open(|| println!("connected")).await; + inner.on_close(|| println!("disconnected")).await; + inner.on_error(|message| eprintln!("error: {message}")).await; + inner + .on_status_change(|status| println!("status: {status:?}")) + .await; + + println!("current status: {:?}", inner.conn_status()); + + connection.disconnect().await; + Ok(()) +} +``` + +`ConnectionStatus` is one of `Idle`, `Connecting`, `Connected`, or `Disconnected`. Connections reconnect automatically with backoff until you call `disconnect`. + +## Low-Level HTTP & WebSocket + +For actors that implement `on_request` or `on_websocket`, call them directly on the untyped handle (`handle.inner()`). `fetch` returns a `reqwest::Response`, and `web_socket` returns a `tokio_tungstenite` stream. This example also needs a few extra crates: + +```sh +cargo add futures-util tokio-tungstenite +cargo add reqwest --features json +``` + +```rust @nocheck +use counter::Counter; +use futures_util::{SinkExt, StreamExt}; +use reqwest::{header::HeaderMap, Method}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; +use tokio_tungstenite::tungstenite::Message; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let handle = client.get_or_create_typed_default::("counter", ["general"])?; + + // Raw HTTP request + let response = handle + .inner() + .fetch("history", Method::GET, HeaderMap::new(), None) + .await?; + let history: Vec = response.json().await?; + println!("history: {history:?}"); + + // Raw WebSocket connection + let mut ws = handle.inner().web_socket("stream", None).await?; + ws.send(Message::text("hello")).await?; + if let Some(message) = ws.next().await { + println!("received: {:?}", message?); + } + + Ok(()) +} +``` + +## Calling from Backend + +The client is a normal Tokio type, so you can hold it in your backend (Axum, Actix, etc.) and call actors from request handlers. The client is `Clone` and cheap to share: + +```rust @nocheck +use counter::{Counter, Increment}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +async fn increment(client: Client) -> Result { + let counter = client.get_or_create_typed_default::("counter", ["server-counter"])?; + let count = counter.send(Increment { amount: 1 }).await?; + Ok(count) +} +``` + +## Error Handling + +Action and connection calls return `anyhow::Result`. Actor-side errors surface as an `anyhow::Error` carrying the error group, code, message, and metadata: + +```rust @nocheck +use counter::{Counter, Increment}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + + match counter.send(Increment { amount: 1 }).await { + Ok(count) => println!("count: {count}"), + Err(error) => eprintln!("action failed: {error:#}"), + } + + Ok(()) +} +``` + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```rust @nocheck +use counter::Counter; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + // Compound key: [org, room] + let room = client.get_or_create_typed_default::("counter", ["org-acme", "general"])?; + let actor_id = room.inner().resolve().await?; + println!("Actor ID: {actor_id}"); + + Ok(()) +} +``` + +Keys accept arrays of `&str` or `String` (`["org-acme", "general"]`). Don't build keys with string interpolation like `format!("org:{user_id}")` when `user_id` contains user data. Use arrays instead to prevent key injection attacks. + +### Configuration + +`ClientConfig::new(endpoint)` is a builder. The endpoint is always required; there is no default. Common options: + +```rust @nocheck +use rivetkit::client::ClientConfig; + +let config = ClientConfig::new("http://localhost:6420") + .namespace("default") + .token("pk_...") + .pool_name("my-pool") + .header("x-custom", "value"); +``` + +- `namespace` - target namespace (defaults to the engine's configured namespace). +- `token` - authentication token for the engine. +- `pool_name` - runner pool to target. +- `header` / `headers` - extra HTTP headers sent with each request. +- `max_input_size` - cap on encoded action input size. + +For serverless deployments, set the endpoint to your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints) for details. + +## API Reference + +See the full client API documentation on [docs.rs/rivetkit-client](https://docs.rs/rivetkit-client/latest/rivetkit_client/). + +_Source doc path: /docs/clients/rust_ diff --git a/.agents/skills/chat-room/reference/clients/swift.md b/.agents/skills/chat-room/reference/clients/swift.md new file mode 100644 index 0000000..c760645 --- /dev/null +++ b/.agents/skills/chat-room/reference/clients/swift.md @@ -0,0 +1,454 @@ +# Swift + +> Source: `src/content/docs/clients/swift.mdx` +> Canonical URL: https://rivet.dev/docs/clients/swift +> Description: Connect Swift apps to Rivet Actors. + +--- +## Install + +Add the Swift package dependency and import `RivetKitClient`: + +```swift +// Package.swift +dependencies: [ + .package(url: "https://github.com/rivet-dev/rivetkit-swift", from: "2.0.0") +] + +targets: [ + .target( + name: "MyApp", + dependencies: [ + .product(name: "RivetKitClient", package: "rivetkit-swift") + ] + ) +] +``` + +## Minimal Client + +### Endpoint URL + +```swift +import RivetKitClient + +let config = try ClientConfig( + endpoint: "https://my-namespace:pk_...@api.rivet.dev" +) +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["my-counter"]) +let count: Int = try await handle.action("increment", 1, as: Int.self) +``` + +### Explicit Fields + +```swift +import RivetKitClient + +let config = try ClientConfig( + endpoint: "https://api.rivet.dev", + namespace: "my-namespace", + token: "pk_..." +) +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["my-counter"]) +let count: Int = try await handle.action("increment", 1, as: Int.self) +``` + +## Stateless vs Stateful + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["my-counter"]) + +// Stateless: each call is independent +let current: Int = try await handle.action("getCount", as: Int.self) +print("Current count: \(current)") + +// Stateful: keep a connection open for realtime events +let conn = handle.connect() + +// Subscribe to events using AsyncStream +let eventTask = Task { + for await count in await conn.events("count", as: Int.self) { + print("Event: \(count)") + } +} + +_ = try await conn.action("increment", 1, as: Int.self) + +eventTask.cancel() +await conn.dispose() +await client.dispose() +``` + +## Getting Actors + +```swift +import RivetKitClient + +struct GameInput: Encodable { + let mode: String +} + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +// Get or create an actor +let room = client.getOrCreate("chatRoom", ["room-42"]) + +// Get an existing actor (fails if not found) +let existing = client.get("chatRoom", ["room-42"]) + +// Create a new actor with input +let created = try await client.create( + "game", + ["game-1"], + options: CreateOptions(input: GameInput(mode: "ranked")) +) + +// Get actor by ID +let byId = client.getForId("chatRoom", "actor-id") + +// Resolve actor ID +let resolvedId = try await room.resolve() +print("Resolved ID: \(resolvedId)") + +await client.dispose() +``` + +Actions support positional overloads for 0–5 args: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("counter", ["my-counter"]) + +let count: Int = try await handle.action("getCount") +let updated: String = try await handle.action("rename", "new-name") +let ok: Bool = try await handle.action("setScore", "user-1", 42) + +print("Count: \(count), Updated: \(updated), OK: \(ok)") +await client.dispose() +``` + +If you need more than 5 arguments, use the raw JSON fallback: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("counter", ["my-counter"]) + +let args: [JSONValue] = [ + .string("user-1"), + .number(.int(42)), + .string("extra"), + .string("more"), + .string("args"), + .string("here") +] +let ok: Bool = try await handle.action("setScore", args: args, as: Bool.self) +print("OK: \(ok)") + +await client.dispose() +``` + +## Connection Parameters + +```swift +import RivetKitClient + +struct ConnParams: Encodable { + let authToken: String +} + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +let chat = client.getOrCreate( + "chatRoom", + ["general"], + options: GetOrCreateOptions(params: ConnParams(authToken: "jwt-token-here")) +) + +let conn = chat.connect() + +// Use the connection... +for await status in await conn.statusChanges() { + print("Status: \(status.rawValue)") + if status == .connected { + break + } +} + +await conn.dispose() +await client.dispose() +``` + +## Subscribing to Events + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let conn = client.getOrCreate("chatRoom", ["general"]).connect() + +// Subscribe to events using AsyncStream +let messageTask = Task { + for await (from, body) in await conn.events("message", as: (String, String).self) { + print("\(from): \(body)") + } +} + +// For one-time events, break after receiving +let gameOverTask = Task { + for await _ in await conn.events("gameOver", as: Void.self) { + print("done") + break + } +} + +// Let it run for a bit +try await Task.sleep(for: .seconds(5)) + +// Cancel when done +messageTask.cancel() +gameOverTask.cancel() +await conn.dispose() +await client.dispose() +``` + +Event streams support 0–5 typed arguments. If you need raw values or more than 5 arguments, use `JSONValue`: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let conn = client.getOrCreate("chatRoom", ["general"]).connect() + +let rawTask = Task { + for await args in await conn.events("message") { + print(args) + } +} + +try await Task.sleep(for: .seconds(5)) +rawTask.cancel() +await conn.dispose() +await client.dispose() +``` + +## Connection Lifecycle + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let conn = client.getOrCreate("chatRoom", ["general"]).connect() + +// Monitor status changes (immediately yields current status) +let statusTask = Task { + for await status in await conn.statusChanges() { + print("status: \(status.rawValue)") + } +} + +// Monitor errors +let errorTask = Task { + for await error in await conn.errors() { + print("error: \(error.group).\(error.code)") + } +} + +// Monitor open/close events +let openTask = Task { + for await _ in await conn.opens() { + print("connected") + } +} + +let closeTask = Task { + for await _ in await conn.closes() { + print("disconnected") + } +} + +// Check current status +let current = await conn.currentStatus +print("Current status: \(current.rawValue)") + +// Let it run for a bit +try await Task.sleep(for: .seconds(5)) + +// Cleanup +statusTask.cancel() +errorTask.cancel() +openTask.cancel() +closeTask.cancel() +await conn.dispose() +await client.dispose() +``` + +## Low-Level HTTP & WebSocket + +For actors that implement `onRequest` or `onWebSocket`, you can call them directly: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("chatRoom", ["general"]) + +// Raw HTTP request +let response = try await handle.fetch("history") +let history: [String] = try response.json([String].self) +print("History: \(history)") + +// Raw WebSocket connection +let websocket = try await handle.websocket(path: "stream") +try await websocket.send(text: "hello") +let message = try await websocket.receive() +print("Received: \(message)") + +await client.dispose() +``` + +## Calling from Backend + +Use the same client in server-side Swift (Vapor, Hummingbird, etc.): + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["server-counter"]) +let count: Int = try await handle.action("increment", 1, as: Int.self) +print("Count: \(count)") + +await client.dispose() +``` + +## Error Handling + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +do { + _ = try await client.getOrCreate("user", ["user-123"]) + .action("updateUsername", "ab", as: String.self) +} catch let error as ActorError { + print("Error code: \(error.code)") + print("Metadata: \(String(describing: error.metadata))") +} + +await client.dispose() +``` + +If you need an untyped response, you can decode to `JSONValue`: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("data", ["raw"]) + +let value: JSONValue = try await handle.action("getRawPayload") +print("Raw value: \(value)") + +await client.dispose() +``` + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +// Use compound keys for hierarchical addressing +let room = client.getOrCreate("chatRoom", ["org-acme", "general"]) +let actorId = try await room.resolve() +print("Actor ID: \(actorId)") + +await client.dispose() +``` + +Don't build keys with string interpolation like `"org:\(userId)"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`ClientConfig` reads optional values from environment variables: + +- `RIVET_NAMESPACE` - Namespace (can also be in endpoint URL) +- `RIVET_TOKEN` - Authentication token (can also be in endpoint URL) +- `RIVET_RUNNER` - Runner name (defaults to `"default"`) + +The `endpoint` parameter is always required. There is no default endpoint. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, set the endpoint to your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## API Reference + +### Client +- `RivetKitClient(config:)` - Create a client with a config +- `ClientConfig` - Configure endpoint, namespace, and token +- `client.get()` / `getOrCreate()` / `getForId()` / `create()` - Get actor handles +- `client.dispose()` - Dispose the client and all connections + +### ActorHandle +- `handle.action(name, args..., as:)` - Stateless action call +- `handle.connect()` - Create a stateful connection +- `handle.resolve()` - Get the actor ID +- `handle.getGatewayUrl()` - Get the raw gateway URL +- `handle.fetch(path, request:)` - Raw HTTP request +- `handle.websocket(path:)` - Raw WebSocket connection + +### ActorConnection +- `conn.action(name, args..., as:)` - Action call over WebSocket +- `conn.events(name, as:)` - AsyncStream of typed events +- `conn.statusChanges()` - AsyncStream of status changes +- `conn.errors()` - AsyncStream of connection errors +- `conn.opens()` - AsyncStream that yields on connection open +- `conn.closes()` - AsyncStream that yields on connection close +- `conn.currentStatus` - Current connection status +- `conn.dispose()` - Close the connection + +### Types +- `ActorConnStatus` - Connection status enum (`.idle`, `.connecting`, `.connected`, `.disconnected`, `.disposed`) +- `ActorError` - Typed actor errors with `group`, `code`, `message`, `metadata` +- `JSONValue` - Raw JSON value for untyped responses + +_Source doc path: /docs/clients/swift_ diff --git a/.agents/skills/chat-room/reference/clients/swiftui.md b/.agents/skills/chat-room/reference/clients/swiftui.md new file mode 100644 index 0000000..4ae65d8 --- /dev/null +++ b/.agents/skills/chat-room/reference/clients/swiftui.md @@ -0,0 +1,359 @@ +# SwiftUI + +> Source: `src/content/docs/clients/swiftui.mdx` +> Canonical URL: https://rivet.dev/docs/clients/swiftui +> Description: Build SwiftUI apps with Rivet Actors. + +--- +## Install + +Add the Swift package dependency and import `RivetKitSwiftUI`: + +```swift +// Package.swift +dependencies: [ + .package(url: "https://github.com/rivet-dev/rivetkit-swift", from: "2.0.0") +] + +targets: [ + .target( + name: "MyApp", + dependencies: [ + .product(name: "RivetKitSwiftUI", package: "rivetkit-swift") + ] + ) +] +``` + +`RivetKitSwiftUI` re-exports `RivetKitClient` and `SwiftUI`, so a single import covers both. + +## Minimal Client + +```swift HelloWorldApp.swift +import RivetKitSwiftUI +import SwiftUI + +@main +struct HelloWorldApp: App { + var body: some Scene { + WindowGroup { + ContentView() + .rivetKit(endpoint: "https://my-namespace:pk_...@api.rivet.dev") + } + } +} +``` + +```swift ContentView.swift +import RivetKitSwiftUI +import SwiftUI + +struct ContentView: View { + @Actor("counter", key: ["my-counter"]) private var counter + @State private var count = 0 + + var body: some View { + VStack(spacing: 16) { + Text("\(count)") + .font(.system(size: 64, weight: .bold, design: .rounded)) + + Button("Increment") { + counter.send("increment", 1) + } + .disabled(!counter.isConnected) + } + .task { + count = (try? await counter.action("getCount")) ?? 0 + } + .onActorEvent(counter, "newCount") { (newCount: Int) in + count = newCount + } + } +} +``` + +## Actor Options + +The `@Actor` property wrapper always uses get-or-create semantics and accepts: + +- `name` (required) +- `key` as `String` or `[String]` (required) +- `params` (optional connection parameters) +- `createWithInput` (optional creation input) +- `createInRegion` (optional creation hint) +- `enabled` (toggle connection lifecycle) + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct ConnParams: Encodable { + let authToken: String +} + +struct ChatView: View { + @Actor( + "chatRoom", + key: ["general"], + params: ConnParams(authToken: "jwt-token"), + enabled: true + ) private var chat + + var body: some View { + Text("Chat: \(chat.connStatus.rawValue)") + } +} +``` + +## Actions + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct CounterView: View { + @Actor("counter", key: ["my-counter"]) private var counter + @State private var count = 0 + @State private var name = "" + + var body: some View { + VStack { + Text("Count: \(count)") + Text("Name: \(name)") + + Button("Fetch") { + Task { + count = try await counter.action("getCount") + name = try await counter.action("rename", "new-name") + } + } + + Button("Increment") { + counter.send("increment", 1) + } + } + } +} +``` + +## Subscribing to Events + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct GameView: View { + @Actor("game", key: ["game-1"]) private var game + @State private var count = 0 + @State private var isGameOver = false + + var body: some View { + VStack { + Text("Count: \(count)") + if isGameOver { + Text("Game Over!") + } + } + .onActorEvent(game, "newCount") { (newCount: Int) in + count = newCount + } + .onActorEvent(game, "gameOver") { + isGameOver = true + } + } +} +``` + +## Async Event Streams + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct ChatView: View { + @Actor("chatRoom", key: ["general"]) private var chat + @State private var messages: [String] = [] + + var body: some View { + List(messages, id: \.self) { message in + Text(message) + } + .task { + for await message in chat.events("message", as: String.self) { + messages.append(message) + } + } + } +} +``` + +## Connection Status + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct StatusView: View { + @Actor("counter", key: ["my-counter"]) private var counter + @State private var count = 0 + + var body: some View { + VStack { + Text("Status: \(counter.connStatus.rawValue)") + + if counter.connStatus == .connected { + Text("Connected!") + .foregroundStyle(.green) + } + + Button("Fetch via Handle") { + Task { + if let handle = counter.handle { + count = try await handle.action("getCount", as: Int.self) + } + } + } + .disabled(!counter.isConnected) + } + } +} +``` + +## Error Handling + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct UserView: View { + @Actor("user", key: ["user-123"]) private var user + @State private var errorMessage: String? + @State private var username = "" + + var body: some View { + VStack { + TextField("Username", text: $username) + + Button("Update Username") { + Task { + do { + let _: String = try await user.action("updateUsername", username) + } catch let error as ActorError { + errorMessage = "\(error.code): \(String(describing: error.metadata))" + } + } + } + + if let errorMessage { + Text(errorMessage) + .foregroundStyle(.red) + } + } + .onActorError(user) { error in + errorMessage = "\(error.group).\(error.code): \(error.message)" + } + } +} +``` + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct OrgChatView: View { + @Actor("chatRoom", key: ["org-acme", "general"]) private var room + + var body: some View { + Text("Room: \(room.connStatus.rawValue)") + } +} +``` + +Don't build keys with string interpolation like `"org:\(userId)"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Configuration + +Call `.rivetKit(endpoint:)` or `.rivetKit(client:)` once at the root of your view tree: + +```swift +// With endpoint string (recommended for most apps) +@main +struct MyApp: App { + var body: some Scene { + WindowGroup { + ContentView() + .rivetKit(endpoint: "https://my-namespace:pk_...@api.rivet.dev") + } + } +} + +// With custom client (for advanced configuration) +@main +struct MyApp: App { + private let client = RivetKitClient( + config: try! ClientConfig(endpoint: "https://api.rivet.dev", token: "pk_...") + ) + + var body: some Scene { + WindowGroup { + ContentView() + .rivetKit(client: client) + } + } +} +``` + +When using `.rivetKit(endpoint:)`, the client is created once and cached per endpoint. When using `.rivetKit(client:)`, store the client as a property on `App` (not inside `body`) since SwiftUI can call `body` multiple times. + +### Environment Variables + +`ClientConfig` reads optional values from environment variables: + +- `RIVET_NAMESPACE` - Namespace (can also be in endpoint URL) +- `RIVET_TOKEN` - Authentication token (can also be in endpoint URL) +- `RIVET_RUNNER` - Runner name (defaults to `"default"`) + +The endpoint is always required. There is no default endpoint. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, set the endpoint to your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## API Reference + +### Property Wrapper +- `@Actor(name, key:, params:, createWithInput:, createInRegion:, enabled:)` - SwiftUI property wrapper for actor connections + +### View Modifiers +- `.rivetKit(endpoint:)` - Configure client with an endpoint URL (creates cached client) +- `.rivetKit(client:)` - Configure client with a custom instance +- `.onActorEvent(actor, event) { ... }` - Subscribe to actor events (supports 0–5 typed args) +- `.onActorError(actor) { error in ... }` - Handle actor errors + +### ActorObservable +- `actor.action(name, args..., as:)` - Async action call +- `actor.send(name, args...)` - Fire-and-forget action +- `actor.events(name, as:)` - AsyncStream of typed events +- `actor.connStatus` - Current connection status +- `actor.isConnected` - Whether connected +- `actor.handle` - Underlying `ActorHandle` (optional) +- `actor.connection` - Underlying `ActorConnection` (optional) +- `actor.error` - Most recent error (optional) + +### Types +- `ActorConnStatus` - Connection status enum (`.idle`, `.connecting`, `.connected`, `.disconnected`, `.disposed`) +- `ActorError` - Typed actor errors with `group`, `code`, `message`, `metadata` + +_Source doc path: /docs/clients/swiftui_ diff --git a/.agents/skills/chat-room/reference/cookbook/ai-agent.md b/.agents/skills/chat-room/reference/cookbook/ai-agent.md new file mode 100644 index 0000000..1adb285 --- /dev/null +++ b/.agents/skills/chat-room/reference/cookbook/ai-agent.md @@ -0,0 +1,127 @@ +# AI Agent + +> Source: `src/content/cookbook/ai-agent.mdx` +> Canonical URL: https://rivet.dev/cookbook/ai-agent +> Description: Build an AI agent backend with persistent memory: one Rivet Actor per conversation, queued message handling, and streaming LLM responses as realtime events. + +--- +Patterns for building AI agent backends with RivetKit, where each conversation is one Rivet Actor that owns its memory, its message queue, and its streaming output. + +## Starter Code + +Start with one of the working examples on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/ai-agent) and adapt it. The sections below describe the flagship `ai-agent` example unless a variant is called out explicitly. + +| Variant | Starter Code | Use When | +| --- | --- | --- | +| Queue-driven AI SDK agent | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/ai-agent) | You want a streaming chat agent where each conversation keeps its own persistent memory and processes one message at a time. | +| Sandbox coding agent | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/sandbox-coding-agent) | The agent should run a coding agent (Codex by default) inside an isolated [sandbox](/docs/actors/sandbox) via Docker, Daytona, or E2B. | +| Durable streams agent (experimental) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/experimental-durable-streams-ai-agent) | You want replayable, restart-safe prompt and response delivery through durable streams instead of actor state and events. | + +## Conversation Memory + +Use one actor per conversation, keyed by a conversation or agent id (see [Actor Keys](/docs/actors/keys)). The agent actor's persistent [state](/docs/actors/state) is the conversation memory: in the `ai-agent` example, `messages` and `status` live in JSON actor state and survive sleep and restarts with no external database. Every model call rebuilds the prompt from `c.state.messages` plus a system prompt, so memory and inference input are the same data. + +| Variant | Where Memory Lives | Persisted State Fields | +| --- | --- | --- | +| `ai-agent` | JSON actor state | `messages`, `status` | +| `sandbox-coding-agent` | JSON actor state plus the sandbox ACP session | `messages`, `status`, `sessionId` | +| `experimental-durable-streams-ai-agent` | Durable streams; the actor stores only its conversation id and a read cursor | `conversationId`, `promptStreamOffset` | + +## Message Handling + +In the `ai-agent` example, the client pushes user input onto the agent's `message` [queue](/docs/actors/queues) with `agent.connection.send("message", { text, sender })`. This is a queue push, not an action call. The actor's `run` hook (see [Lifecycle](/docs/actors/lifecycle)) consumes the queue serially with `for await (const queued of c.queue.iter())`. + +Serial queue consumption is the per-conversation concurrency guarantee: at most one in-flight model call per actor, with no extra locking. The `status` field (`thinking` while a model call is in flight) is UI signal only; the run loop is the actual lock. The loop also checks `c.aborted` inside the token stream so shutdown exits gracefully. + +| Variant | Message Ingress | Serialization Guarantee | +| --- | --- | --- | +| `ai-agent` | `message` queue pushed via `connection.send` | `run` hook pops one queued message at a time with `c.queue.iter()`. | +| `sandbox-coding-agent` | `sendMessage` [action](/docs/actors/actions), no queue | Each call awaits the sandbox round trip before broadcasting the result. | +| `experimental-durable-streams-ai-agent` | Durable prompt stream long-polled from `onWake` | `promptStreamOffset` is persisted per chunk, so restarts resume without reprocessing prompts. | + +## Streaming Responses + +The `ai-agent` actor broadcasts a `response` [event](/docs/actors/events) for every model text delta. The payload carries `messageId`, the per-token `delta`, the cumulative `content`, and a `done` flag (plus `error` on failure), so clients can either append deltas or idempotently replace the message by `messageId` using `content`. The example frontend replaces by `messageId`, which tolerates dropped events. The terminal broadcast has an empty `delta`, the full `content`, and `done: true`. + +Because the assistant message object lives in `c.state.messages` and is mutated in place during streaming, partial content persists if the actor restarts mid-stream. The example broadcasts once per AI SDK delta with no throttling; batching or throttling deltas is a recommended extension for high-traffic deployments, not something the example implements. + +Variant differences: `sandbox-coding-agent` sends a single `response` broadcast with `done: true` after the sandbox finishes (no incremental streaming), and `experimental-durable-streams-ai-agent` appends per-token chunks to a durable response stream, then broadcasts `responseComplete` or `responseError`. + +## Architecture + +| Topic | Summary | +| --- | --- | +| Topology | `agentManager["primary"]` singleton directory plus one `agent[agentId]` actor per conversation. | +| Ingress | Client pushes `AgentQueueMessage` payloads onto the agent's `message` queue with `connection.send`. | +| Streaming | One `response` broadcast per model delta, terminal broadcast with `done: true`. | +| Memory | Full transcript and status in JSON actor state; no external database. | + +The manager creates `AgentInfo` records and warms each agent through [actor-to-actor communication](/docs/actors/communicating-between-actors): `createAgent` calls `c.client()`, then `client.agent.getOrCreate([info.id])` and awaits `getStatus()` so the conversation actor exists before the client connects. The sandbox variant extends this topology with a `codingSandbox` actor that shares the agent's key (`codingSandbox.getOrCreate([c.key[0]])`), so the agent-to-sandbox mapping is implicit in the key space. + +**Actors** + +- **Key**: `agentManager["primary"]` +- **Responsibility**: Directory actor. Creates `AgentInfo` records, lists agents, and warms each agent actor via `c.client()`. +- **Actions** + - `createAgent` + - `listAgents` +- **Queues** + - None +- **State** + - JSON + - `agents` + +- **Key**: `agent[agentId]` +- **Responsibility**: One actor per conversation. Holds the full message history and status, consumes queued user messages in its `run` loop, calls the model via the AI SDK, and broadcasts streaming deltas. +- **Actions** + - `getHistory` + - `getStatus` +- **Queues** + - `message` +- **Events** + - `messageAdded` + - `status` + - `response` +- **State** + - JSON + - `messages` + - `status` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant AM as agentManager + participant A as agent + participant LLM as Model API + + C->>AM: createAgent(name) + AM->>A: getOrCreate([info.id]) + getStatus() + AM-->>C: AgentInfo + C->>A: connection.send("message", {text, sender}) + Note over A: run loop pops queue via c.queue.iter() + A-->>C: messageAdded (user message) + A-->>C: messageAdded (assistant placeholder) + A-->>C: status (thinking) + A->>LLM: streamText(system prompt + history) + loop each text delta + LLM-->>A: delta + A-->>C: response {messageId, delta, content, done: false} + end + A-->>C: response {delta: "", content, done: true} + A-->>C: status (idle) +``` + +## Security Checklist + +The examples ship without auth so they stay minimal. Apply this baseline before exposing an agent backend. + +- **API keys stay server-side**: `OPENAI_API_KEY` (or `ANTHROPIC_API_KEY`) is read by the AI SDK inside the actor process. The key never reaches the browser; clients only talk to the actor over RivetKit. The sandbox variant forwards keys into the sandbox env, never to the client. +- **Add authentication**: The examples have no auth, so anyone who reaches the server can create agents, list them, and message any agent whose key they can guess. Add `onBeforeConnect` or `createConnState` checks with scoped tokens as a recommended extension. See [Authentication](/docs/actors/authentication). +- **Validate and rate-limit queue payloads**: The example only skips bodies without a string `text`. Enforce payload size limits, schema validation, and per-connection rate limits as a recommended extension. +- **Derive sender identity server-side**: The example trusts the client-supplied `sender` field verbatim. Bind sender identity to the authenticated connection instead. +- **Cap or trim message history**: The example sends the full transcript on every model call with no cap. Trim or summarize old messages as a recommended extension so prompts and state stay bounded. +- **Set cost ceilings per conversation**: Add per-agent token budgets and quotas as a recommended extension. The sandbox variant runs real compute, so also enforce per-user sandbox quotas and restrict sandbox network egress. + +_Source doc path: /cookbook/ai-agent_ diff --git a/.agents/skills/chat-room/reference/cookbook/chat-room.md b/.agents/skills/chat-room/reference/cookbook/chat-room.md new file mode 100644 index 0000000..cb8dbe4 --- /dev/null +++ b/.agents/skills/chat-room/reference/cookbook/chat-room.md @@ -0,0 +1,114 @@ +# Chat Room + +> Source: `src/content/cookbook/chat-room.mdx` +> Canonical URL: https://rivet.dev/cookbook/chat-room +> Description: Build a realtime chat room backend with Rivet Actors: one actor per room, SQLite-backed message history, and WebSocket broadcast to every connected client. + +--- +Patterns for building a chat room backend with RivetKit: room-scoped actors, persistent message history, and realtime delivery over WebSocket connections. + +## Starter Code + +Start with the working example on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room) and adapt it. The backend is a single `chatRoom` actor; the frontend is a React app using `@rivetkit/react` (see the [React quickstart](/docs/actors/quickstart/react)). + +| Topic | Summary | +| --- | --- | +| Room model | One `chatRoom` actor per room key. The frontend defaults the key to `general`; typing a different room name connects to a different actor. | +| History | SQLite `messages` table created in `db({ onMigrate })`, read back with `ORDER BY id ASC`. | +| Delivery | `sendMessage` inserts the row, then broadcasts a typed `newMessage` event to every connected client. | +| Identity | None in the example. `sender` is a plain action argument; production should bind identity to the connection. | + +## Room-Per-Actor Model + +Each room is one Rivet Actor instance, addressed by [key](/docs/actors/keys). The client calls `useActor({ name: "chatRoom", key: [roomId] })`, which gets-or-creates the actor for that room. This gives you: + +- **Isolation**: each room's history and connections are fully scoped to its key. Switching the room input re-keys the hook and connects to a different actor with separate history. +- **A single serialized writer**: all `sendMessage` calls for one room run through one actor, so message ordering is consistent without locks. The SQLite `AUTOINCREMENT` id is the canonical order, which is why `getHistory` sorts by `id` rather than by timestamp. +- **Natural scaling**: rooms spread across the cluster independently. A hot room does not slow down other rooms. + +## Message History Storage + +This example stores history in the actor's SQLite database, not in JSON state. Pick based on history size and query needs: + +| Approach | Use When | Implementation Guidance | +| --- | --- | --- | +| [SQLite](/docs/actors/sqlite) (what this example uses) | Large or long-lived history that needs ordering, caps, pagination, or search | Create the `messages` table in `db({ onMigrate })`, insert with parameterized queries (`c.db.execute("INSERT ... VALUES (?, ?, ?)", ...)`), and read with `ORDER BY id ASC`. History survives actor sleep and scales past what you want in memory. | +| [JSON state](/docs/actors/state) | Small recent history, for example the last 50 to 100 messages | Push onto a `messages` array in actor state and trim to a cap on every send. Simplest option, but the whole history lives in memory and there is no query layer, so it only fits bounded recent-history use cases. | + +## Broadcast Delivery + +New messages reach connected clients through a typed [event](/docs/actors/events): + +- The actor declares `events: { newMessage: event() }`, where `Message` is `{ sender, text, timestamp }`. +- The `sendMessage` [action](/docs/actors/actions) builds the message with a server-side `Date.now()` timestamp, inserts it into the `messages` table, then calls `c.broadcast("newMessage", message)` and returns the message to the caller. +- Each client subscribes with `useEvent("newMessage", ...)` and appends to its local list. The sender renders its own message through the same broadcast path as everyone else, so all clients stay on one code path. +- History load is connection-gated: once the connection is ready, the client calls `getHistory()` once to render the backlog, then relies on events for everything after. + +Use `c.broadcast(...)` for room-wide messages. For private or per-recipient payloads (such as DMs inside a room), send on the individual connection instead, which is a recommended extension beyond this example. + +## Typing Indicators And Presence (Extension) + +The example does not implement typing indicators, presence, or join/leave handling of any kind. There is no `createConnState`, `onConnect`, or `onDisconnect` in the code. If you need them, add them as ephemeral [connection](/docs/actors/connections) behavior: + +- **Keep it ephemeral**: store the username and typing flag in per-connection state, never in SQLite or persisted actor state. Presence is derived from live connections and should disappear with them. +- **Broadcast on change only**: emit a typing event when a user starts or stops typing, and a presence event from `onConnect` / `onDisconnect`, rather than polling or ticking. +- **Expire on the client**: clear a typing indicator after a short client-side timeout so a dropped connection never leaves a stuck "is typing" row. + +## Per-User Inbox (Extension) + +For offline delivery, DMs, unread counts, or notification fanout, add a `userInbox[userId]` actor per user. This is an extension beyond the example: + +- The room actor forwards each message to the inbox actor of every member via [actor-to-actor calls](/docs/actors/communicating-between-actors), so users who are not connected to the room still accumulate messages. +- The inbox actor owns per-user unread state and serves it when the user comes online, independent of which rooms they are in. +- DMs become a degenerate room: either a `chatRoom` keyed by the sorted pair of user ids, or direct inbox-to-inbox delivery if you do not need shared history semantics. + +## Actors + +- **Key**: `chatRoom[roomId]` +- **Responsibility**: Owns one chat room. Persists the room's message history in its SQLite database and broadcasts each new message to every connected client. +- **Actions** + - `sendMessage` + - `getHistory` +- **Queues** + - None +- **Events** + - `newMessage` +- **State** + - SQLite + - `messages` table: `id` (autoincrement primary key), `sender`, `text`, `timestamp` + +## Lifecycle + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant R as chatRoom + + A->>R: connect with key [roomId] + Note over R: every start runs onMigrate (CREATE TABLE IF NOT EXISTS messages) + A->>R: getHistory() + R-->>A: Message[] ordered by id + B->>R: connect with key [roomId] + B->>R: getHistory() + R-->>B: Message[] ordered by id + A->>R: sendMessage(sender, text) + Note over R: INSERT row with server timestamp + R-->>A: newMessage (broadcast) + R-->>B: newMessage (broadcast) + A->>R: disconnect + Note over R: history stays in SQLite for the next connection +``` + +## Security Checklist + +The example is intentionally minimal and skips all of the following. Add them before production: + +- **Auth before join**: any client can join any room by knowing its name, and `sender` is arbitrary client input on every call. Validate a token during [connection auth](/docs/actors/authentication), bind identity to [connection state](/docs/actors/connections), and check room membership before serving history. Never trust a sender name passed as an action argument. +- **Message length clamps**: the example accepts empty messages and has no length limit. Trim server-side, reject empty text, and clamp to a maximum length. +- **Per-connection rate limiting**: rate limit `sendMessage` per connection to stop spam and broadcast amplification. +- **Server-side timestamps and ids**: the example already does this correctly. `timestamp` comes from `Date.now()` inside the action and `id` from SQLite `AUTOINCREMENT`. Keep it that way; never accept client-supplied timestamps or ids. +- **History caps**: `getHistory` returns every row with no limit. Add a `LIMIT` plus pagination, and prune or archive old rows so a long-lived room cannot grow unbounded. +- **Parameterized queries**: the example already inserts with `?` placeholders. Keep all user-supplied text out of SQL string interpolation. + +_Source doc path: /cookbook/chat-room_ diff --git a/.agents/skills/chat-room/reference/cookbook/collaborative-text-editor.md b/.agents/skills/chat-room/reference/cookbook/collaborative-text-editor.md new file mode 100644 index 0000000..cacbc1f --- /dev/null +++ b/.agents/skills/chat-room/reference/cookbook/collaborative-text-editor.md @@ -0,0 +1,157 @@ +# Collaborative Text Editor + +> Source: `src/content/cookbook/collaborative-text-editor.mdx` +> Canonical URL: https://rivet.dev/cookbook/collaborative-text-editor +> Description: Build a collaborative text editor backend with Yjs CRDTs and Rivet Actors: per-document actors relay sync and awareness updates and persist snapshots. + +--- +Patterns for building a Yjs server on RivetKit: CRDT document sync, presence and cursors, and snapshot persistence, with one Rivet Actor per document acting as a relay. + +## Starter Code + +Start with the working example on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/collaborative-document) and adapt it to your editor. It ships a React frontend with a plain textarea, remote cursor overlays, and a workspace document index. + +| Use Case | Starter Code | Common Examples | +| --- | --- | --- | +| Shared document editing | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/collaborative-document) | Notion-style docs, shared notes, pair-writing tools, form co-editing | + +## CRDT vs OT + +Two families of algorithms solve concurrent text editing. The choice decides what your server has to do. + +| Dimension | CRDT (Yjs) | Operational Transformation | +| --- | --- | --- | +| Conflict resolution model | Commutative merges. Updates apply in any order on any peer and converge to the same result. | Server transforms each operation against every concurrent operation. Correctness depends on a central sequencer. | +| Offline support | Strong. Clients keep editing locally and merge buffered updates on reconnect. | Weak. Long-lived divergence makes transformation chains complex and fragile. | +| Server role | Relay plus persistence. The server applies opaque updates and rebroadcasts them. It never needs to understand document semantics. | Authoritative transformer. The server must implement transformation logic for every operation type. | +| Library maturity | Yjs is mature and widely deployed, with bindings for ProseMirror, CodeMirror, Monaco, and others. | Production-grade implementations are mostly proprietary (Google Docs) or aging (ShareDB). | + +The example uses Yjs because CRDTs let the server stay a relay-style Rivet Actor. The actor applies each incoming update to a server-side `Y.Doc` so it can persist the merged state and serve late joiners, but it never transforms operations or arbitrates conflicts. Ordering does not matter because Yjs merges are commutative. + +## Document Actor Model + +| Topic | Summary | +| --- | --- | +| Topology | One `document[workspaceId, documentId]` actor per document plus one `documentList[workspaceId]` coordinator per workspace. | +| Sync model | Each client holds a local `Y.Doc`. The document actor relays incremental Yjs updates as broadcast [events](/docs/actors/events) and keeps a server-side merged copy in vars. | +| Persistence | Full merged Yjs snapshot overwritten in one binary [actor KV](/docs/actors/kv) key (`yjs:doc`) on every sync update. Document metadata lives in JSON [state](/docs/actors/state). | +| Queues | None. The example is purely [actions](/docs/actors/actions) plus broadcast events. | +| Presence | Yjs Awareness relayed through the same `applyUpdate` action. Per-connection `connState` tracks asserted awareness clientIds for disconnect cleanup. | + +The two-actor split follows the coordinator pattern from [Design Patterns](/docs/actors/design-patterns): the coordinator owns discovery and creation, and each document actor owns one document's realtime state. Multi-part [keys](/docs/actors/keys) scope both actors to a workspace. + +**Actors** + +- **Key**: `document[workspaceId, documentId]` +- **Responsibility**: Applies incoming sync and awareness updates to a server-side `Y.Doc` and `Awareness`, persists the merged Yjs snapshot to actor KV, and broadcasts updates to all connected collaborators. +- **Actions** + - `getContent` + - `applyUpdate` + - `getAwareness` +- **Queues** + - None +- **State** + - JSON metadata only: `title`, `createdAt`, `updatedAt` + - Binary KV key `yjs:doc` holding the full merged Yjs snapshot + - Ephemeral vars: the live `Y.Doc` and `Awareness`, created in `createVars` and rehydrated from KV on actor start + - Per-connection `connState`: `clientIds` of awareness clients asserted by that connection + +- **Key**: `documentList[workspaceId]` +- **Responsibility**: Coordinator for one workspace. Creates document actors through the actor-to-actor client and maintains the index of document summaries. +- **Actions** + - `createDocument` + - `listDocuments` + - `deleteDocument` +- **Queues** + - None +- **State** + - JSON + - `documents` array of `DocumentSummary` entries (`id`, `title`, `createdAt`, `updatedAt`) + +The coordinator's `createDocument` generates a UUID, then explicitly creates the document actor with `c.client()` and passes `{ title, createdAt }` as creation [input](/docs/actors/input), which the document actor's `createState` consumes. See [Communicating Between Actors](/docs/actors/communicating-between-actors) for the actor-to-actor client. + +## Update Relay + +A single `applyUpdate(update, kind, clientId?)` action handles both update kinds. Updates cross the action boundary as `number[]` byte arrays and are converted back to `Uint8Array` on each side. + +| Kind | Server Applies To | Persists | Broadcasts | +| --- | --- | --- | --- | +| `"sync"` | `c.vars.doc` via `Y.applyUpdate` with origin `"client"` | Full merged snapshot to KV key `yjs:doc`, then bumps `updatedAt` | `sync` event carrying the incremental update | +| `"awareness"` | `c.vars.awareness` via `applyAwarenessUpdate` with origin `"client"` | Nothing. Presence is ephemeral. | `awareness` event carrying the update | + +Note the asymmetry on the sync branch: the broadcast carries only the small incremental update, while the KV write stores the full merged document re-encoded with `Y.encodeStateAsUpdate`. + +Yjs origin tags are the echo guards that keep the relay loop-free: + +| Origin Tag | Set Where | Effect | +| --- | --- | --- | +| `"local"` | Client edits inside `doc.transact(..., "local")` | The client's update listener fires and sends `applyUpdate` to the actor. | +| `"client"` | Server applying an incoming update to its `Y.Doc` or `Awareness` | Marks the change as client-originated on the server copy. | +| `"remote"` | Client applying broadcast events or initial sync data | Update listeners early-return on `"remote"`, so a client never re-sends its own echo. | + +On connect or reconnect, the client calls `getContent` and `getAwareness`, then applies both results to its local `Y.Doc` and `Awareness` with origin `"remote"`. After that, every change flows through `applyUpdate` and the broadcast events. + +## Awareness And Presence + +Presence (user names, colors, cursor positions) rides on the Yjs Awareness protocol instead of actor state: + +- Clients set presence with `awareness.setLocalStateField` for the `user` and `cursor` fields. The awareness update listener encodes the change and sends `applyUpdate(update, "awareness", awareness.clientID)`. +- The actor records each asserted `clientId` in that connection's `connState.clientIds`, applies the update to the server-side `Awareness`, and broadcasts the `awareness` event to all peers. See [Connections](/docs/actors/connections) for per-connection state. +- `onDisconnect` reads the connection's `clientIds`, calls `removeAwarenessStates` on the server-side `Awareness`, and broadcasts the encoded removal so every remaining client drops the departed user's cursor. See [Lifecycle](/docs/actors/lifecycle) for the hook. + +Because the actor tracks which awareness clientIds belong to which connection, presence cleanup is automatic on disconnect with no client cooperation required. + +## Persistence And Compaction + +The example persists with a full-snapshot overwrite: on every `"sync"` update, the actor re-encodes the entire merged document with `Y.encodeStateAsUpdate` and overwrites the single binary KV key `yjs:doc`. There is no append-only update log and no separate compaction job. Compaction is implicit because `Y.encodeStateAsUpdate` emits one compact merged representation of the document, so Yjs merge semantics keep the stored blob compact on their own. + +| Property | Full-Snapshot Overwrite (the example) | +| --- | --- | +| Write cost | One full-document KV write per sync update, so every keystroke rewrites the whole blob. | +| Read cost | One binary KV read in `createVars` rehydrates the document on actor start. | +| Crash safety | The last completed `applyUpdate` is durable. No log replay needed. | +| Sweet spot | Small to medium documents where simplicity beats write amplification. | + +**Recommended extension (not in the example)**: for large documents or very high edit rates, switch to appending incremental updates to a KV update log and writing a merged snapshot only periodically (for example every N updates). Boot becomes snapshot plus log replay, and the snapshot write becomes the explicit compaction step that truncates the log. Adopt this only when full-snapshot writes become the measured bottleneck or the blob approaches KV value size limits. + +## Lifecycle + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant DL as documentList + participant D as document + + A->>DL: listDocuments() + A->>DL: createDocument(title) + DL->>D: create([workspaceId, documentId], input) + DL-->>A: DocumentSummary + A->>D: connect + B->>D: connect + Note over D: createVars rehydrates Y.Doc from KV "yjs:doc" + A->>D: getContent() + getAwareness() + D-->>A: encoded doc + awareness state + Note over A: local edit with origin "local" + A->>D: applyUpdate(update, "sync") + Note over D: apply with origin "client", overwrite KV snapshot + D-->>B: sync event (incremental update) + Note over B: apply with origin "remote", no echo + A->>D: applyUpdate(update, "awareness", clientId) + D-->>B: awareness event + B-->>D: disconnect + Note over D: onDisconnect removes B's awareness clientIds + D-->>A: awareness event (removal) +``` + +## Security Checklist + +The example ships with no authentication or authorization. Harden it with this baseline before production. None of these are implemented in the example. + +- **Authenticate before connect**: Anyone who knows or guesses a workspace ID can connect, and because `useActor` implicitly getOrCreates, connecting with a nonexistent workspace ID silently creates a blank `documentList` coordinator. Add connection auth so unauthenticated clients never reach an actor. See [Authentication](/docs/actors/authentication). +- **Per-document access control**: Validate that the authenticated user is allowed to access the specific `[workspaceId, documentId]` key, not just any document. +- **Cap and rate limit `applyUpdate`**: Update payloads are unvalidated `number[]` arrays with no size limit, and the example client sends one action per keystroke and per cursor move with zero throttling. Enforce payload size caps and per-connection rate limits on the server, and debounce on the client. +- **Do not trust client-asserted awareness clientIds**: The `clientId` argument to `applyUpdate` is client-supplied and trusted as-is. Derive or verify presence identity from connection-scoped server state instead. +- **Destroy actors and KV on delete**: `deleteDocument` only filters the entry out of the coordinator's index. The document actor and its KV snapshot are orphaned. On delete, also destroy the document actor and its storage, with a permission check on who may delete. + +_Source doc path: /cookbook/collaborative-text-editor_ diff --git a/.agents/skills/chat-room/reference/cookbook/cron-jobs.md b/.agents/skills/chat-room/reference/cookbook/cron-jobs.md new file mode 100644 index 0000000..12f7119 --- /dev/null +++ b/.agents/skills/chat-room/reference/cookbook/cron-jobs.md @@ -0,0 +1,123 @@ +# Cron Jobs and Scheduled Tasks + +> Source: `src/content/cookbook/cron-jobs.mdx` +> Canonical URL: https://rivet.dev/cookbook/cron-jobs +> Description: Durable cron jobs with Rivet Actors: schedule.after and schedule.at timers survive restarts and crashes, plus re-arming recurring jobs and idempotent handlers. + +--- +Patterns for running durable cron jobs and scheduled tasks on Rivet Actors. Actor schedules are persistent timers owned by the engine, so a job keeps its deadline through actor sleep, restarts, upgrades, deploys, and crashes. + +## Starter Code + +Start from the working [Scheduling example on GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/scheduling). It implements a reminder service with one-shot timers, a React frontend, and live trigger events. + +## The Scheduling API + +The full API is documented in [Scheduling](/docs/actors/schedule). There are two methods, both available on the actor context: + +| Method | Behavior | +| --- | --- | +| `c.schedule.after(duration, actionName, ...args)` | Runs the named action after `duration` milliseconds. | +| `c.schedule.at(timestamp, actionName, ...args)` | Runs the named action at an exact epoch timestamp in milliseconds. | + +Key properties: + +- **Durable**: The schedule is persisted by the engine and the timer survives actor sleep, restart, upgrade, and crash. If the actor is asleep at the deadline, the engine wakes it to run the action. See [Lifecycle](/docs/actors/lifecycle). +- **Plain actions as callbacks**: The scheduled callback is an ordinary [action](/docs/actors/actions) on the same actor, invoked by name. Arguments after the action name are forwarded positionally, for example `c.schedule.after(delayMs, "triggerReminder", reminder.id)`. +- **No cancellation API**: Rivet does not currently support canceling a scheduled action. The pattern is a tombstone guard: remove the entry from [state](/docs/actors/state) and have the scheduled action no-op when it cannot find its entry. The example's `cancelReminder` and `triggerReminder` actions implement exactly this. + +## Recurring Jobs Via Re-Arm + +`c.schedule` is one-shot, so recurring jobs are built by having the scheduled action re-arm itself at the end of each run: + +Arm the first run from `onCreate` or a setup action; after that, the action keeps the chain alive by rescheduling itself. + +Re-arming with `after` measures the next run from the end of the current one, so the cadence drifts later by the job's runtime on every cycle. If runs must stay aligned to a fixed cadence, re-arm with `c.schedule.at(c.state.lastRunAt + DAY_MS, "runReport")` instead. + +The Scheduling example itself only uses one-shot reminders. A real re-arm implementation lives in the [idle world actor](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/idle/), where the `collectProduction` action credits production, updates `lastCollectedAt`, and calls a `scheduleCollection` helper that re-arms with `c.schedule.after(delayMs, "collectProduction", { buildingId })`. It also shows catch-up handling: if the action runs late, it computes how many whole intervals elapsed since the last run and credits them in one batch before re-arming. + +For multi-step jobs that need retries and progress tracking inside a single run, consider [Workflows](/docs/actors/workflows) instead of chaining schedules. + +## Durability Comparison + +| Approach | Timer Durability | Horizontal Scaling | Deploys And Restarts | +| --- | --- | --- | --- | +| `setTimeout` / `setInterval` | In-process memory only | Every replica arms its own timer, so jobs run once per instance | All pending timers are lost on restart or crash | +| `node-cron` and similar libraries | In-process memory only | Every instance runs the job unless you add external locking | Schedule resets on deploy; runs missed during downtime are skipped | +| External cron service | Lives outside your app | Needs a public HTTP endpoint plus its own dedupe and retry state | Survives your deploys but is separate infrastructure to operate | +| Rivet Actor scheduling | Persisted by the engine as a durable timer | Exactly one actor per key, so the timer is armed once rather than once per replica | Survives actor sleep, restart, upgrade, and crash | + +## Idempotency + +A scheduled action can fire more than you expect: a crash between doing the work and re-arming can cause the action to run again, and because schedules cannot be cancelled, an action can fire for an entry that was already removed. Design handlers so a duplicate firing is harmless: + +- **Store a run marker in state**: Keep a `lastRunAt` timestamp or a sequence number in actor state and update it inside the action. On each firing, compute elapsed time since the marker and skip or batch accordingly. The idle world actor's `collectProduction` does this with `lastCollectedAt` and whole-interval batching. +- **Tombstone guard for cancelled entries**: The example's `triggerReminder` looks the reminder up in `c.state.reminders` first and returns with a warning if it is gone, so a fire-after-cancel is a safe no-op. +- **Keep work and marker updates in the same action**: Actor state writes are persisted with the action, so updating the marker in the same handler that does the work keeps the two consistent. + +## Topology + +| Topology | Use When | Example Key | +| --- | --- | --- | +| Singleton job actor | One global job such as a nightly report or cleanup pass | `job["daily-report"]` | +| Actor per scheduled entity | Per-user or per-resource timers such as reminders, trials, or billing periods | `reminder[userId]` | + +The Scheduling example uses a single shared `reminderActor["main"]` key for demo simplicity. For production reminder systems, prefer one actor per user so timers, state, and load are isolated per entity. See [Keys](/docs/actors/keys). + +## Reminder Service Example + +| Topic | Summary | +| --- | --- | +| Scheduling | One-shot timers armed with `c.schedule.after(delayMs, "triggerReminder", reminder.id)` or `c.schedule.at(timestamp, "triggerReminder", reminder.id)`. | +| State | JSON state holding `reminders` and `completedCount`; the scheduled action mutates state when it fires. | +| Events | `triggerReminder` broadcasts a `reminderTriggered` event to all connected clients. See [Events](/docs/actors/events). | +| Cancellation | `cancelReminder` only removes the reminder from state; the scheduled action may still fire and no-ops via a state lookup guard. | + +**Actors** + +- **Key**: `reminderActor["main"]` +- **Responsibility**: Stores reminders in persistent state, arms a future self-action per reminder via `c.schedule`, marks reminders completed when the scheduled action fires, and broadcasts `reminderTriggered` to connected clients. +- **Actions** + - `scheduleReminder` + - `scheduleReminderAt` + - `triggerReminder` + - `getReminders` + - `cancelReminder` + - `getStats` +- **Queues** + - None +- **State** + - JSON + - `reminders` + - `completedCount` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant R as reminderActor + participant E as Engine + + C->>R: scheduleReminder(message, delayMs) + R->>E: schedule.after(delayMs, triggerReminder, id) + Note over E: schedule persisted + alarm armed + R-->>C: reminder + Note over R: actor sleeps + E->>R: alarm fires, actor wakes + Note over R: triggerReminder(id) runs + R-->>C: reminderTriggered event + Note over R: recurring jobs re-arm here with schedule.after +``` + +## Security Checklist + +The example is intentionally open: any client can connect to the shared `["main"]` key and schedule or cancel anything. Treat all of the following as required extensions for production: + +- **Validate schedule inputs**: Clamp `delayMs` and `timestamp` from clients. Reject negative delays, timestamps in the past, and absurdly far-future deadlines, and bound message or payload sizes. +- **Never schedule client-chosen actions**: Expose specific actions like `scheduleReminder` that internally arm a fixed callback. Do not pass a client-supplied action name or unchecked args into `c.schedule`. +- **Authenticate and scope keys**: Add connection [authentication](/docs/actors/authentication) and use per-user actor keys instead of one global key, so users cannot read or cancel each other's schedules. +- **Prune completed entries**: The example's `reminders` array grows without bound. Remove or archive completed entries so state stays small. +- **Use stable IDs**: Generate entry IDs with `crypto.randomUUID()` rather than timestamp-plus-random strings. + +_Source doc path: /cookbook/cron-jobs_ diff --git a/.agents/skills/chat-room/reference/cookbook/live-cursors.md b/.agents/skills/chat-room/reference/cookbook/live-cursors.md new file mode 100644 index 0000000..71c94ab --- /dev/null +++ b/.agents/skills/chat-room/reference/cookbook/live-cursors.md @@ -0,0 +1,152 @@ +# Live Cursors and Presence + +> Source: `src/content/cookbook/live-cursors.mdx` +> Canonical URL: https://rivet.dev/cookbook/live-cursors +> Description: Live cursors and multiplayer presence with Rivet Actors: per-connection cursor state, realtime updates over events or raw WebSockets, and throttling. + +--- +Patterns for building live cursors, multiplayer presence, and realtime cursor sharing with RivetKit. One room actor fans cursor positions out to every connected client, keyed per room with [actor keys](/docs/actors/keys). + +## Starter Code + +Start with one of the two working variants on GitHub. Both implement the same collaborative cursor canvas with persistent text labels; they differ only in transport. + +| Variant | Starter Code | Transport | Presence Storage | +| --- | --- | --- | --- | +| `cursors` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/cursors) | Typed [actions](/docs/actors/actions) and [events](/docs/actors/events) over the RivetKit connection | `connState` per connection | +| `cursors-raw-websocket` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/cursors-raw-websocket) | Raw [`onWebSocket` handler](/docs/actors/websocket-handler) with a custom JSON message protocol | Socket map in `createVars` | + +Use `cursors` by default: typed actions, typed events, and automatic connection tracking cover most apps with less code. Use `cursors-raw-websocket` when you need full control of the wire format, for example a custom JSON or binary protocol, or clients that do not use the RivetKit client library. + +## Connection State vs Persistent State + +Presence is ephemeral by definition. A cursor position is only meaningful while its connection is alive, so it belongs in per-connection storage, not in persistent actor state. Persistent state is reserved for data that must survive disconnects and actor restarts. + +| Data | Where It Lives | Why | +| --- | --- | --- | +| Cursor position | `connState` (`cursors`) or the `createVars` socket map (`cursors-raw-websocket`) | Scoped to one connection and discarded with it. Stale presence cannot accumulate in storage. | +| Text labels (`textLabels`) | Persistent actor `state` in both variants | Canvas content must survive disconnects and actor restarts. | + +In the `cursors` variant, `updateCursor` writes `c.conn.state.cursor` and `getRoomState` rebuilds the presence snapshot by iterating `c.conns.values()`, so the cursor map is always derived from live connections rather than stored. See [Connections](/docs/actors/connections) for `connState` and [State](/docs/actors/state) for persistence semantics. + +## Presence Lifecycle + +- **Join**: The `cursors-raw-websocket` variant pushes an `init` message with the current `{ cursors, textLabels }` snapshot as soon as a socket connects. The `cursors` variant has no explicit join broadcast; the client calls the `getRoomState` action once after connecting to seed its local maps, and peers first see a new user on that user's first `cursorMoved` broadcast. +- **Move**: Every `updateCursor` call writes the connection's presence entry, then broadcasts `cursorMoved` to all connections, including the sender. +- **Leave**: The `cursors` variant handles leave in `onDisconnect`, broadcasting `cursorRemoved` with the connection's last cursor. The raw variant does the same from the socket `close` listener, then deletes the session from the `vars.websockets` map. Clients delete that user from their local cursor map, so stale cursors disappear the moment a tab closes. + +See [Lifecycle](/docs/actors/lifecycle) for `onDisconnect` and `createVars`. + +## Update Throttling + +Neither example throttles. Both frontends send a cursor update on every raw `mousemove` event with no debounce or interval cap. That is fine for a demo, but a fast mouse on a high-refresh display can emit hundreds of events per second per user. The patterns below are recommended production hardening on top of the starter code, not something the examples implement. + +| Layer | Pattern | Guidance | +| --- | --- | --- | +| Client (smoothness) | Throttle to 20-30Hz | Sample the latest pointer position every 33-50ms and send only that. Drop intermediate moves, but always flush the final position so cursors settle at the true location. Interpolate between received positions on the rendering side. | +| Server (enforcement) | Per-connection rate limit | Track the last accepted update timestamp per connection and drop or coalesce updates arriving faster than your cap. Client throttles are cooperative; the actor is the enforcement boundary. | + +## Actors + +- **Key**: `cursorRoom[roomId]` (the frontend defaults `roomId` to `"general"`) +- **Responsibility**: Holds per-connection cursor presence in `connState`, persists shared text labels in actor state, and broadcasts cursor and text updates to all connections. +- **Actions** + - `updateCursor` + - `updateText` + - `removeText` + - `getRoomState` +- **Events** + - `cursorMoved` + - `cursorRemoved` + - `textUpdated` + - `textRemoved` +- **Queues** + - None +- **State** + - JSON + - `textLabels` (persistent) + - `connState.cursor` per connection (ephemeral) + +- **Key**: `cursorRoom[roomId]` (resolved via `client.cursorRoom.getOrCreate(roomId)`) +- **Responsibility**: Exposes a raw WebSocket endpoint, tracks live sockets and their cursors in a `createVars` map keyed by a `sessionId` query parameter, persists text labels, and manually fans JSON frames out to every socket. +- **Actions** + - `getOrCreate` (stub returning `{ status: "ok" }`; the frontend resolves the actor ID with the client handle's `getOrCreate(roomId).resolve()`, which creates the actor without dispatching this action) + - `getRoomState` +- **Queues** + - None +- **State** + - JSON + - `textLabels` (persistent) + - `vars.websockets` map of `sessionId` to socket and cursor (in-memory, lost on restart) + +The raw variant defines no RivetKit events. Its message names are `type` fields on raw JSON frames: + +| Direction | Message `type` | Payload | +| --- | --- | --- | +| Client to server | `updateCursor` | `{ userId, x, y }` | +| Client to server | `updateText` | `{ id, userId, text, x, y }` | +| Client to server | `removeText` | `{ id }` | +| Server to client | `init` | `{ cursors, textLabels }` snapshot on connect | +| Server to client | `cursorMoved`, `textUpdated`, `textRemoved`, `cursorRemoved` | The corresponding cursor, label, or ID payload | + +## Lifecycle + +### cursors (Actions + Events) + +```mermaid +sequenceDiagram + participant A as Client A + participant R as cursorRoom + participant B as Other Clients + + A->>R: connect via useActor (cursorRoom[roomId]) + A->>R: getRoomState() + R-->>A: {cursors, textLabels} + loop every mouse move + A->>R: updateCursor(userId, x, y) + Note over R: write c.conn.state.cursor + R-->>B: cursorMoved (broadcast) + end + A->>R: updateText(id, userId, text, x, y) + Note over R: upsert persistent state.textLabels + R-->>B: textUpdated (broadcast) + Note over A: tab closes + Note over R: onDisconnect reads conn.state.cursor + R-->>B: cursorRemoved (broadcast) +``` + +### cursors-raw-websocket + +```mermaid +sequenceDiagram + participant A as Client A + participant R as cursorRoom + participant B as Other Clients + + A->>R: getOrCreate(roomId).resolve() + R-->>A: actorId + A->>R: open WebSocket /gateway/{actorId}/websocket?sessionId=... + Note over R: close 1008 if sessionId is missing + Note over R: store socket in vars.websockets + R-->>A: init {cursors, textLabels} + loop every mouse move + A->>R: {type: "updateCursor"} frame + Note over R: update session cursor in vars + R-->>B: cursorMoved frame + end + Note over A: socket closes + R-->>B: cursorRemoved frame + Note over R: delete session from vars.websockets +``` + +## Security Checklist + +Both examples ship without authentication so the presence pattern stays readable. Everything below is recommended hardening for production, not behavior the examples implement. + +- **Identity**: Bind presence identity to the connection (`c.conn.id` in the actions variant, a server-generated session ID in the raw variant). Never trust a client-supplied `userId`; in the examples it is a random client-generated string, so any client can impersonate or remove any cursor. +- **Authorization**: Authorize label mutations by owner. In the examples, `updateText` accepts arbitrary `id` and `userId` arguments and `removeText` accepts an arbitrary `id`, so any client can edit or delete any label. +- **Input validation**: Clamp `x` and `y` to canvas bounds, cap text label length, and cap the total `textLabels` count so persistent state cannot grow unbounded. +- **Rate limiting**: Enforce a per-connection cap on `updateCursor` (for example 30Hz) and on label writes, as described in [Update Throttling](#update-throttling). +- **Protocol strictness (raw variant)**: Validate message shape before use and close the socket on malformed JSON instead of logging and continuing. Reject duplicate `sessionId` values rather than silently overwriting another session's socket entry. + +_Source doc path: /cookbook/live-cursors_ diff --git a/.agents/skills/chat-room/reference/cookbook/multiplayer-game.md b/.agents/skills/chat-room/reference/cookbook/multiplayer-game.md new file mode 100644 index 0000000..425b113 --- /dev/null +++ b/.agents/skills/chat-room/reference/cookbook/multiplayer-game.md @@ -0,0 +1,713 @@ +# Multiplayer Game + +> Source: `src/content/cookbook/multiplayer-game.mdx` +> Canonical URL: https://rivet.dev/cookbook/multiplayer-game +> Description: Pragmatic patterns for building multiplayer games: matchmaking, tick loops, realtime state, interest management, and validation. + +--- +Patterns for building multiplayer games with RivetKit, intended as a practical checklist you can adapt per genre. + +## Starter Code + +Start with one of the working examples on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/) and adapt it to your game. Do not start from scratch for matchmaking and lifecycle flows. + +| Game Classification | Starter Code | Common Examples | +| --- | --- | --- | +| Battle Royale | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/battle-royale/) | Fortnite, Apex Legends, PUBG, Warzone | +| Arena | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/arena/) | Call of Duty TDM/FFA, Halo Slayer, Counter-Strike casual, VALORANT unrated, Overwatch Quick Play, Rocket League | +| IO Style | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/io-style/) | Agar.io, Slither.io, surviv.io | +| Open World | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/open-world/) | Minecraft survival servers, Rust-like worlds, MMO zone/chunk worlds | +| Party | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/party/) | Fall Guys private lobbies, custom game rooms, social party sessions | +| Physics 2D | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-2d/) | Top-down physics brawlers, 2D arena games, platform fighters | +| Physics 3D | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-3d/) | Physics sandbox sessions, 3D arena games, movement playgrounds | +| Ranked | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/ranked/) | Chess ladders, competitive card games, duel arena ranked queues | +| Turn-Based | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/turn-based/) | Chess correspondence, Words With Friends, async board games | +| Idle | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/idle/) | Cookie Clicker, Idle Miner Tycoon, Adventure Capitalist | + +## Server Simulation + +### Game Loop And Tick Rates + +| Pattern | Use When | Implementation Guidance | +| --- | --- | --- | +| Fixed realtime loop | Battle Royale, Arena, IO Style, Open World, Ranked | Run in `run` with `sleep(tickMs)` and exit on `c.aborted`. | +| Action-driven updates | Party, Turn-Based | Mutate and broadcast only on actions/events rather than scheduled ticks. | +| Coarse offline progression | Any mode with idle progression | Use `c.schedule.after(...)` with coarse windows (for example 5 to 15 minutes) and apply catch-up from elapsed wall clock time. | + +### Physics + +Start with custom kinematic logic for simple games. Switch to a full physics engine when you need joints, stacked bodies, high collision density, or complex shapes (rotated polygons, capsules, convex hulls, triangle meshes). + +Pick one engine per simulation. Keep frontend-only libs out of backend simulation paths and treat server state as authoritative. + +| Dimension | Primary Engine | Fallback Engines | Example Code | +| --- | --- | --- | --- | +| 2D | `@dimforge/rapier2d` | `planck-js`, `matter-js` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-2d/) | +| 3D | `@dimforge/rapier3d` | `cannon-es`, `ammo.js` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-3d/) | + +### Spatial Indexing + +For non-physics spatial queries, use a dedicated index instead of naive `O(n^2)` checks: + +| Index Type | Recommendation | +| --- | --- | +| AABB index | For AOI, visibility, and non-collider entities, use `rbush` for dynamic sets or `flatbush` for static-ish sets. | +| Point index | For nearest-neighbor or within-radius queries, use `d3-quadtree`. | + +## Networking & State Sync + +### Netcode + +| Model | When To Use | Implementation | +| --- | --- | --- | +| Hybrid (client movement, server combat) | Shooters, action sports, ranked duels | Client owns movement and sends capped-rate position updates. Server validates for anti-cheat. Combat (projectiles, hits, damage) is fully server-authoritative. | +| Server-authoritative with interpolation | IO Style, persistent worlds | Client sends input commands. Server simulates on fixed ticks and publishes authoritative snapshots. Client interpolates between snapshots. | +| Server-authoritative (basic logic) | Turn-based, event-driven | Server validates and applies discrete actions (turns, phase transitions, votes). Client displays confirmed state. | + +### Realtime Data Model + +- **Snapshots and diffs**: Publish state as events. Send a full snapshot on join/resync, then per-tick diffs for regular updates. +- **Batch per tick**: Keep events small and typed. Batch high-frequency updates per tick. +- **Avoid UI framework state for game updates**: Use `requestAnimationFrame` or a Canvas/Three.js loop for simulation, not React state. Reserve UI framework state for menus, HUD, and forms. +- **Broadcast vs per-connection**: Use `c.broadcast(...)` for shared updates and `conn.send(...)` for private/per-player data. + +### Shared Simulation Logic + +Shared simulation logic runs on both the client and the server. For example, an `applyInput(state, input, dt)` function that integrates velocity and clamps to world bounds can run on the client for prediction and on the server for validation. + +- **Hybrid modes**: Client runs shared movement as primary authority, server runs it for anti-cheat validation. +- **Server-authoritative modes**: Client uses shared logic for interpolation and prediction only. +- **Keep it pure**: Movement integration, input transforms, collision helpers, and constants only. +- **Put shared code in `src/shared/`**: Keep deterministic helpers in `src/shared/sim/*` with no side effects. + +### Interest Management + +Control what each client receives to reduce bandwidth and prevent information leaks. + +#### Per-Player Replication Filters + +- **Filter by relevance**: Send each client only state relevant to that player (proximity, line-of-sight, team, or game phase). +- **Shooters and action games**: Limit replication by proximity and optional field-of-view checks. +- **Server-side only**: Clients should never receive data they should not see. + +#### Sharded Worlds + +- **Partition large worlds**: Use chunk actors keyed by `worldId:chunkX:chunkY`. +- **Subscribe to nearby chunks**: Clients connect only to nearby partitions (for example a 3x3 chunk window). +- **Use sparingly**: Only when the world is large and state-heavy (sandbox builders, MMOs), not as a default for small matches. + +## Backend Infrastructure + +### Persistence + +- **In-memory state**: Best for realtime game state that changes every tick (player positions, inputs, match phase, scores). +- **SQLite (`rivetkit/db`)**: Better for large or table-like state that needs queries, indexes, or long-term persistence (tiles, inventory, matchmaking pools). Serialize DB work through a queue since multiple actions can hit the same actor concurrently. + +### Matchmaking Patterns + +Common building blocks used across the architecture patterns below. + +#### Actor Topology + +| Primitive | Use When | Typical Ownership | +| --- | --- | --- | +| `matchmaker["main"]` + `match[matchId]` | Session-based multiplayer (battle royale, arena, ranked, party, turn-based) | Matchmaker owns discovery/assignment. Match owns lifecycle and gameplay state. | +| `chunk[worldId,chunkX,chunkY]` | Large continuous worlds that need sharding | Each chunk owns local players, chunk state, and local simulation. | +| `world[playerId]` | Per-player progression loops (idle/solo world state) | Per-player resources, buildings, timers, and progression. | +| `player[username]` | Canonical profile/rating reused across matches | Durable player stats (for example rating and win/loss). | +| `leaderboard["main"]` | Shared rankings across many matches/players | Global ordered score rows and top lists. | + +#### Queueing Strategy + +- Multiple players can hit the matchmaker at the same time, so actions like find/create, queue/unqueue, and close need to be serialized through actor queues to avoid races. +- Match-local actions (gameplay, scoring) do not need queueing unless they write back to the matchmaker. + +## Security And Anti-Cheat + +Start with this baseline, then harden further for competitive or high-risk environments. + +### Baseline Checklist + +- **Identity**: Use `c.conn.id` as the authoritative transport identity. Treat `playerId`/`username` in params as untrusted input and bind through server-issued assignment/join tickets. +- **Authorization**: Validate the caller is allowed to mutate the target entity (room membership, turn ownership, host-only actions). +- **Input validation**: Clamp sizes/lengths, validate enums, and validate usernames (length, allowed chars, avoid unbounded Unicode). +- **Rate limiting**: Per-connection rate limits for spammy actions (chat, join/leave, fire, movement updates). +- **State integrity**: Server recomputes derived state (scores, win conditions, placements). Never allow client-authoritative changes to inventory/currency/leaderboard totals. + +### Movement Validation + +For any mode with client-authoritative movement (hybrid flows), clients may send position/rotation updates for smoothness, but the server must: + +- Enforce max delta per update (speed cap) based on elapsed time. +- Reject or clamp teleports. +- Enforce world bounds (and basic collision if applicable). +- Rate limit update frequency (for example 20Hz max). + +## Architecture Patterns + +Each game type below starts with a quick summary table, then details actors and lifecycle. + +### Battle Royale + +| Topic | Summary | +| --- | --- | +| Matchmaking | Immediate routing to the fullest non-started lobby (oldest tie-break); players wait in lobby until capacity, then the match starts. | +| Netcode | Hybrid. Client owns movement, camera, and local prediction. Server owns zone state, projectiles, hit resolution, eliminations, loot, and final placement. | +| Tick Rate | 10 ticks/sec (`100ms`) with a fixed loop for zone progression and lifecycle checks. | +| Physics | Client owns movement with server anti-cheat validation; projectiles, hits, and damage are server-authoritative. Use `@dimforge/rapier3d` for 3D or `@dimforge/rapier2d` for top-down 2D. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Finds or creates lobbies, tracks pending reservations, and maintains occupancy. +- **Actions** + - `findMatch` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **Queues** + - `findMatch` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **State** + - SQLite + - `matches` + - `pending_players` + - `player_count` includes connected and pending players + +- **Key**: `match[matchId]` +- **Responsibility**: Runs lobby/live/finished phases, owns player state, zone progression, and eliminations. +- **Actions** + - `connect` + - Movement and combat actions +- **Queues** + - None +- **State** + - JSON + - `phase` + - `players` + - `zone` + - `eliminations` + - `snapshot data` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant M as match + + C->>MM: findMatch() + alt no open lobby + MM->>M: create(matchId) + end + MM-->>C: {matchId, playerId} + C->>M: connect(playerId) + M->>MM: pendingPlayerConnected(matchId, playerId) + MM-->>M: accepted + Note over M: lobby countdown -> live + M-->>C: snapshot + shoot events + M->>MM: closeMatch(matchId) +``` + +### Arena + +| Topic | Summary | +| --- | --- | +| Matchmaking | Mode-based fixed-capacity queues (`duo`, `squad`, `ffa`) that build only full matches and pre-assign teams (except FFA). | +| Netcode | Hybrid. Client owns movement plus prediction and smoothing. Server owns team or FFA assignment, projectiles, hit resolution, phase transitions, and scoring. | +| Tick Rate | 20 ticks/sec (`50ms`) with a tighter loop for live team and FFA snapshots. | +| Physics | Medium to high intensity; client movement with server validation and server-authoritative combat/entities. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Runs mode queues, builds full matches, assigns teams, and publishes assignments. +- **Actions** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **Queues** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **State** + - SQLite + - `player_pool` + - `matches` + - `assignments` keyed by connection and player + +- **Key**: `match[matchId]` +- **Responsibility**: Runs match phases and in-match player/team state for score and win conditions. +- **Actions** + - `connect` + - Gameplay actions +- **Queues** + - None +- **State** + - JSON + - `phase` + - `players` + - `team assignments` + - `score and win state` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant M as match + + C->>MM: queueForMatch(mode) + Note over MM: enqueue in player_pool + Note over MM: fill when capacity reached + MM->>M: create(matchId, assignments) + Note over MM: persist assignments + MM-->>C: assignmentReady + C->>M: connect(playerId) + Note over M: waiting -> live when all players connect + M->>MM: matchCompleted(matchId) +``` + +### IO Style + +| Topic | Summary | +| --- | --- | +| Matchmaking | Open-lobby routing to the fullest room below capacity; room counts are heartbeated and new lobbies are auto-created when needed. | +| Netcode | Server-authoritative with interpolation. Client sends input intents and interpolates. Server owns movement, bounds, room membership, and canonical snapshots. | +| Tick Rate | 10 ticks/sec (`100ms`) with lightweight periodic room snapshots. | +| Physics | Low to medium intensity; server-authoritative kinematic movement, escalating to a physics engine only when collisions get complex. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Routes players into the fullest open lobby and tracks reservations and occupancy. +- **Actions** + - `findLobby` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **Queues** + - `findLobby` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **State** + - SQLite + - `matches` + - `pending_players` + - Occupancy includes pending reservations + +- **Key**: `match[matchId]` +- **Responsibility**: Runs per-match movement simulation and broadcasts snapshots. +- **Actions** + - `connect` + - `setInput` +- **Queues** + - None +- **State** + - JSON + - `players` + - `inputs` + - `movement state` + - `snapshot cache` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant M as match + + C->>MM: findLobby() + alt no open lobby + MM->>M: create(matchId) + end + MM-->>C: {matchId, playerId} + C->>M: connect(playerId) + M->>MM: pendingPlayerConnected(matchId, playerId) + MM-->>M: accepted + Note over M: fixed tick simulation + M-->>C: snapshot events + M->>MM: closeMatch(matchId) +``` + +### Open World + +| Topic | Summary | +| --- | --- | +| Matchmaking | Client-driven chunk routing from world coordinates, with nearby chunk windows preloaded via adjacent chunk connections. | +| Netcode | Hybrid for sandbox (client movement with validation) or server-authoritative for MMO-like flows. Server owns chunk routing, persistence, and canonical world state. | +| Tick Rate | 10 ticks/sec per chunk actor (`100ms`), so load scales with active chunks. | +| Physics | Medium to high at scale; chunk-local simulation can be server-authoritative (MMO-like) or client movement with server validation (sandbox-like). | + +**Actors** + +- **Key**: `chunk[worldId,chunkX,chunkY]` +- **Responsibility**: Owns chunk-local players, blocks, movement tick, and chunk membership. +- **Actions** + - `connect` + - `enterChunk` + - `addPlayer` + - `setInput` + - `leaveChunk` + - `removePlayer` +- **Queues** + - None +- **State** + - JSON + - `connections` + - `players` + - `blocks` scoped to one chunk key + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant CH as chunk + + Note over C: resolve chunk keys from world position + loop each visible chunk + C->>CH: connect(worldId, chunkX, chunkY, playerId) + Note over CH: store connection metadata + end + C->>CH: enterChunk/addPlayer + loop movement updates + C->>CH: setInput(...) + CH-->>C: snapshot + end + C->>CH: leaveChunk/removePlayer or disconnect + Note over CH: remove membership and metadata +``` + +### Party + +| Topic | Summary | +| --- | --- | +| Matchmaking | Host-created private party flow using party codes and explicit joins. | +| Netcode | Server-authoritative (basic logic). Server owns membership, host permissions, and phase transitions. | +| Tick Rate | No continuous tick; updates are event-driven (`join`, `start`, `finish`). | +| Physics | Low intensity for lobby-first flows; usually no dedicated physics or indexing unless you add realtime mini-games. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Handles party create/join flow, validates join tickets, and tracks party size. +- **Actions** + - `createParty` + - `joinParty` + - `verifyJoin` + - `updatePartySize` + - `closeParty` +- **Queues** + - `createParty` + - `joinParty` + - `verifyJoin` + - `updatePartySize` + - `closeParty` +- **State** + - SQLite + - `parties` + - `join_tickets` for party lookup and join validation + +- **Key**: `match[matchId]` +- **Responsibility**: Owns party members, host role, ready flags, and phase transitions. +- **Actions** + - `connect` + - `startGame` + - `finishGame` +- **Queues** + - None +- **State** + - JSON + - `members` + - `host` + - `ready state` + - `phase` + - `party events` + +**Lifecycle** + +### Host Flow + +```mermaid +sequenceDiagram + participant H as Host Client + participant MM as matchmaker + participant M as match + + H->>MM: createParty() + MM-->>H: {matchId, partyCode, playerId, joinToken} + H->>M: connect(playerId, joinToken) + M->>MM: verifyJoin(...) + MM-->>M: allowed + M->>MM: updatePartySize(playerCount) + H->>M: startGame() / finishGame() + M->>MM: closeParty(matchId) +``` + +### Joiner Flow + +```mermaid +sequenceDiagram + participant J as Joiner Client + participant MM as matchmaker + participant M as match + + J->>MM: joinParty(partyCode) + MM-->>J: {matchId, playerId, joinToken} + J->>M: connect(playerId, joinToken) + M->>MM: verifyJoin(...) + MM-->>M: allowed / denied + M->>MM: updatePartySize(playerCount) +``` + +### Ranked + +| Topic | Summary | +| --- | --- | +| Matchmaking | ELO-based queue pairing with a widening search window as wait time increases. | +| Netcode | Hybrid. Client owns movement with local prediction and interpolation. Server owns projectiles, hit resolution, match results, and rating updates. | +| Tick Rate | 20 ticks/sec (`50ms`) with fixed live ticks for deterministic pacing and broadcast cadence. | +| Physics | Medium to high intensity; client movement with server validation and server-authoritative combat/hit resolution. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Runs rating-based queueing, pairing, assignment persistence, and completion fanout. +- **Actions** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **Queues** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **State** + - SQLite + - `player_pool` + - `matches` + - `assignments` with rating window and connection scoping + +- **Key**: `match[matchId]` +- **Responsibility**: Runs ranked match phase, score, and winner reporting. +- **Actions** + - `connect` + - Gameplay actions +- **Queues** + - None +- **State** + - JSON + - `phase` + - `players` + - `score` + - `winner` + - `completion payload` + +- **Key**: `player[username]` +- **Responsibility**: Stores canonical player MMR and win/loss profile. +- **Actions** + - `initialize` + - `getRating` + - `applyMatchResult` +- **Queues** + - None +- **State** + - JSON + - `rating` + - `wins` + - `losses` + - `match counters` + +- **Key**: `leaderboard["main"]` +- **Responsibility**: Stores and serves top-ranked players. +- **Actions** + - `updatePlayer` +- **Queues** + - None +- **State** + - SQLite + - Leaderboard score rows + - Top-list ordering + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant P as player + participant M as match + participant LB as leaderboard + + C->>MM: queueForMatch(username) + MM->>P: initialize/getRating + P-->>MM: rating + Note over MM: store queue row + retry pairing + MM->>M: create(matchId, assigned players) + MM-->>C: assignmentReady + C->>M: connect(username) + M->>MM: matchCompleted(...) + MM->>P: applyMatchResult(...) + MM->>LB: updatePlayer(...) + Note over MM: remove matches + assignments rows +``` + +### Turn-Based + +| Topic | Summary | +| --- | --- | +| Matchmaking | Async private-invite and public-queue pairing in the same pattern. | +| Netcode | Server-authoritative (basic logic). Client can draft moves before submit. Server owns turn ownership, committed move log, turn order, and completion state. | +| Tick Rate | No continuous tick; move submission and turn transitions drive updates. | +| Physics | Very low intensity; no realtime physics loop, just discrete rules validation. Indexing is optional and mostly for board or query convenience at scale. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Handles private invite and public queue pairing for async matches. +- **Actions** + - `createGame` + - `joinByCode` + - `queueForMatch` + - `unqueueForMatch` + - `closeMatch` +- **Queues** + - `createGame` + - `joinByCode` + - `queueForMatch` + - `unqueueForMatch` + - `closeMatch` +- **State** + - SQLite + - `matches` + - `player_pool` + - `assignments` for invite and queue mapping + +- **Key**: `match[matchId]` +- **Responsibility**: Owns board state, turn order, move validation, and final result. +- **Actions** + - `connect` + - `makeMove` +- **Queues** + - None +- **State** + - JSON + - `board` + - `turns` + - `players` + - `connection presence` + - `result` + +**Lifecycle** + +### Public Queue + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant MM as matchmaker + participant M as match + + A->>MM: queueForMatch() + B->>MM: queueForMatch() + Note over MM: pair first two queued players + MM->>M: create(matchId) + seed X/O players + MM-->>A: assignment/match info + MM-->>B: assignment/match info + A->>M: connect(playerId) + B->>M: connect(playerId) + A->>M: makeMove() + B->>M: makeMove() + opt all players disconnected for timeout + Note over M: destroy after idle timeout + end + M->>MM: closeMatch(matchId) +``` + +### Private Invite + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant MM as matchmaker + participant M as match + + A->>MM: createGame() + MM-->>A: {matchId, playerId, inviteCode} + B->>MM: joinByCode(inviteCode) + MM->>M: create(matchId) + seed X/O players + MM-->>A: assignment/match info + MM-->>B: assignment/match info + A->>M: connect(playerId) + B->>M: connect(playerId) + A->>M: makeMove() + B->>M: makeMove() + M->>MM: closeMatch(matchId) +``` + +### Idle + +| Topic | Summary | +| --- | --- | +| Matchmaking | No matchmaker; each player uses a direct per-player actor and a shared leaderboard actor. | +| Netcode | Server-authoritative (basic logic). Client owns UI and build intent. Server owns resources, production rates, building validation, and leaderboard totals. | +| Tick Rate | No continuous tick; use `c.schedule.after(...)` for coarse intervals and compute offline catch-up from elapsed wall time. | +| Physics | None for standard idle loops; transitions are discrete (`build`, `collect`, `upgrade`) and do not need spatial indexing. | + +**Actors** + +- **Key**: `world[playerId]` +- **Responsibility**: Owns one player's progression, buildings, production scheduling, and state updates. +- **Actions** + - `initialize` + - `build` + - `collectProduction` +- **Queues** + - None +- **State** + - JSON + - Per-player buildings + - `resources` + - `timers` + - `progression state` + +- **Key**: `leaderboard["main"]` +- **Responsibility**: Stores global scores and serves leaderboard updates. +- **Actions** + - `updateScore` +- **Queues** + - `updateScore` +- **State** + - SQLite + - `scores` table keyed by player + - Current leaderboard totals + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant W as world + participant LB as leaderboard + + C->>W: getOrCreate(playerId) + initialize() + Note over W: seed state + schedule collection + W-->>C: stateUpdate + loop gameplay loop + C->>W: build() / collectProduction() + W->>LB: updateScore(...) + Note over LB: upsert scores + LB-->>C: leaderboardUpdate + W-->>C: stateUpdate + end +``` + +_Source doc path: /cookbook/multiplayer-game_ diff --git a/.agents/skills/chat-room/reference/cookbook/per-tenant-database.md b/.agents/skills/chat-room/reference/cookbook/per-tenant-database.md new file mode 100644 index 0000000..e3c5616 --- /dev/null +++ b/.agents/skills/chat-room/reference/cookbook/per-tenant-database.md @@ -0,0 +1,119 @@ +# Database per Tenant + +> Source: `src/content/cookbook/per-tenant-database.mdx` +> Canonical URL: https://rivet.dev/cookbook/per-tenant-database +> Description: Multi-tenant data isolation with one Rivet Actor per tenant: the actor key is the tenant id, so each tenant gets its own isolated dataset and migrations. + +--- +Patterns for database-per-tenant architectures with RivetKit. Instead of one shared database with a `tenant_id` column on every table, each tenant gets its own Rivet Actor, and that actor owns the tenant's entire dataset. + +## Starter Code + +Start with the working example on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/per-tenant-database) and adapt it. The example stores each tenant's dataset in JSON actor state and serves a React dashboard with live event updates. + +| Topic | Summary | +| --- | --- | +| Isolation | One `companyDatabase` actor per tenant, keyed by company name. Switching tenants swaps the entire dataset. | +| State | JSON actor state holding `employees` and `projects` arrays plus timestamps. No SQLite, no queues, no scheduling. | +| Realtime | Every write action mutates state, then broadcasts a typed event (`employeeAdded`, `projectAdded`) to all connected clients of that tenant. | +| Auth | None. The sign-in screen is cosmetic. Production guidance is in the [security checklist](#security-checklist). | + +## The Isolation Model + +The actor key is the tenant id. The client connects with `useActor({ name: "companyDatabase", key: [companyName] })` and the actor reads `c.key[0]` in `createState` to seed that tenant's dataset. This gives you: + +- **One actor per tenant**: `companyDatabase[tenantId]` addresses exactly one actor instance. Two tenants can never share an actor. +- **One dataset per tenant**: All reads and writes go through that actor's [state](/docs/actors/state), so there is no shared table with a `tenant_id` column to filter incorrectly. Cross-tenant leaks require constructing the wrong key, not forgetting a `WHERE` clause. +- **No key injection**: Keys are arrays, not interpolated strings. `key: [tenantId]` cannot be escaped the way `"tenant:" + tenantId` string concatenation can. See [Keys](/docs/actors/keys). + +The example's test ([tests/per-tenant-database.test.ts](https://github.com/rivet-dev/rivet/tree/main/examples/per-tenant-database/tests/per-tenant-database.test.ts)) proves the isolation: data written to `companyDatabase["Alpha Co"]` never appears in `companyDatabase["Beta Co"]`. + +## Choosing a State Backend + +The example uses plain JSON actor state. The same key-equals-tenant model works with any actor state backend. + +| Backend | Use When | Docs | Working Code | +| --- | --- | --- | --- | +| JSON actor state | Small datasets, simple reads, whole dataset fits comfortably in memory. What the example uses. | [State](/docs/actors/state) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/per-tenant-database) | +| Actor SQLite (`rivetkit/db`) | Tables, indexes, SQL queries, larger-than-memory data, per-tenant relational schema. | [SQLite](/docs/actors/sqlite) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/kitchen-sink/src/actors/state/sqlite-raw.ts) | +| SQLite + Drizzle | Typed schema, query builder, and generated migration files on top of actor SQLite. | [SQLite + Drizzle](/docs/actors/sqlite-drizzle) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/kitchen-sink/src/actors/state/sqlite-drizzle/) | + +With either SQLite option, every tenant gets its own embedded SQLite database, since the database is scoped to the actor and the actor is scoped to the tenant. + +## Migrations + +The per-tenant example has no migrations because JSON state has no schema. When you adopt SQLite, migrations run per tenant database: + +- **Raw SQL**: `db({ onMigrate })` runs your migration SQL inside a SQLite savepoint before the actor serves traffic. If `onMigrate` throws, all migration SQL rolls back atomically and the actor does not start. See [SQLite](/docs/actors/sqlite). +- **Drizzle**: `drizzle-kit` generates migration files from your typed schema, and `db({ schema, migrations })` applies them when the actor wakes. See [SQLite + Drizzle](/docs/actors/sqlite-drizzle). + +Because each tenant has its own database, migrations roll out per actor as each tenant's actor wakes, rather than as one large migration against a shared database. + +## Tenant Id Must Come From Auth + +The example's sign-in is cosmetic: the client picks any company string and that string becomes the actor key, so any visitor can read and write any tenant's data. Do not ship this. As a required production extension (not implemented by the example): + +- Derive the tenant id from a verified credential, such as a JWT claim, never from user input. +- Validate the credential against `c.key` in `onBeforeConnect` (pass/fail) or `createConnState` (store the verified user on connection state). See [Authentication](/docs/actors/authentication) and [Connections](/docs/actors/connections). +- Add per-action permission checks on top of connection-level auth. See [Access Control](/docs/actors/access-control). + +## Actors + +- **Key**: `companyDatabase[companyName]` (single-element array key; `c.key[0]` is the company name) +- **Responsibility**: One actor per tenant. Holds that company's employees and projects in persistent state, serves reads and writes via actions, and broadcasts mutations to connected clients. +- **Actions** + - `addEmployee` + - `listEmployees` + - `addProject` + - `listProjects` + - `getStats` +- **Queues** + - None +- **Events** + - `employeeAdded` + - `projectAdded` +- **State** + - JSON + - `company_name` + - `employees` + - `projects` + - `created_at` + - `updated_at` + +Every write action follows the same mutate-then-broadcast shape: push the record into `c.state`, bump `updated_at`, broadcast the typed event, return the record. See [Actions](/docs/actors/actions) and [Events](/docs/actors/events). + +## Lifecycle + +```mermaid +sequenceDiagram + participant A as Tenant A client + participant DA as companyDatabase A + participant B as Tenant B client + participant DB as companyDatabase B + + Note over A: authenticate and derive tenant id + A->>DA: connect with key [tenantA] + Note over DA: createState seeds company_name, employees, projects + A->>DA: listEmployees() + listProjects() + getStats() + A->>DA: addEmployee(name, role) + DA-->>A: employeeAdded event + B->>DB: connect with key [tenantB] + Note over DB: separate actor, separate dataset + B->>DB: listEmployees() + DB-->>B: tenant B data only +``` + +In the example, the "authenticate" step is a free-text company picker. The rest of the flow matches the diagram: `createState` seeds the dataset on first creation, the dashboard loads with `listEmployees`, `listProjects`, and `getStats`, and every connected client of the same tenant receives `employeeAdded` and `projectAdded` events. + +## Security Checklist + +The example ships with none of these. Apply all of them before production. + +- **Tenant identity**: Derive the tenant id from a verified JWT claim, never from a client-supplied string. +- **Connection validation**: In `onBeforeConnect` or `createConnState`, verify the credential's tenant claim matches `c.key` and reject mismatches. +- **Per-action authorization**: Check the caller's role before mutating actions (`addEmployee`, `addProject`), not just at connect time. See [Access Control](/docs/actors/access-control). +- **Input validation**: Clamp name and role lengths and validate enums. The example only trims input and substitutes fallback defaults. +- **Key construction**: Always pass the tenant id as an array element (`key: [tenantId]`). Never interpolate tenant ids into key strings, and never build keys from one tenant's input to address another tenant's actor. +- **Growth limits**: As a recommended extension, cap or paginate the `employees` and `projects` arrays. The example lets them grow unboundedly in JSON state; move to [SQLite](/docs/actors/sqlite) when the dataset outgrows memory. + +_Source doc path: /cookbook/per-tenant-database_ diff --git a/.agents/skills/chat-room/reference/cookbook/vpc-air-gapped.md b/.agents/skills/chat-room/reference/cookbook/vpc-air-gapped.md new file mode 100644 index 0000000..f7d87a3 --- /dev/null +++ b/.agents/skills/chat-room/reference/cookbook/vpc-air-gapped.md @@ -0,0 +1,136 @@ +# Deploying Rivet in a VPC or Air-Gapped Network + +> Source: `src/content/cookbook/vpc-air-gapped.mdx` +> Canonical URL: https://rivet.dev/cookbook/vpc-air-gapped +> Description: Run Rivet entirely inside your own perimeter: single-binary or Docker Compose install, file system storage with no database infrastructure, and no outbound telemetry by default. + +--- +Patterns for running self-hosted Rivet inside a private network: a VPC without internet egress, an on-premises rack, or a fully air-gapped environment. The engine is one service, the recommended single-node storage backend is the local file system, and the engine makes no outbound connections by default. Self-hosting is the only Rivet deployment model that supports air-gapped networks; see the [Self-Hosting Overview](/docs/self-hosting) for the full comparison with BYOC. + +## What Runs Inside the Perimeter + +A self-hosted deployment has three components, all of which live inside your network: + +| Component | Role | Inside the perimeter | +| --- | --- | --- | +| Your backend | Your application server, including the runner that executes actor code | Yes | +| Rivet Engine | Orchestration service that manages actor lifecycle, routes messages, and serves the dashboard and APIs | Yes | +| Storage | Persistence for actor state. Local file system for single-node, PostgreSQL or FoundationDB for multi-node | Yes | + +There is no license server, no Rivet Cloud account, and no callback to `rivet.dev`. Clients inside the perimeter reach actors through the engine's gateway over your private network. See [Architecture](/docs/self-hosting#architecture). + +## Single-Binary Install + +The engine compiles to a single `rivet-engine` binary. Build it from source outside the perimeter, then copy the binary across the boundary: + +```bash +git clone https://github.com/rivet-dev/rivet.git +cd rivet +cargo build --release -p rivet-engine +# Copy target/release/rivet-engine into the perimeter. +``` + +Prebuilt binaries are coming soon; see [Installing Rivet Engine](/docs/self-hosting/install) for current options. + +Run it with the file system backend, which stores everything on local disk and is the production-ready choice for single-node deployments. The [File System](/docs/self-hosting/filesystem) docs list air-gapped environments as a primary use case because it needs no database infrastructure: + +```bash +RIVET__database__file_system__path="/var/lib/rivet/data" ./rivet-engine +``` + +Configuration can also come from files. The engine discovers config at `/etc/rivet/config.json` on Linux (JSON, JSON5, JSONC, YAML, and YML are all supported), and `--config` overrides the path. Environment variables use the `RIVET__` prefix with `__` as the separator. See [Configuration](/docs/self-hosting/configuration). + +The engine serves its own dashboard on port `6420`, so inspection and namespace management work with nothing but a browser inside the perimeter. + +## Docker Compose Deployment + +For Docker hosts without registry access, move the engine image across the boundary the standard way: + +```bash +# Outside the perimeter. +docker pull rivetdev/engine:latest +docker save rivetdev/engine:latest -o rivet-engine.tar +# Inside the perimeter. +docker load -i rivet-engine.tar +``` + +Then run the engine and your app together in one Compose file: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - rivet-data:/data + environment: + RIVET__FILE_SYSTEM__PATH: "/data" + restart: unless-stopped + + my-app: + build: . + environment: + RIVET_ENDPOINT: "http://default:admin@rivet-engine:6420" + depends_on: + - rivet-engine + restart: unless-stopped + +volumes: + rivet-data: +``` + +`RIVET_ENDPOINT` uses the format `http://namespace:token@host:port` and tells your app to connect to the engine as a runner instead of running standalone. After both services start, register your runner with the engine through the dashboard or its API. The full walkthrough, including PostgreSQL setup for multi-node deployments, is in [Docker Compose](/docs/self-hosting/docker-compose). + +## No Outbound Telemetry + +The engine exports traces and metrics only when you opt in with OpenTelemetry. Export is disabled unless `RIVET_OTEL_ENABLED=1` is set, and the export target defaults to a local collector at `http://localhost:4317`. With no configuration, nothing crosses the perimeter. + +When you want observability, keep it inside the network: + +- Set `RIVET_OTEL_ENABLED=1` and point `RIVET_OTEL_GRPC_ENDPOINT` at a collector you run inside the perimeter. +- Adjust `RIVET_OTEL_SAMPLER_RATIO` to control trace sampling. +- Use the engine's health endpoint for liveness and readiness probes. + +See the [Production Checklist](/docs/self-hosting/production-checklist) for monitoring guidance. + +## Embedding Rivet in a Customer's Environment + +If you ship software that runs inside your customers' VPCs, the same setup turns Rivet into an internal component of your product rather than a service your customers must reach over the internet: + +- **Ship the engine next to your app.** Add `rivetdev/engine` to the Compose file or chart you already deliver. Your app finds it over the private network via `RIVET_ENDPOINT`, so one artifact deploys the whole stack. +- **One namespace per install.** The endpoint URL carries the namespace and token (`http://namespace:token@host:port`), so a single image works across customer deployments. See [Endpoints](/docs/general/endpoints). +- **Generate a strong admin token per install.** Replace the default token and keep it server-side. Never include the admin token in `RIVET_PUBLIC_ENDPOINT` or anywhere clients can read it. +- **Public endpoint only when needed.** `RIVET_PUBLIC_ENDPOINT` with a public (`pk_`) token is only required when browser clients connect to actors in [serverless runtime mode](/docs/general/runtime-modes). Backend-only deployments can skip it entirely. +- **TLS at the customer's edge.** Terminate TLS with the customer's reverse proxy or load balancer in front of the engine. + +## Scaling Past One Node + +| Backend | Use when | Status | +| --- | --- | --- | +| [File System](/docs/self-hosting/filesystem) (RocksDB-based) | Single-node deployments, including air-gapped installs | Production-ready, single node only | +| [PostgreSQL](/docs/self-hosting/postgres) | Multi-node deployments | Recommended for multi-node today, but experimental | +| FoundationDB | Largest production deployments | [Enterprise](/sales) | + +For multi-node deployments, run two or more engine nodes behind a load balancer and add NATS for pub/sub, which replaces the default PostgreSQL `LISTEN`/`NOTIFY` path at high throughput. Neither is needed for a single-node file system install. See the [Production Checklist](/docs/self-hosting/production-checklist). + +## Perimeter Checklist + +- **Admin token**: Generate a strong, random token for engine authentication and verify it is not exposed to clients. +- **TLS termination**: Encrypt connections to the engine via a reverse proxy or load balancer. +- **No public exposure**: Keep port `6420` reachable only from inside the perimeter unless clients outside it genuinely need access. +- **Health checks**: Configure liveness and readiness probes against the engine health endpoint. +- **Telemetry**: Leave OpenTelemetry export off, or point it at a collector inside the network. +- **Backups**: With the file system backend, back up the data directory. With PostgreSQL, configure automated backups and failover. + +## Full Configuration + +- [Self-Hosting Overview](/docs/self-hosting) for architecture and the self-host vs BYOC comparison +- [Installing Rivet Engine](/docs/self-hosting/install) for Docker, binary, and source installs +- [Docker Container](/docs/self-hosting/docker-container) and [Docker Compose](/docs/self-hosting/docker-compose) for container deployments +- [Kubernetes](/docs/self-hosting/kubernetes) for cluster deployments +- [Configuration](/docs/self-hosting/configuration) for every option and the full JSON schema +- [Endpoints](/docs/general/endpoints) for connecting your backend and clients +- [Production Checklist](/docs/self-hosting/production-checklist) before going live + +_Source doc path: /cookbook/vpc-air-gapped_ diff --git a/.agents/skills/chat-room/reference/deploy/aws-ecs.md b/.agents/skills/chat-room/reference/deploy/aws-ecs.md new file mode 100644 index 0000000..ab381ce --- /dev/null +++ b/.agents/skills/chat-room/reference/deploy/aws-ecs.md @@ -0,0 +1,13 @@ +# Deploying to AWS ECS + +> Source: `src/content/docs/deploy/aws-ecs.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/aws-ecs +> Description: Run your backend on Amazon ECS with Fargate. + +--- +See the [AWS ECS template](https://github.com/rivet-dev/template-aws-ecs) for deployment instructions: + +- [Deploy with Terraform](https://github.com/rivet-dev/template-aws-ecs#option-a-deploy-with-terraform) +- [Deploy with AWS CLI](https://github.com/rivet-dev/template-aws-ecs#option-b-deploy-with-aws-cli) + +_Source doc path: /docs/deploy/aws-ecs_ diff --git a/.agents/skills/chat-room/reference/deploy/aws-lambda.md b/.agents/skills/chat-room/reference/deploy/aws-lambda.md new file mode 100644 index 0000000..f1327cc --- /dev/null +++ b/.agents/skills/chat-room/reference/deploy/aws-lambda.md @@ -0,0 +1,10 @@ +# Deploy To Amazon Web Services Lambda + +> Source: `src/content/docs/deploy/aws-lambda.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/aws-lambda +> Description: _AWS Lambda is coming soon_ + +--- + + +_Source doc path: /docs/deploy/aws-lambda_ diff --git a/.agents/skills/chat-room/reference/deploy/cloudflare.md b/.agents/skills/chat-room/reference/deploy/cloudflare.md new file mode 100644 index 0000000..970078e --- /dev/null +++ b/.agents/skills/chat-room/reference/deploy/cloudflare.md @@ -0,0 +1,53 @@ +# Deploying to Cloudflare Workers + +> Source: `src/content/docs/deploy/cloudflare.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/cloudflare +> Description: Deploy an existing Rivet project to Cloudflare Workers. + +--- +This guide covers deploying an existing Rivet project to Cloudflare Workers. + +## Prerequisites + +- [Cloudflare account](https://dash.cloudflare.com/) +- [`wrangler`](https://developers.cloudflare.com/workers/wrangler/) configured for your account +- A Rivet namespace from the [Rivet Dashboard](https://dashboard.rivet.dev/) or a self-hosted Rivet Engine + +## Steps + +### Set up your project + +Follow the [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) to set up your project locally. + +### Configure Wrangler + +Set your Rivet connection values as Worker variables. Find `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` in the [Rivet Dashboard](https://dashboard.rivet.dev/) under **Settings → Namespace → Advanced → Backend Configuration** and copy them in. + +```toml wrangler.toml +name = "rivetkit-cloudflare" +main = "src/index.ts" +compatibility_date = "2025-04-01" +compatibility_flags = ["nodejs_compat"] + +[vars] +RIVET_ENDPOINT = "https://your-namespace:sk_...@api.rivet.dev" +RIVET_PUBLIC_ENDPOINT = "https://your-namespace@api.rivet.dev" +``` + +### Deploy + +```sh +npx wrangler deploy +``` + +### Register the Serverless Runner URL + +After deploy, set the Worker URL with the `/api/rivet` path as the serverless runner URL in Rivet. + +## Related + +- [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) +- [Deploying to Supabase Functions](/docs/deploy/supabase) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/deploy/cloudflare_ diff --git a/.agents/skills/chat-room/reference/deploy/container-runner.md b/.agents/skills/chat-room/reference/deploy/container-runner.md new file mode 100644 index 0000000..7bb0c5a --- /dev/null +++ b/.agents/skills/chat-room/reference/deploy/container-runner.md @@ -0,0 +1,95 @@ +# Container Runner + +> Source: `src/content/docs/deploy/container-runner.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/container-runner +> Description: Run any containerized server as a Rivet Actor. + +--- +The container runner (`rivet-container-runner`) is an adapter for running arbitrary containers as Rivet Actors. Use it for non-RivetKit workloads such as Unity or Godot dedicated game servers and batch jobs like FFmpeg transcoding. + +## Steps + +### Prerequisites + +- A containerized server (a Unity or Godot dedicated server, a plain Node process, or any HTTP/WebSocket server) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) +- Docker running locally + +### Install in Your Container + +Download the static binary from Rivet's release artifacts in your Dockerfile and set it as the entrypoint, passing your server's launch command after `--`: + +```dockerfile @nocheck +FROM debian:bookworm-slim +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl && rm -rf /var/lib/apt/lists/* + +# Install the Rivet container runner. +RUN curl -fsSL https://releases.rivet.dev/rivet/latest/container-runner/rivet-container-runner-x86_64-unknown-linux-musl \ + -o /usr/local/bin/rivet-container-runner \ + && chmod +x /usr/local/bin/rivet-container-runner + +# Your server binary and assets. +COPY build/ /game/ +WORKDIR /game + +ENTRYPOINT ["rivet-container-runner", "--", "./GameServer", "-batchmode", "-nographics", "-logFile", "-"] +``` + +Artifacts are published for `x86_64-unknown-linux-musl` and `aarch64-unknown-linux-musl`. The binaries are fully static, so they run in any Linux base image, including `scratch`. Pin a version by replacing `latest` with a release version, for example `https://releases.rivet.dev/rivet/2.3.3/container-runner/rivet-container-runner-x86_64-unknown-linux-musl`. + +### Deploy + +Deploy the image to [Rivet Compute](/docs/deploy/rivet-compute) with the CLI. For game servers, configure the pool with one actor per instance: + +```bash +npx @rivetkit/cli deploy \ + --token "$RIVET_CLOUD_TOKEN" \ + --instance-request-concurrency 1 \ + --dockerfile Dockerfile +``` + +### Create Actors and Connect Clients + +Create actors against the pool's runner (`default`) and connect clients through the gateway URL shown in the dashboard. WebSocket clients connect at the bare gateway URL with the `rivet` WebSocket subprotocol. + +## How It Works + +1. The engine cold-starts your container and calls `POST /api/rivet/start` on the port it injects as `RIVET_PORT`. +2. The runner spawns your server as a child process with `PORT` set to the child port, waits for the port to open, and reports the actor as running. +3. Gateway traffic for the actor arrives over Rivet's tunnel and is proxied to `127.0.0.1:`. WebSocket clients connect at the bare gateway URL with the `rivet` WebSocket subprotocol. Raw HTTP reaches the child under the `/request/*` prefix on the actor surface (the prefix is stripped before proxying); other paths are reserved for the runtime's own endpoints. +4. Child stdout and stderr are re-emitted with an `[actorId=... key=...]` prefix so actor logs are attributed in the dashboard. +5. When an actor stops, the runner sends its child `SIGTERM`, escalates to `SIGKILL` after a grace period, and exits the process once no actors remain. + +## Configuration + +All flags can also be set through environment variables: + +| Flag | Environment variable | Default | Description | +| --- | --- | --- | --- | +| `--port` | `RIVET_PORT` / `PORT` | `8080` | Serverless front-door HTTP port. Rivet Compute injects `RIVET_PORT` automatically. | +| `--child-port` | `CHILD_PORT` | `7770` | First local child port; each actor's child gets the next free port at or above this, exported to the child as `PORT`. | +| `--actor-name` | `RIVET_ACTOR_NAME` | `game` | Actor name this runner serves. | +| `--runner-version` | `RIVET_RUNNER_VERSION` | `1` | Version reported to the engine, used to drain old runners on deploy. | +| `--base-path` | `RIVET_SERVERLESS_BASE_PATH` | `/api/rivet` | Base path the engine calls for serverless start. | +| `--stop-grace-secs` | `RIVET_STOP_GRACE_SECS` | `25` | `SIGTERM` to `SIGKILL` grace period when stopping the child. Capped to a few seconds when the platform itself is reclaiming the instance, so shutdown fits inside the platform's own kill window. | +| `--readiness-timeout-secs` | `RIVET_READINESS_TIMEOUT_SECS` | `30` | How long to wait for the child's port to open before failing the start. | + +### Per-Actor Input + +The actor's `input` payload can override the launch spec per actor. All fields are optional and fall back to the entrypoint command. RivetKit clients pass this object directly; when creating actors through the raw engine API, encode it as CBOR before base64-encoding the `input` field: + +```json +{ + "command": ["./GameServer", "-batchmode"], + "args": ["-extra-flag"], + "env": { "MATCH_MODE": "ranked" } +} +``` + +`command` replaces the entrypoint command template, `args` are appended to it, and `env` adds environment variables for the child. + +## Source and Examples + +The runner and a full end-to-end example, including a Unity FishNet demo project and a local test harness, live in the Rivet repository under [`container-runner/`](https://github.com/rivet-dev/rivet/tree/main/container-runner). + +_Source doc path: /docs/deploy/container-runner_ diff --git a/.agents/skills/chat-room/reference/deploy/freestyle.md b/.agents/skills/chat-room/reference/deploy/freestyle.md new file mode 100644 index 0000000..eb6ed57 --- /dev/null +++ b/.agents/skills/chat-room/reference/deploy/freestyle.md @@ -0,0 +1,136 @@ +# Deploying to Freestyle + +> Source: `src/content/docs/deploy/freestyle.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/freestyle +> Description: Deploy RivetKit app to Freestyle.sh, a cloud platform for running AI-generated code with built-in security and scalability. + +--- +Freestyle provides built-in security for running untrusted AI-generated code, making it ideal for AI agent applications. Using Rivet, it is easy to deploy your vibe-coded or user-provided RivetKit backends straight to Freestyle. + +- [Freestyle + Rivet](https://github.com/rivet-dev/rivet/tree/main/examples/freestyle) — Complete example of deploying RivetKit app to Freestyle.sh. + +## Setup + +### Install packages + +Install RivetKit and Hono and create your registry: + +```bash +npm install rivetkit hono +``` + +### Configure serverless driver + +Update your server code to run the registry serverless with Deno. + +```typescript index.ts @hide +import { actor, setup } from "rivetkit"; + +export const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, x: number) => { + c.state.count += x; + return c.state.count; + }, + }, +}); + +export const registry = setup({ + use: { counter }, +}); +registry.start(); +``` + +```typescript server.ts @nocheck +import { registry } from "./index"; + +// Freestyle uses Deno under the hood for web deployments +// @ts-ignore Deno is a Freestyle runtime global +Deno.serve((request: Request) => registry.handler(request)); +``` + +The `Deno.serve` API is provided by Freestyle's runtime environment. The `@ts-ignore` comment suppresses TypeScript errors for this platform-specific API. + +### Deploy to Freestyle + +Deploy your application to Freestyle with the correct configuration. Create a deployment script or add this to your existing deployment process: + +```typescript @nocheck +const FREESTYLE_DOMAIN = "my-domain.style.dev"; // Change to your desired Freestyle domain + +declare const freestyle: any; +declare const buildDir: string; + +const res = await freestyle.deployWeb(buildDir, { + envVars: { + FREESTYLE_ENDPOINT: `https://${FREESTYLE_DOMAIN}`, + RIVET_RUNNER_KIND: "serverless", + // For self-hosted instances: + // RIVET_ENDPOINT: "http://127.0.0.1:6420", + RIVET_ENDPOINT: "api.rivet.dev", + }, + timeout: 60 * 5, // Increases max request lifetime on the runner + entrypoint: "server.ts", // File which starts serverless runner + domains: [FREESTYLE_DOMAIN], + build: false, +}); +``` + +Details on `buildDir` and other settings are available on [Freestyle docs](https://docs.freestyle.sh/web/web). + +Run this deployment script to push your application to Freestyle. + +**Deployment Configuration:** + +- `timeout: 60 * 5` - Set timeout to 5 minutes for actor operations - it's important to keep this high +- `entrypoint: "server.ts"` - Entry point file with your serverless setup +- `domains` - Your Freestyle domain(s) +- `build: false` - Disable build if you're pre-building your assets + +### Configure runner + +Update the runner configuration on the Rivet side to connect with your Freestyle deployment. Create a configuration script and run it after your Freestyle deployment is live: + +```typescript @nocheck +import { RivetClient } from "@rivetkit/engine-api-full"; + +const rivet = new RivetClient({ + environment: "https://api.rivet.dev", + token: process.env.RIVET_API_TOKEN, +}); + +const FREESTYLE_DOMAIN = "my-domain.style.dev"; // Change to your desired Freestyle domain +const RIVET_NAMESPACE = "my-rivet-namespace"; // Change to your Rivet namespace + +await rivet.runnerConfigsUpsert("freestyle-runner", { + namespace: RIVET_NAMESPACE, + datacenters: { + default: { + serverless: { + url: `https://${FREESTYLE_DOMAIN}/start`, + runnersMargin: 1, + minRunners: 1, + maxRunners: 1, + slotsPerRunner: 1, + // Must be shorter than Freestyle request `timeout` config + requestLifespan: 60 * 5 - 5, + }, + }, + }, +}); +``` + +Execute this configuration script to register your Freestyle deployment with Rivet. + +**Runner Configuration:** + +- `url` - Freestyle deployment URL with `/start` endpoint +- `runnersMargin` - Buffer of runners to maintain +- `minRunners/maxRunners` - Scaling limits +- `slotsPerRunner` - Concurrent actors per runner +- `requestLifespan` - Request timeout (slightly less than Freestyle timeout) + +Once executed, Rivet will be connected to your Freestyle serverless instance. + +_Source doc path: /docs/deploy/freestyle_ diff --git a/.agents/skills/chat-room/reference/deploy/gcp-cloud-run.md b/.agents/skills/chat-room/reference/deploy/gcp-cloud-run.md new file mode 100644 index 0000000..f140950 --- /dev/null +++ b/.agents/skills/chat-room/reference/deploy/gcp-cloud-run.md @@ -0,0 +1,74 @@ +# Deploying to Google Cloud Run + +> Source: `src/content/docs/deploy/gcp-cloud-run.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/gcp-cloud-run +> Description: Deploy your RivetKit app to Google Cloud Run. + +--- +## Steps + +### Prerequisites + +- Google Cloud project with Cloud Run and Artifact Registry enabled +- `gcloud` CLI authenticated (`gcloud auth login`) and project set (`gcloud config set project YOUR_PROJECT`) +- Artifact Registry repository or Container Registry enabled +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Package Your App + +Create a `Dockerfile` in your project root: + +```dockerfile +FROM node:20-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev +COPY . . +ENV PORT=8080 +CMD ["node", "server.js"] +``` + +### Build and Push the Image + +Use Cloud Build to build and push the image. Replace the region and repository with your own. + +```bash +gcloud builds submit --tag us-central1-docker.pkg.dev/YOUR_PROJECT/rivetkit-app/rivetkit-app:latest +``` + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select Google Cloud Run as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables to use when deploying. + +### Deploy to Cloud Run + +Deploy the service to Cloud Run, passing the Rivet environment variables. Adjust the region and image as needed. + +```bash +gcloud run deploy rivetkit-app \ + --image us-central1-docker.pkg.dev/YOUR_PROJECT/rivetkit-app/rivetkit-app:latest \ + --region us-central1 \ + --allow-unauthenticated \ + --min-instances 1 \ + --set-env-vars RIVET_ENDPOINT=,RIVET_PUBLIC_ENDPOINT= +``` + +### Connect to Rivet + +1. After deployment, note the service URL (e.g. `https://rivetkit-app-xxxxx-uc.a.run.app`) +2. On the Rivet dashboard, paste your URL with the `/api/rivet` path into the connect form (e.g. `https://rivetkit-app-xxxxx-uc.a.run.app/api/rivet`) +3. Click "Done" + +### Verify + +Confirm the service is running: + +```bash +gcloud run services describe rivetkit-app --region us-central1 --format 'value(status.conditions[?type="Ready"].status)' +``` + +Your app should appear as connected on the Rivet dashboard once the service reports ready. + +_Source doc path: /docs/deploy/gcp-cloud-run_ diff --git a/.agents/skills/chat-room/reference/deploy/hetzner.md b/.agents/skills/chat-room/reference/deploy/hetzner.md new file mode 100644 index 0000000..5b61024 --- /dev/null +++ b/.agents/skills/chat-room/reference/deploy/hetzner.md @@ -0,0 +1,10 @@ +# Deploying to Hetzner + +> Source: `src/content/docs/deploy/hetzner.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/hetzner +> Description: Please see the VM & Bare Metal guide. + +--- + + +_Source doc path: /docs/deploy/hetzner_ diff --git a/.agents/skills/chat-room/reference/deploy/kubernetes.md b/.agents/skills/chat-room/reference/deploy/kubernetes.md new file mode 100644 index 0000000..43496a9 --- /dev/null +++ b/.agents/skills/chat-room/reference/deploy/kubernetes.md @@ -0,0 +1,121 @@ +# Deploying to Kubernetes + +> Source: `src/content/docs/deploy/kubernetes.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/kubernetes +> Description: Deploy your RivetKit app to any Kubernetes cluster. + +--- +## Steps + +### Prerequisites + +- A Kubernetes cluster with `kubectl` access (EKS, GKE, k3s, etc.) +- Container registry credentials (Docker Hub, GHCR, GCR, etc.) +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Package Your App + +Create a `Dockerfile` in your project root: + +```dockerfile +FROM node:20-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev +COPY . . +ENV PORT=8080 +CMD ["node", "server.js"] +``` + +### Build and Push the Image + +```bash +docker build -t registry.example.com/your-team/rivetkit-app:latest . +docker push registry.example.com/your-team/rivetkit-app:latest +``` + +Replace `registry.example.com/your-team` with your registry path. Auth with `docker login` first if needed. + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select Kubernetes as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables. + +Create a `rivetkit-secrets.yaml` for your environment variables: + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: rivetkit-secrets +type: Opaque +stringData: + RIVET_ENDPOINT: + RIVET_PUBLIC_ENDPOINT: +``` + +### Deploy to Kubernetes + +Create a `deployment.yaml`: + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: rivetkit-app +spec: + replicas: 1 + selector: + matchLabels: + app: rivetkit-app + template: + metadata: + labels: + app: rivetkit-app + spec: + # Allow enough time for actors to gracefully stop on SIGTERM. + # The runner waits up to 30m for actors to finish. + # Add buffer for runner shutdown overhead after actors stop. + # See: /docs/actors/versions#graceful-shutdown-sigterm + terminationGracePeriodSeconds: 2100 + containers: + - name: rivetkit-app + image: registry.example.com/your-team/rivetkit-app:latest + envFrom: + - secretRef: + name: rivetkit-secrets +``` + +Apply both manifests: + +```bash +kubectl apply -f rivetkit-secrets.yaml +kubectl apply -f deployment.yaml +``` + +### Connect to Rivet + +1. Add a `Service` and Ingress to expose your app externally (e.g. `my-app.example.com`) +2. On the Rivet dashboard, paste your domain with the `/api/rivet` path into the connect form (e.g. `https://my-app.example.com/api/rivet`) +3. Click "Done" + +Rivet envoys connect to your app over long-lived WebSockets, and your app's clients (browsers, SDKs) do the same. Default Ingress and cloud load balancer idle timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +Raise the idle / read / send timeout on every Ingress and load balancer in front of your app to at least 1 hour (`3600` seconds). Examples: + +- **NGINX Ingress**: `nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"` and `nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"` +- **AWS Load Balancer Controller (ALB)**: `alb.ingress.kubernetes.io/load-balancer-attributes: idle_timeout.timeout_seconds=3600` +- **GCE Ingress (GKE)**: set `timeoutSec: 3600` on the `BackendConfig` referenced by the Service. + +### Verify + +Check that the pod is running: + +```bash +kubectl get pods -l app=rivetkit-app +``` + +Your app should appear as connected on the Rivet dashboard once the pod is ready. + +_Source doc path: /docs/deploy/kubernetes_ diff --git a/.agents/skills/chat-room/reference/deploy/railway.md b/.agents/skills/chat-room/reference/deploy/railway.md new file mode 100644 index 0000000..640ac37 --- /dev/null +++ b/.agents/skills/chat-room/reference/deploy/railway.md @@ -0,0 +1,45 @@ +# Deploying to Railway + +> Source: `src/content/docs/deploy/railway.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/railway +> Description: Deploy your RivetKit app to Railway. + +--- +## Steps + +### Prerequisites + +- [Railway account](https://railway.app) +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Deploy to Railway + +1. Connect your GitHub account to Railway +2. Select your repository containing your RivetKit app +3. Railway will automatically detect and deploy your app + +See [Railway's deployment docs](https://docs.railway.com/quick-start) for more details. + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select Railway as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables to add to your Railway service. + +See [Railway's environment variables docs](https://docs.railway.com/guides/variables#service-variables) for more details. + +### Connect to Rivet + +1. In your Railway project, go to **Settings > Networking** +2. Click **Create Custom Domain** then **Create Domain** to generate a Railway domain (e.g. `my-app.railway.app`) +3. On the Rivet dashboard, paste your domain with the `/api/rivet` path into the connect form (e.g. `https://my-app.railway.app/api/rivet`) +4. Click "Done" + +Rivet envoys connect to your app over long-lived WebSockets, and your app's clients (browsers, SDKs) do the same. Railway's HTTP proxy supports WebSockets, but if you front your app with your own reverse proxy (NGINX, Caddy, etc.) inside the Railway service, raise its idle / read timeout to at least 1 hour (`3600` seconds). Default proxy timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +### Configure Sleeping & Multi-Region (Optional) + +- [Enable App Sleeping](https://docs.railway.com/reference/app-sleeping) to reduce costs when idle +- [Configure Multi-Region](https://docs.railway.com/reference/deployment-regions) to deploy closer to your users + +_Source doc path: /docs/deploy/railway_ diff --git a/.agents/skills/chat-room/reference/deploy/rivet-compute.md b/.agents/skills/chat-room/reference/deploy/rivet-compute.md new file mode 100644 index 0000000..69507aa --- /dev/null +++ b/.agents/skills/chat-room/reference/deploy/rivet-compute.md @@ -0,0 +1,144 @@ +# Deploying to Rivet Compute + +> Source: `src/content/docs/deploy/rivet-compute.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/rivet-compute +> Description: Run your backend on Rivet Compute. + +--- +Using an AI coding agent? Open **Connect** on the [Rivet dashboard](https://dashboard.rivet.dev), select **Rivet Cloud**, and paste the one-shot prompt into your agent and have it connect with Rivet Compute for you. + +## Steps + +### Prerequisites + +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- A [Rivet Cloud](https://dashboard.rivet.dev) account and project +- Docker running locally + +### Create a Dockerfile + +Add a `Dockerfile` to your project root that builds and runs your RivetKit server: + +```dockerfile @nocheck +FROM node:24-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev +COPY . . +CMD ["node", "src/server.js"] +``` + +### Get Your Cloud Token + +1. Open the [Rivet dashboard](https://dashboard.rivet.dev) and navigate to your project +2. Click **Connect** and select **Rivet Cloud** +3. Copy the **`RIVET_CLOUD_TOKEN`** value shown + +### Deploy + +Run the deploy command from your project root. The token is saved to `~/.rivet/credentials`, so later deploys can omit it. + +```bash +npx @rivetkit/cli deploy --token cloud_api_xxxxx +``` + +The CLI resolves your project from the token, builds and pushes your Docker image to Rivet's built-in registry, upserts the managed pool, and prints the deployment URL on stdout when the pool is ready. + +### Optionally Add CI + +After local deploys work, install the GitHub Actions workflow that deploys on every push and pull request: + +```bash +npx @rivetkit/cli setup-ci +``` + +This writes `.github/workflows/rivet-deploy.yml`. Add your token as a repository secret to enable it: + +```bash +gh secret set RIVET_CLOUD_TOKEN +``` + +The workflow creates production and pull-request namespaces, posts preview links, and cleans up PR namespaces when pull requests close. See the [CLI reference](/docs/cli) for all commands. + +### Monitor Deployment + +The dashboard shows live status as Rivet Compute provisions your backend: + +| Status | Description | +| --- | --- | +| Initializing | Starting the runtime environment | +| Deploying | Pulling and launching your container | +| Binding | Connecting the runner to the network | +| Ready | Deployment complete | + +Once the status reaches **Ready**, your backend is live and actors are available for connections. + +If you are an agent monitoring the deployment via API rather than the dashboard, poll the managed-pool endpoint on the Cloud API. + +The `RIVET_CLOUD_TOKEN` secret is a `cloud_api_*` management token scoped to the Cloud API at `cloud-api.rivet.dev`. Use it for `Authorization: Bearer ...` against the Cloud API. Do not confuse it with a `pk_*` publishable key, which is scoped to the Rivet Engine API at `api.rivet.dev` and will 401 against this endpoint. + +Substitute `$CLOUD_API_URL` (typically `https://cloud-api.rivet.dev`), `$PROJECT`, `$ORG`, `$CLOUD_NAMESPACE`, and `$CLOUD_TOKEN`. + +Poll every 5 seconds until `status` is `ready`. Stop and investigate if `status` is `error`. + +```bash +curl -s "$CLOUD_API_URL/projects/$PROJECT/namespaces/$CLOUD_NAMESPACE/managed-pools/default?org=$ORG" -H "Authorization: Bearer $CLOUD_TOKEN" +``` + +## Checking Logs + +Use the CLI to read your deployment's logs. By default `rivet logs` prints the last 100 lines from the `production` namespace, oldest to newest, then exits. + +```bash +npx @rivetkit/cli logs +``` + +The CLI resolves your token the same way `deploy` does (the `--token` flag, then the `RIVET_CLOUD_TOKEN` environment variable, then `~/.rivet/credentials`). + +### Follow logs live + +Pass `--follow` (`-f`) to stream new logs as they arrive instead of fetching history: + +```bash +npx @rivetkit/cli logs --follow +``` + +Each formatted line is printed as ` [] `: + +``` +2026-06-16T18:26:51.160Z [INFO] eu-central-1 server listening on port 3000 +2026-06-17T11:24:20.425Z [ERROR] us-east-1 failed to connect to upstream +``` + +A few examples: + +```bash +# Last 200 lines from a specific namespace +npx @rivetkit/cli logs --namespace production -n 200 + +# Live tail, only lines containing "error" +npx @rivetkit/cli logs --follow --contains error + +# JSON output piped to jq +npx @rivetkit/cli logs -n 50 --json | jq . +``` + +## Troubleshooting + +If the status stays in **Initializing** for more than a few minutes, verify that: + +- The `RIVET_CLOUD_TOKEN` secret is correctly set in your GitHub repository +- The GitHub Actions workflow completed without errors — check the run logs + +If the status shows **Error**, check that your container starts successfully and does not exit immediately (you can check this with container logs). Common causes: + +- The server file is not calling `registry.start()` +- A runtime crash on startup — test the image locally with `docker run` +- The server is not listening on the `RIVET_PORT` environment variable (RivetKit reads `RIVET_PORT`, defaulting to `3000`) + +## Pricing + +You are billed for the compute resources your deployment uses while it is running. + +_Source doc path: /docs/deploy/rivet-compute_ diff --git a/.agents/skills/chat-room/reference/deploy/supabase.md b/.agents/skills/chat-room/reference/deploy/supabase.md new file mode 100644 index 0000000..fa98436 --- /dev/null +++ b/.agents/skills/chat-room/reference/deploy/supabase.md @@ -0,0 +1,50 @@ +# Deploying to Supabase Functions + +> Source: `src/content/docs/deploy/supabase.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/supabase +> Description: Deploy an existing Rivet project to Supabase Edge Functions. + +--- +This guide covers deploying an existing Rivet project to Supabase Edge Functions. + +## Prerequisites + +- [Supabase project](https://supabase.com/) +- [Supabase CLI](https://supabase.com/docs/guides/cli) configured for your project +- A Rivet namespace from the [Rivet Dashboard](https://dashboard.rivet.dev/) or a self-hosted Rivet Engine + +## Steps + +### Set up your project + +Follow the [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) to set up your project locally. + +### Set Secrets + +Set your Rivet connection values as Supabase secrets. Find `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` in the [Rivet Dashboard](https://dashboard.rivet.dev/) under **Settings → Namespace → Advanced → Backend Configuration** and copy them in. + +```sh +npx supabase secrets set \ + RIVET_ENDPOINT=https://your-namespace:sk_...@api.rivet.dev \ + RIVET_PUBLIC_ENDPOINT=https://your-namespace@api.rivet.dev +``` + +### Deploy + +Make sure the function has the `deno.json` import map from the [quickstart](/docs/actors/quickstart/supabase) that points `rivetkit` at `@rivetkit/supabase`. It keeps the deploy to the WebAssembly runtime; without it the deploy pulls Rivet's native engine and fails with a `413` (request too large). + +```sh +npx supabase functions deploy rivet +``` + +### Register the Serverless Runner URL + +After deploy, set the function URL with the `/api/rivet` path as the serverless runner URL in Rivet. For a function named `rivet`, this is usually `https://your-project.functions.supabase.co/functions/v1/rivet/api/rivet`. + +## Related + +- [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) +- [Deploying to Cloudflare Workers](/docs/deploy/cloudflare) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/deploy/supabase_ diff --git a/.agents/skills/chat-room/reference/deploy/vercel.md b/.agents/skills/chat-room/reference/deploy/vercel.md new file mode 100644 index 0000000..e8b5ba3 --- /dev/null +++ b/.agents/skills/chat-room/reference/deploy/vercel.md @@ -0,0 +1,138 @@ +# Deploying to Vercel + +> Source: `src/content/docs/deploy/vercel.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/vercel +> Description: Deploy your Next.js Rivet app to Vercel. + +--- +This guide assumes a Next.js app. + +## Prerequisites + +- [Vercel account](https://vercel.com/) +- A Next.js Rivet app +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +## Steps + +### Set up your project + +Follow the [Next.js Quickstart](/docs/actors/quickstart/next-js) to set up your project. + +### Verify Your Project Structure + +Your Next.js project should have the following structure: + +- `src/app/api/rivet/[...all]/route.ts`: RivetKit route handler +- `src/rivet/registry.ts`: Actor definitions and registry + +The route handler sets `maxDuration` to extend the serverless function timeout so long-lived actor requests are not cut short: + +```ts src/app/api/rivet/[...all]/route.ts @nocheck +import { toNextHandler } from "@rivetkit/next-js"; +import { registry } from "@/rivet/registry"; + +export const maxDuration = 300; + +export const { GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS } = toNextHandler(registry); +``` + +### Set Environment Variables + +Set `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` in your Vercel project settings using the URL auth format: + +``` +RIVET_ENDPOINT=https://my-namespace:sk_****@api.rivet.dev +RIVET_PUBLIC_ENDPOINT=https://my-namespace:pk_****@api.rivet.dev +``` + +`RIVET_ENDPOINT` uses the secret token for server-side access. `RIVET_PUBLIC_ENDPOINT` uses the publishable token and tells the metadata endpoint what connection info to provide to clients. + +### Deploy to Vercel + +1. Connect your GitHub repository to Vercel +2. Vercel will deploy your app + +### Configure Preview Deployments (Recommended) + +Add a GitHub action to automatically create isolated Rivet namespaces for each PR: + +1. Add these secrets to your GitHub repository: + - `RIVET_CLOUD_TOKEN`: Get from [Rivet Dashboard](https://dashboard.rivet.dev) → Settings → Advanced → Cloud API Tokens + - `VERCEL_TOKEN`: Get from [Vercel Account Settings](https://vercel.com/account/tokens) + +2. Create `.github/workflows/rivet-preview.yml`: + +```yaml +name: Rivet Preview + +on: + pull_request: + types: [opened, synchronize, reopened] + push: + branches: [main] + +concurrency: + group: rivet-preview-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + rivet-preview: + runs-on: ubuntu-latest + permissions: + pull-requests: write + steps: + - uses: rivet-dev/preview-namespace-action@v1 + with: + platform: vercel + rivet-token: ${{ secrets.RIVET_CLOUD_TOKEN }} + vercel-token: ${{ secrets.VERCEL_TOKEN }} +``` + +## Troubleshooting + +``` +Error: ENOENT: no such file or directory, mkdir '.../rivetkit/.../state' +``` + +**Cause:** The `RIVET_ENDPOINT` environment variable is not configured. RivetKit falls back to the file system driver, which fails in Vercel's read-only serverless environment. + +**Solution:** Ensure `RIVET_ENDPOINT` is set with your Rivet endpoint using the URL auth format: + +``` +RIVET_ENDPOINT=https://my-namespace:sk_****@api.rivet.dev +``` + +If using the [preview-namespace-action](https://github.com/rivet-dev/preview-namespace-action), this is configured automatically. + +The `/api/rivet/metadata` endpoint returns data but `clientEndpoint`, `clientNamespace`, and `clientToken` are missing. + +**Cause:** The `RIVET_PUBLIC_ENDPOINT` environment variable is not configured. This tells the metadata endpoint what connection info to provide to clients. + +**Solution:** Set `RIVET_PUBLIC_ENDPOINT` with the publishable token (for client access): + +``` +RIVET_PUBLIC_ENDPOINT=https://my-namespace:pk_****@api.rivet.dev +``` + +If using the [preview-namespace-action](https://github.com/rivet-dev/preview-namespace-action), this is configured automatically. + +Rivet fails to connect to your Vercel deployment with a 401 error mentioning "Authentication Required". + +**Cause:** [Vercel Deployment Protection](https://vercel.com/docs/security/deployment-protection) is blocking requests from Rivet. + +**Solution:** + +1. Create a bypass secret in your Vercel project settings +2. In Rivet, go to **Settings > Providers** +3. Click the three dots on your provider and select **Edit** +4. Click **Add Header** and add `x-vercel-protection-bypass` with your bypass secret + +If using the [preview-namespace-action](https://github.com/rivet-dev/preview-namespace-action), this is configured automatically. + +## Related + +- [Next.js Quickstart](/docs/actors/quickstart/next-js) +- [Self-Hosting](/docs/general/self-hosting) + +_Source doc path: /docs/deploy/vercel_ diff --git a/.agents/skills/chat-room/reference/deploy/vm-and-bare-metal.md b/.agents/skills/chat-room/reference/deploy/vm-and-bare-metal.md new file mode 100644 index 0000000..6a123f9 --- /dev/null +++ b/.agents/skills/chat-room/reference/deploy/vm-and-bare-metal.md @@ -0,0 +1,96 @@ +# Deploying to VMs & Bare Metal + +> Source: `src/content/docs/deploy/vm-and-bare-metal.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/vm-and-bare-metal +> Description: Deploy your RivetKit app to any Linux VM or bare metal host. + +--- +## Steps + +### Prerequisites + +- A Linux VM or bare metal server with SSH access +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Upload Your App + +- Build your RivetKit app locally +- Copy the build output to your server (example): + +```bash +scp -r ./dist user@server:/opt/rivetkit-app +``` + +Place the files somewhere readable by the service user, such as `/opt/rivetkit-app`. + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select VM & Bare Metal as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables to use in the next step. + +### Create the systemd Service + +Create `/etc/systemd/system/rivetkit-app.service`: + +```ini +[Unit] +Description=RivetKit App +After=network.target + +[Service] +Type=simple +WorkingDirectory=/opt/rivetkit-app +ExecStart=/usr/bin/node server.js +Restart=on-failure +Environment=RIVET_ENDPOINT= +Environment=RIVET_PUBLIC_ENDPOINT= + +[Install] +WantedBy=multi-user.target +``` + +Replace the environment values with those from the Rivet dashboard and adjust paths to match your deployment. + +### Start the Service + +Reload systemd units and start the service: + +```bash +sudo systemctl daemon-reload +sudo systemctl enable --now rivetkit-app.service +``` + +### Connect to Rivet + +1. Ensure your server is accessible via a public URL (e.g. `https://my-app.example.com`) +2. On the Rivet dashboard, paste your URL with the `/api/rivet` path into the connect form (e.g. `https://my-app.example.com/api/rivet`) +3. Click "Done" + +If you front your app with a reverse proxy or load balancer (NGINX, HAProxy, Caddy, AWS ALB/NLB, etc.), raise its idle / read timeout to at least 1 hour (`3600` seconds). Rivet envoys connect to your app over long-lived WebSockets, and clients (browsers, SDKs) do the same. Default proxy timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +Examples: + +- **NGINX**: `proxy_read_timeout 3600s;` and `proxy_send_timeout 3600s;` in the relevant `location` block. +- **HAProxy**: `timeout client 1h` and `timeout server 1h` in the matching frontend / backend. +- **AWS ALB / NLB**: set the load balancer attribute `idle_timeout.timeout_seconds = 3600`. + +## Operating + +### Restart + +Restart the service after deploying new builds or environment changes: + +```bash +sudo systemctl restart rivetkit-app.service +``` + +### Logs + +Follow realtime logs when debugging: + +```bash +sudo journalctl -u rivetkit-app.service -f +``` + +_Source doc path: /docs/deploy/vm-and-bare-metal_ diff --git a/.agents/skills/chat-room/reference/general/actor-configuration.md b/.agents/skills/chat-room/reference/general/actor-configuration.md new file mode 100644 index 0000000..72bc6fd --- /dev/null +++ b/.agents/skills/chat-room/reference/general/actor-configuration.md @@ -0,0 +1,19 @@ +# Actor Configuration + +> Source: `src/content/docs/general/actor-configuration.mdx` +> Canonical URL: https://rivet.dev/docs/general/actor-configuration +> Description: This page documents the configuration options available when defining a RivetKit actor. The actor configuration is passed to the `actor()` function. + +--- +## Basic Example + +## Configuration Reference + +## Related + +- [Registry Configuration](/docs/general/registry-configuration): Configure the RivetKit registry +- [State](/docs/actors/state): Managing actor state +- [Actions](/docs/actors/actions): Defining actor actions +- [Lifecycle](/docs/actors/lifecycle): Actor lifecycle hooks + +_Source doc path: /docs/general/actor-configuration_ diff --git a/.agents/skills/chat-room/reference/general/architecture.md b/.agents/skills/chat-room/reference/general/architecture.md new file mode 100644 index 0000000..3da2912 --- /dev/null +++ b/.agents/skills/chat-room/reference/general/architecture.md @@ -0,0 +1,452 @@ +# Architecture + +> Source: `src/content/docs/general/architecture.mdx` +> Canonical URL: https://rivet.dev/docs/general/architecture +> Description: - rivetkit is the typescript library used for both local development & to connect your application to rivet - a rivetkit instance is called a "runner." you can run multiple runners to scale rivetkit horizontally. read omre about runners below. + +--- +## 3 ways of running + +### rivetkit + +- rivetkit is the typescript library used for both local development & to connect your application to rivet +- a rivetkit instance is called a "runner." you can run multiple runners to scale rivetkit horizontally. read more about runners below. + +#### local development + +- in local development, rivetkit provides a full actor environment for single-node deployments + +#### drivers + +- rivetkit supports multiple drivers. currently supports: file system (default in local dev), memory, rivet engine (used for rivet cloud & self-hosting), cloudflare durable objects (does not rely on rivet engine) +- drivers are very flexible to enable you to write your actors once and plug in to any system that fits your architecture adequately +- see the driver interface + - actordriver https://github.com/rivet-dev/rivet/blob/eeb01fc4d9ca0e06f2e740d267bd53280ca7330e/rivetkit-typescript/packages/rivetkit/src/actor/driver.ts + - managerdriver https://github.com/rivet-dev/rivet/blob/eeb01fc4d9ca0e06f2e740d267bd53280ca7330e/rivetkit-typescript/packages/rivetkit/src/manager/driver.ts + +### rivet cloud + +- provides multi-region and highest performance out of the box +- accessible at dashboard.rivet.dev and the api is avialble at api.rivet.dev + +### rivet self-hosted + +- available as a standalone rust binary or a docker contianer +- can be configured to persist to postgres or rocksdb +- can scale horiziontally across multipe nodes and can scale across multiple regions +- see [self-hosting docs](/docs/self-hosting/) + +## actors + +- Actors for long-lived processes with durable state, realtime, and hibernate when not in use. read more about actors at a high level at (link to actors/index) + +### actor-per-entity + +- actors are designed to have an actor-per-entity +- you can think about actors a bit like objects in object-oriented programming where each is responsible for their own state and expose methods (ie actions in our case) +- examples include + - actor per user + - actor per user session + - actor per document + - actor per game room + - actor per tenant + - actor per rate limit topic + +### architecting for scale + +- actors scale by: + - having isolated state to each actor that combines compute and storage for in-memory reads and writes + - communication is standardized based on actions & events + - scale horizontally +- read more about scaling at [Design Patterns](/docs/actors/design-patterns) + +### horizontal scaling + +- actors can run across multiple rivetkit runners. this is orchestrated by rivetkit itself. + +### lifecycle + +actors have create, destroy, wake, and sleep lifecycle hooks that you can implement to modify behavior. see the lifecycle docs for reference on actor lifecycel hook sequences + +### actor sleeping + +- actors sleep when not in use +- an actor is considered not in use when there are no active network connections to the actor (or the network connections are hibernatable websockets, see below) and there are no actions in flight +- actors have a sleep timeout (configured in `options.sleepTimeout`) that decides how long to keep the actor in memory with no recent activity +- sleep can be held off for the lifetime of a promise with `c.keepAwake(promise)` +- see the [sleeping docs](/docs/actors/lifecycle#sleeping) for full details + +### wake events + +- actors can wake to any of the follwoing events: + - network requests + - websocket messages + - alarms (see scheduling docs) + +### live actor migration + +- live actor migrations lets your application ugprade, crash, or hot reload cahnges without interruption to your user or application (including websockets) +- this is powered by hibernating websockets for live websocket migraiton & our fault tolerance mechanism (read more below) + +### coldstart performance + +- actors have negligible coldstart performance. the code to run the actor is already started (ie the runner), so creating/starting an actor is incredibly cheap. +- creating new actors with a key requires some overhead to communicate with other regions in order to reserve the actor's key (see below). actors can be created without keys with near-0 latency. + +### multi-region, globally unique actor keys + +- actors can optionally have a globally unique "key" +- when creating an actor with a key +- this system is highly optimized to reduce wan round trips using per-key Paxos with a custom database called Epoxy (https://github.com/rivet-dev/rivet/tree/main/engine/packages/epoxy) +- limitation: when creating an actor with a given key, that key will always be pinned to that region even if the actor is destroyed. creating a new actor with the same key will always live in the same region. +- see the actors keys document + +### input + +- actors have input data that can be passed to them when constructed +- this is similar to apssing data to a constructor in an object + +### generic parameters + +actor definitions include the following generic parameters that you'll see frequently in the code: + +- state +- conn state +- conn params +- ephemeral variables +- input data +- (experimental) database connector + +### persistence + +- state automatically flushes to storage intelligently +- to force a state flush and wait for it to finish, call (TODO: look this up in state document) +- read more about state persistence in the state document (link to document) +- state is stored in the same place as where the actor lives. loading an actor in to memory has comparable performance to network attached storage, and once in memory, has performance of any standard in-memory read/write like a variable. + +### scheduling & alarms + +- actors have a scheduling api to be able to wake up at any time in the indefinite future +- think of this like setTimeout but without a max timeout +- rivet is responsible for waking the actor when this timeout wakes + +### ephemeral variables + +- actors have the ability to create ephemrla variables for things that you do not want to be persisted with the actor's state +- this is useful for non-serializable data like a utility class like a pubsubs erver or something (TODO extra info) +- link to ephemeral variables docs + +### actions + +- for stateless clients, actions are sent as http requests via `POST /gateway/{actor id}/actions/{action name}` +- for stateful clients, actions are sent as websocket messages + +### events & subscriptions + +- events are sent as websocket messages + +### error handling + +- this is different than fault tolerance: + - error handling is a user error + - fault tolerance is something goes wrong that your applciation was not built to handle (ie hard crash, oom, network error) +- rivet provdies a special UserError class to throw custom errors that will be returned to the client +- all other errors are returned as a generic "internal error" +- this is becuase leaking error deatils is a common security hole, so we default to expose-nothing errors + +### logging + +- rivet uses pino for logging +- we expose a scoped child logger for each actor at `c.log` that automatically logs the actor id + key +- this allows you to search lgos easily by actor id without having to log the actor id frequently +- logs can be configured via the `RIVET_LOG_LEVEL` env var + +### fault tolerance + +- actors are fault tolerant, meaning that the host machine can crash and the actors will proceed to operate as if nothing happened +- runners maintain a socket with rivet engine. when this socket closes or takes to long to ping, actors will reschedule +- hibernating websockets (enabled by default) will live-migrate to the new actor as if nothing happened + +### crash policy + +- there are 3 crash policies: sleep, restart, and destroyed + - sleep (default, usually the option you want): + - when to use: actors that need high-performance in-memory logic. + - when not to use: you need this actor running at all times no matter what, even if idle + - examples: (list commone xamples) + - destroy: + - when to use: actors that need to run once until completion. on crash, do not try to reschedule. + - when not to use: if you want your actor to have fault tolerance and be able to run transaprenlty to the underlying runner + - examples: batch jobs, image conversions, ephemeral jobs, (TODO come up with better eaxmples) + - restart: + - when to use: actors that should be running at all times + - when not to use: if you don't absolutely need something running at all times, since this consumes needless compute resources. considure using the scheduling api instead. + - examples: maintain outbound sockets, daemons, always-running jobs, (TODO come up with better examples) + +the behavior for each is described below: + +| Event | Restart | Sleep | Destroy | +|------------------------------|--------------|--------------|--------------| +| Graceful exit (StopCode::Ok) | Destroy | Destroy | Destroy | +| Crash (non-Ok exit) | Reschedule | Sleep | Destroy | +| Lost (runner disappeared) | Reschedule | Sleep | Destroy | +| Lost + force_reschedule | Reschedule | Reschedule | Reschedule | +| GoingAway (runner draining) | Reschedule | Sleep | Destroy | +| No capacity (allocation) | Queue (wait) | Sleep | Queue (wait) | +| No capacity + serverless | Queue (wait) | Queue (wait) | Queue (wait) | +| Wake signal (while sleeping) | Reschedule | Reschedule | Reschedule | + +### inspector + +- actors provide an inspector api to implement the: + - repl + - state read/write + - network inspector + - event log +- this is impelmented over a websocket over bare + +### http api + +- see the http api document on actors + +### multi-region + +- actors can be scheduled across multiple regions +- each actor has an actor id which embeds which region it lives in +- networking is automatically routed to the region that an actor lives in +- limitation: actors curretnly cannot migrate across regions + +### backpressure + +#### no runner capacity + +- this is how actors with different crash policies behave when when there's backpressure: + - sleep = sleeps (sheds load by not rescheduling) + - restart = queues + - destroy = queues +- see the above matrix for more details on actor crash policy on how it handles no capacity. + +- the actor queue is built to withstand high amounts of backpressure on rivet, so queueing actors is fine here +- a large queue means it'll take more time for your application to process the queue to catch up with demand when it comes online. + +#### per-actor cpu & networking exhaustion + +- actors are isolated, so they each have their own individual bottleneck. you can think of this like a process thread where each thread can only do so much. +- there is no durable message queue/"mailbox" for actors. if the actor cannot respond in time, then the request is dropped. +- if an actor exhauses its cpu or networking, then the runner +- returns service unavailble (503) if the actor fails to respond to a request in time +- there is no hard cap on the networking or cpu usage for each actor at the moment +- if your actor is resource intensive, it's common to use a separate mailbox actor to act as a queue + +## runners + +### regular vs serverless runners + +there are 2 types of runners: + +- regular: these are standard nodejs processes connected to rivet that rivet can orchestrate actors to and send network requests to at any time +- serverless: rivet works with serverless platforms. when an actor is created, it has a request-per-actor model where it opens a long-running request on the serverless platofrm to run a given actor. + +### runner pool + +- runners are pooled together by sharing a common name (ie "default") +- when an actor is created, it chooses the pool by selecting the runner name to run on +- rivet will automatically load balance actors across these runners + +### runner key + +- not relevnat for serverless runners +- each runner has a unique key that it provides when connecting. keys are unique to the instace the runner is running on and should be the same if the runner is restarted. +- this can be the: machine's ip, k8s pod name, etc +- if there is an existing runner connected with a given key, the runner will disconnect the old runner and replace it +- rivet is designed to handle network partitions by waiting for runners to miss a ping, indicating it's no longer alive. however, often times runners restart immediately after a hard crash and reconnect. in this case, the runner will reconnect on restart and terminate the old runner in order to prevent further actors from scheduling to the crashed runner. + +### capacity + +- not relevnat for serverless runners +- each runner can be assigned a capacity of how many actors it can run +- rivet will schedule with spread (not binpacking) in order to spread load over actors + +#### usefulness of capacity = 1 + +- setting a capacity of 1 is helpful for situations where you have cpu-intensive apps that should not run with any other actors +- examples include game servers, ffmpeg jobs, etc + +### versions & upgrading code + +- each runner has a version index +- actors are always scheduled to the highest verison index (see runner priority below) +- this means that when a new runner is deployed: + 1. runners with higher index come online + 2. actors schedule to the highest index, stop scheduling to the older index + 3. old index runners start draining and migrating actors to new index + 4. all old runners are now shut down +- websocekts are live migrated to the new version when upgrading using hibernating websockets to users see no hiccup in their applications +- this is important because actors should never downgrade their runner. they should always move to a newer version of code in order to prevent corruption. + +### runner scheduling prioroty + +- actors are scheduled to runners sorted by priority of (version DESC, remaining capacity ASC) + +### multi-region + +TODO + +### shutdown sequence + +- runner shutdown is important to ensure that actors do not get unexpectedly terminated when either: + - upgrading your applciation and taking down old pods + - scaling down your runners horizontally (ie from an hpa) + - pressing ctrl-c when in development +- on shutdown: + 1. tell rivet the runner is stopping + 2. rivet tells all the actors on this runner to migrate + 3. runner waits for all actors to finish migrating + 4. runner exits process + +### reconnection + +- runners can handle temporary network partitions +- they'll automatically reconnect and replay missed commands/events between rivet and the runner +- this happens transparenlty to the user +- if disconnected for too long (indicating a network partition), the runner will shut itself down and exit + +### autoscaling + +- not relevant to serverless +- runners currently autoscale on cpu. more intelligent scaling is coming soon. +- tune your runner total slots capacity accordingly +- it's up to you to configure your hpa/etc to work like this. see the Connect guides (link to index page) for reference on hwo to configure this. + +### serverless timeouts + +- serverless runners take in to account the maximum run duration of the serverless platform +- the runners will mgirate actors to a new request before the request times out +- this is completely transparent to you and the user because of the fault tolerance and websocket migraiton characteristics +- it's common for actors to go sleep before hitting the serverless timeout + +## networking + +### web standards + +- everything in rivet is built on webstandards by default +- nothing in rivet requires you to use our sdk, our sdks are meant to be a convenience. it's built to be as easy to use raw http/websocket endpoints from scratch. +- actions, events, etc are all built on simple, well-documented http/websocket under the hood (link to openapi & asyncapi docs). +- you can use low-level request handlers (lnk to dock) and low-level weboscket handlers (link to doc) to handle low-level primtivies yourself + +### encoding + +- rivetkit's action/events api supports communicating via [VBARE](link to github repo, see the blog post for the link), CBOR, or JSON + - VBARE: high-perofrmance & compact, optimal use case + - CBOR: descent encoding/decoding perf + portable libraries, good for implemnting high-ish performance on other platforms + - JSON: good for fast implementations & debugging (easy to read) + +### tunneling + +- when a runner connects it opens a tunnel to rivet to allow incoming traffic + - this is simila to systems like tailscale, ngrok, or other vpns + - we do this for security & configuraiton simplicity since it means that you don't have to manage exposing your rivetkit applications' networkig to rivet. instead, anything that can open a socket to rivet can accept inbound traffic to actors. + +### gateway + +- incoming traffic to actors come to the Rivet gateway and are routed to the appropriate runner +- the rivet gateway automatically handles: + - multi-region routing to route traffic to the correct reigon for an actor + - automatically waking the actor if needed + - sending traffic over the runner + +### hibernating websockets + +- hibernating web sockets are a core component of live actor migration & fault tolerance. it allows us to maintain an open websocket while the actor crashes, upgrades, or moves to another runner. +TODO: copy the rest of this from low-level webosckets document and rephrase + +### actor health endpoin + +- actors provide a simple, utility health endpoint at `/health` that lets you check if your actor is reachable (e.g. `curl https://api.rivet.dev/gateway/{actor id}/health`) + +## multi-region + +### networking + +- actors may live in different regions than inbound requests +- Rivet uses the Epoxy (link again) system to handle global routing to route traffic to the correct region with high performance +- this is completely transparent to you. your app sends traffic to https://api.rivet.dev/gateway/* and it automatically routes to the correct actor in the appropriate region + +### globally unique actor keys + +- actor keys are globally unique to be able to benefit from multi-region capabilities without any extra work +- see more about globally uniuqe actor keys above +- see the actor keys document + +### regional endpoints + +- each reigon has a regional endpoint +- this endpoint is used specifically for connecting runners (for example https://api-us-east-1.rivet.dev), opt to use api.rivet.dev for all other traffic +- runners are required to connect to the regional endpoints + - this is because runners are sensitive to latency to the rivet regional datacenter + - we add datacenters regularly so each runner needs to be pinned to a single datacenter in order to ensure your availble datacneter list doesn't change sporadically without your consent + +### persistence + +- data is always persisted in the same region that is written +- this is important for minimal coldstarts & data locality laws + +## namespaces + +- rivet provides namespaces to run multiple actor systems in isolation +- this makes it really easy to have prod/staging environments or completely different applications running on the same rivet instance +- when you connect to rivet, you can specify which namespace you're connecting to +- self-hotsed rivet defaults to namespace "default" +- rivet cloud provdies isolated tokens for each namespace + +## manager api + +- rivet provides a standard rest api for managing actors + - useful endoints include: + - get /actors + - delete /actors/{} + - get /actors/names -> get all actor types available + +## comparison to prior art for actors + +### runtime + +- there are very few serious actor implementation targeted at the javascirpt eocsystem. rivet is arguably the most serious open-source actor implementation for typescript out there. + +### library vs orchestrator + +- some actor systems opt to be purely a library while rivet opts to have an orchestrator (i.e. the single rust binary) +- this lets us to a lot of things other actor systems can't: + - separating orchestration, persistence, and proxy lets us isoalte the core to be incredibly reliable while the fast-changing applications that ocnnect to rivet can be more error-prone safely. with a library, the blast radius of your application also affects the entire actor system. + - support for serverless platforms to benefit from cost, multi-region, blitz scaling, and relibaiblity benefits + - optimize fault tolerance since we can make more assumtions about application state when the rivet core does not crash and your app does + +### scheduling + +actors is a loose term, but there are generally 2 types of schedulign in practice: + +- ephemeral actors + - examples: erlang/otp, akka, swift + - provides no persistence or sleeping mechanism by defualt + - relies on supervisors for managing persistence +- [virtual actors](https://www.microsoft.com/en-us/research/project/orleans-virtual-actors/) + - an extension of the actor pattern that provides actors that can hibernate ("sleep") when not in use + - examples: orleans, dapr, durable objects + +rivet has similarities with both to provide more flexibility: + +- crash policies provdie for 3 types of actors: + - sleep -> most similar to virutal actors + - restart -> most similar to ephemeral actors but with a supervisor to auto-restart, however still has a durable queue ot handle backpressure + - crash -> most similar to traditional actors but with no supervisor to restart, however still has a durable queue to handle backpressure + +### communication + +- many actor frameworks use inbox patterns (think: queue-per-actor) to handle sending messages between actors +- there is no callback mechanims, instead you need to send messages back to the actual actor +- rivet opts to behave like web standards instead of using the message pattern + - actors can impelment the inbox pattern optionally + - but we provide lower-level networking to be able to be compatible with more techniologies + - rivet assumes the same serial concurerntly that other actors do (by the nature of javascript being single-threaded) but we allow you to run promises in parallel or handl eyour own concurrency control (which some other actor frameworks might require a spawning new actor to do) + +_Source doc path: /docs/general/architecture_ diff --git a/.agents/skills/chat-room/reference/general/cors.md b/.agents/skills/chat-room/reference/general/cors.md new file mode 100644 index 0000000..330fe38 --- /dev/null +++ b/.agents/skills/chat-room/reference/general/cors.md @@ -0,0 +1,18 @@ +# Cross-Origin Resource Sharing + +> Source: `src/content/docs/general/cors.mdx` +> Canonical URL: https://rivet.dev/docs/general/cors +> Description: Cross-Origin Resource Sharing (CORS) controls which origins (domains) can access your actors. When actors are exposed to the public internet, proper origin validation is critical to prevent security breaches and denial of service attacks. + +--- +Unlike stateless HTTP APIs that use CORS headers, Rivet Actors are stateful and support persistent WebSocket connections. Since WebSockets don't natively support CORS, we validate origins manually in the `onBeforeConnect` hook before connections may open. + +## Implementing Origin Restrictions + +To implement origin restrictions on Rivet Actors, use the `onBeforeConnect` hook to verify the request. + +To catch the error on the client, use the following code: + + See tracking issue for [configuring CORS per-actor on the gateway](https://github.com/rivet-dev/rivet/issues/3539) that will remove the need to implement origin restrictions in `onBforeRequest`. + +_Source doc path: /docs/general/cors_ diff --git a/.agents/skills/chat-room/reference/general/docs-for-llms.md b/.agents/skills/chat-room/reference/general/docs-for-llms.md new file mode 100644 index 0000000..db0c216 --- /dev/null +++ b/.agents/skills/chat-room/reference/general/docs-for-llms.md @@ -0,0 +1,51 @@ +# Documentation for LLMs & AI + +> Source: `src/content/docs/general/docs-for-llms.mdx` +> Canonical URL: https://rivet.dev/docs/general/docs-for-llms +> Description: Rivet provides optimized documentation formats specifically designed for Large Language Models (LLMs) and AI integration tools. + +--- +## Skills (Recommended) + +For AI coding assistants like Claude Code, Cursor, or Windsurf, install Rivet skills for the best development experience: + +```sh +npx skills add rivet-dev/skills +``` + +Skills provide your AI assistant with Rivet-specific knowledge, best practices, and code patterns directly in your project context. + +## Available Formats + +### `llms.txt` (Condensed) +A condensed version of the documentation perfect for quick reference and context-aware AI assistance. + +**Access:** /llms.txt + +This format includes: +- Key concepts and features +- Essential getting started information +- Summaries of main functionality +- Optimized for token efficiency + +### `llms-full.txt` (Complete) +The complete documentation in a single file, ideal for comprehensive AI assistance and in-depth analysis. + +**Access:** /llms-full.txt + +This format includes: +- Complete documentation content +- All examples and detailed explanations +- Full API references and guides +- Suitable for complex queries and comprehensive understanding + +## Access Pages As Markdown + +Each documentation page is also available as clean markdown by appending `.md` to any documentation URL path. + +For example: + +- Original URL: `https://rivet.dev/docs/actors` +- Markdown URL: `https://rivet.dev/docs/actors.md` + +_Source doc path: /docs/general/docs-for-llms_ diff --git a/.agents/skills/chat-room/reference/general/edge.md b/.agents/skills/chat-room/reference/general/edge.md new file mode 100644 index 0000000..814dde2 --- /dev/null +++ b/.agents/skills/chat-room/reference/general/edge.md @@ -0,0 +1,24 @@ +# Edge Networking + +> Source: `src/content/docs/general/edge.mdx` +> Canonical URL: https://rivet.dev/docs/general/edge +> Description: Actors automatically run near your users on your provider's global network. + +--- +At the moment, edge networking is only supported on Rivet Cloud & Cloudflare Workers. More self-hosted platforms are on the roadmap. + +## Region selection + +### Automatic region selection + +By default, actors will choose the nearest region based on the client's location. + +Under the hood, Rivet and Cloudflare use [Anycast routing](https://en.wikipedia.org/wiki/Anycast) to automatically find the best location for the client to connect to without relying on a slow manual pinging process. + +### Manual region selection + +The region an actor is created in can be overridden using region options: + +See [Create Manage Actors](/docs/actors/communicating-between-actors) for more information. + +_Source doc path: /docs/general/edge_ diff --git a/.agents/skills/chat-room/reference/general/endpoints.md b/.agents/skills/chat-room/reference/general/endpoints.md new file mode 100644 index 0000000..5c376e1 --- /dev/null +++ b/.agents/skills/chat-room/reference/general/endpoints.md @@ -0,0 +1,98 @@ +# Endpoints + +> Source: `src/content/docs/general/endpoints.mdx` +> Canonical URL: https://rivet.dev/docs/general/endpoints +> Description: Configure how your backend connects to Rivet and how clients reach your actors. + +--- +## Local Development + +No configuration is needed for local development. RivetKit runs entirely on your local machine without any extra configuration to run Rivet Actors. + +## Production Deployment + +When deploying to production, you need to configure endpoints so your backend can communicate with Rivet Engine and clients can reach your actors. + +Diagram showing Client connecting to Rivet, which connects to Your Backend + +### Private Endpoint + +The private endpoint tells your backend where to find the Rivet Engine. + +### Environment Variable + +```bash +RIVET_ENDPOINT=https://my-namespace:sk_xxxxx@api.rivet.dev +``` + +### Config + +### Public Endpoint + +The public endpoint tells clients where to connect to reach your actors. + +This endpoint and token will be exposed to the internet. Use a public token (`pk_`), not your secret token (`sk_`). + +The public endpoint is only required if using the [serverless runtime mode](/docs/general/runtime-modes#runners) and if you have a frontend using RivetKit. + +### Environment Variable + +```bash +RIVET_PUBLIC_ENDPOINT=https://my-namespace:pk_xxxxx@api.rivet.dev +``` + +### Config + +## Advanced + +### URL Auth Syntax + +Endpoint URLs support embedding namespace and token directly in the URL: + +``` +https://namespace:token@host/path +``` + +This is the recommended approach for simplicity. Alternatively, you can use separate environment variables: + +```bash +RIVET_ENDPOINT=https://api.rivet.dev +RIVET_NAMESPACE=my-namespace +RIVET_TOKEN=sk_xxxxx +``` + +### Security + +In serverless mode, the private endpoint is used to validate that requests to `GET /api/rivet/start` are coming from your trusted Rivet endpoint. If the private endpoint is not configured, anyone can run a self-hosted instance of Rivet and connect to your backend from any endpoint. + +### How Clients Connect + +This flow applies to [serverless runtime mode](/docs/general/runtime-modes#serverless). For [runner runtime mode](/docs/general/runtime-modes#runners) or [clients configured to connect directly to Rivet](/docs/clients/javascript), clients connect directly to Rivet and this metadata flow is not needed. + +When a client connects to your serverless application, it follows this flow: + +1. Client makes a request to `https://my-app.example.com/api/rivet/metadata` +2. Your app returns the public endpoint configuration: + ```json + { + "clientEndpoint": "https://api.rivet.dev", + "clientNamespace": "my-namespace", + "clientToken": "pk_xxxxx" + } + ``` +3. Client caches these values and uses them for subsequent requests +4. Client connects to `https://api.rivet.dev/gateway/{actor}`, which routes requests to your actors + +This indirection exists because Rivet acts as a gateway between clients and your actors. This is because Rivet handles routing, load balancing, and actor lifecycle management of actors. + +## Reference + +| Environment Variable | Config Option | Description | +|---------------------|---------------|-------------| +| `RIVET_ENDPOINT` | `endpoint` | Rivet Engine URL for your backend | +| `RIVET_NAMESPACE` | `namespace` | Namespace for actor isolation | +| `RIVET_TOKEN` | `token` | Authentication token for engine connection | +| `RIVET_PUBLIC_ENDPOINT` | `serverless.publicEndpoint` | Client-facing endpoint | +| `RIVET_PUBLIC_TOKEN` | `serverless.publicToken` | Client-facing token | + +_Source doc path: /docs/general/endpoints_ diff --git a/.agents/skills/chat-room/reference/general/environment-variables.md b/.agents/skills/chat-room/reference/general/environment-variables.md new file mode 100644 index 0000000..2a86e98 --- /dev/null +++ b/.agents/skills/chat-room/reference/general/environment-variables.md @@ -0,0 +1,87 @@ +# Environment Variables + +> Source: `src/content/docs/general/environment-variables.mdx` +> Canonical URL: https://rivet.dev/docs/general/environment-variables +> Description: This page documents all environment variables that configure RivetKit behavior. + +--- +## Connection + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_ENDPOINT` | Endpoint URL to connect to Rivet Engine. Supports [URL auth syntax](/docs/general/endpoints#url-auth-syntax). | +| `RIVET_TOKEN` | Authentication token for Rivet Engine | +| `RIVET_NAMESPACE` | Namespace to use (default: "default") | + +## Public Endpoint + +These variables configure how clients connect to your actors. + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_PUBLIC_ENDPOINT` | Public endpoint for client connections. Supports [URL auth syntax](/docs/general/endpoints#url-auth-syntax). | +| `RIVET_PUBLIC_TOKEN` | Public token for client authentication | + +## Runner Configuration + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_RUNNER` | Runner name (default: "default") | +| `RIVET_RUNNER_VERSION` | Version number for the runner. See [Versions & Upgrades](/docs/actors/versions). | +| `RIVET_RUNNER_KIND` | Type of runner | +| `RIVET_TOTAL_SLOTS` | Total actor slots available (default: 100000) | + +## Engine + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_RUN_ENGINE` | Set to `1` to spawn the engine process | +| `RIVET_RUN_ENGINE_HOST` | Host to bind the spawned local engine process to. Defaults to `127.0.0.1`. | +| `RIVET_RUN_ENGINE_PORT` | Port to bind the spawned local engine process to. Defaults to `6420`. | +| `RIVET_RUN_ENGINE_VERSION` | Version of engine to download | + +## Inspector + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_INSPECTOR_DISABLE` | Set to `1` to disable the inspector | + +## Metrics + +| Environment Variable | Description | +|---------------------|-------------| +| `_RIVET_METRICS_TOKEN` | Bearer token that gates the per-actor Prometheus `/metrics` endpoint. When unset, `/metrics` is disabled. | + +## Experimental + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_EXPERIMENTAL_OTEL` | Set to `1` to enable experimental OTel tracing in Rivet Actors | + +## Storage + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVETKIT_RUNTIME` | Runtime binding to use for RivetKit core: `auto`, `native`, or `wasm`. Defaults to `auto`. | +| `RIVETKIT_STORAGE_PATH` | Overrides the default file-system storage path used by RivetKit when using the default driver. | + +## Lifecycle + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVETKIT_RUNTIME_MODE` | Controls how `registry.start()` runs. Accepted values are `envoy` and `serverless`; any other explicit value errors. Defaults to `envoy`: opens a long-lived WebSocket to the engine (Mode A). Set to `serverless` to bind an HTTP listener via `registry.listen()` (Mode B). | +| `RIVETKIT_PUBLIC_DIR` | Directory of static assets to serve alongside the framework routes when calling `registry.listen()`. Used as a fallback when `opts.publicDir` is not passed. On auto-listen via `registry.start()`, defaults to `/public` when this env var is unset. | +| `RIVET_PORT` | Port the listener binds when calling `registry.listen()` without an explicit `opts.port`. Must be an integer between 1 and 65535. Defaults to `3000`. | + +## Logging + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_LOG_LEVEL` | Log level: `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `silent` | +| `RIVET_LOG_TARGET` | Set to `1` to include log target | +| `RIVET_LOG_TIMESTAMP` | Set to `1` to include timestamps | +| `RIVET_LOG_MESSAGE` | Set to `1` to include message formatting | +| `RIVET_LOG_ERROR_STACK` | Set to `1` to include error stack traces | +| `RIVET_LOG_HEADERS` | Set to `1` to log request headers | + +_Source doc path: /docs/general/environment-variables_ diff --git a/.agents/skills/chat-room/reference/general/http-server.md b/.agents/skills/chat-room/reference/general/http-server.md new file mode 100644 index 0000000..c3a386c --- /dev/null +++ b/.agents/skills/chat-room/reference/general/http-server.md @@ -0,0 +1,96 @@ +# HTTP Server + +> Source: `src/content/docs/general/http-server.mdx` +> Canonical URL: https://rivet.dev/docs/general/http-server +> Description: Different ways to run your RivetKit HTTP server. + +--- +## Methods of Running Your Server + +### registry.start() + +The simplest way to run your server. Starts a local RivetKit server, serves static files from a `public` directory, and starts the actor runner: + +Run with `npx tsx --watch index.ts` (Node.js), `bun --watch index.ts` (Bun), or `deno run --allow-net --allow-read --allow-env --watch index.ts` (Deno). Clients connect to the Rivet Engine on `http://localhost:6420`. + +### With Fetch Handlers + +A [fetch handler](https://wintercg.org/) is a function that takes a `Request` and returns a `Response`. This is the standard pattern used by Cloudflare Workers, Deno Deploy, Bun, and other modern runtimes. + +Use `registry.serve()` to get a fetch handler: + +To integrate with a router like [Hono](https://hono.dev/) or [Elysia](https://elysiajs.com/), use `registry.handler()`: + +### Hono + +### Elysia + +Then run your server: + +```bash Node.js +npx tsx --watch server.ts +``` + +```bash Bun +bun --watch server.ts +``` + +```bash Deno +deno run --allow-net --allow-read --allow-env --watch server.ts +``` + +### Explicit HTTP Server + +If you need to explicitly start the HTTP server instead of using the fetch handler pattern: + +### Node.js (Hono) + +Using Hono with `@hono/node-server`: + +### Node.js (Adapter) + +Using `@whatwg-node/server` to adapt the fetch handler to Node's HTTP server: + +```ts server.ts @nocheck +import { actor, setup } from "rivetkit"; +import { createServer } from "node:http"; +import { createServerAdapter } from "@whatwg-node/server"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +const handler = createServerAdapter(registry.serve().fetch); +const server = createServer(handler); +server.listen(3000); +``` + +### Bun + +Using Bun's native server: + +```ts server.ts @nocheck +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +Bun.serve({ + port: 3000, + fetch: (request: Request) => registry.handler(request), +}); +``` + +### Deno + +Using Deno's native server: + +```ts server.ts @nocheck +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +Deno.serve({ port: 3000 }, (request: Request) => registry.handler(request)); +``` + +_Source doc path: /docs/general/http-server_ diff --git a/.agents/skills/chat-room/reference/general/logging.md b/.agents/skills/chat-room/reference/general/logging.md new file mode 100644 index 0000000..f7ce9eb --- /dev/null +++ b/.agents/skills/chat-room/reference/general/logging.md @@ -0,0 +1,74 @@ +# Logging + +> Source: `src/content/docs/general/logging.mdx` +> Canonical URL: https://rivet.dev/docs/general/logging +> Description: Actors provide a built-in way to log complex data to the console. + +--- +Using the context's log object (`c.log`) allows you to log complex data using structured logging. + +Using the actor logging API is completely optional. + +## Log levels + +There are 7 log levels: + +| Level | Call | Description | +| ------ | ------------------------------- | ---------------------------------------------------------------- | +| Fatal | `c.log.fatal(message, ...args);` | Critical errors that prevent core functionality | +| Error | `c.log.error(message, ...args);` | Errors that affect functionality but allow continued operation | +| Warn | `c.log.warn(message, ...args);` | Potentially harmful situations that should be addressed | +| Info | `c.log.info(message, ...args);` | General information about significant events & state changes | +| Debug | `c.log.debug(message, ...args);` | Detailed debugging information, usually used in development | +| Trace | `c.log.trace(message, ...args);` | Very detailed debugging information, usually for tracing flow | +| Silent | N/A | Disables all logging output | + +## Structured logging + +The built-in logging API (using `c.log`) provides structured logging to let you log key-value +pairs instead of raw strings. Structured logs are readable by both machines & +humans to make them easier to parse & search. + +When using `c.log`, the actor's name, key, and actor ID are automatically included in every log output. This makes it easy to filter and trace logs by specific actors in production environments. + +### Examples + +The logging system is built on [Pino](https://getpino.io/#/docs/api?id=logger), a high-performance structured logger for Node.js. + +## Configuration + +### Environment Variables + +You can configure logging behavior using environment variables: + +| Variable | Description | Values | Default | +| -------- | ----------- | ------ | ------- | +| `RIVET_LOG_LEVEL` | Sets the minimum log level to display | `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `silent` | `warn` | +| `RIVET_LOG_TARGET` | Include the module name that logged the message | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_TIMESTAMP` | Include timestamp in log output | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_MESSAGE` | Enable detailed message logging for debugging | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_ERROR_STACK` | Include stack traces in error output | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_HEADERS` | Log HTTP headers in requests | `1` to enable, `0` to disable | `0` | + +Example: +```bash +RIVET_LOG_LEVEL=debug RIVET_LOG_TARGET=1 RIVET_LOG_TIMESTAMP=1 node server.js +``` + +### Log Level + +You can configure the log level programmatically when setting up your registry: + +### Custom Pino Logger + +You can also provide a custom Pino base logger for more advanced logging configurations: + +If using a custom base logger, you must manually configure your own log level in the Pino logger. + +For more advanced Pino configuration options, see the [Pino API documentation](https://getpino.io/#/docs/api?id=export). + +### Disable Welcome Message + +You can disable the default RivetKit welcome message with: + +_Source doc path: /docs/general/logging_ diff --git a/.agents/skills/chat-room/reference/general/pool-configuration.md b/.agents/skills/chat-room/reference/general/pool-configuration.md new file mode 100644 index 0000000..21b00f1 --- /dev/null +++ b/.agents/skills/chat-room/reference/general/pool-configuration.md @@ -0,0 +1,119 @@ +# Pool Configuration + +> Source: `src/content/docs/general/pool-configuration.mdx` +> Canonical URL: https://rivet.dev/docs/general/pool-configuration +> Description: Reference for runner pool configuration, including drain behavior, actor eviction rate limiting, and serverless-specific options. + +--- +A **runner pool** is the set of runners Rivet manages for a given runner name within a namespace. The pool configuration controls how runners are scaled, drained on version upgrades, and how quickly actors are evicted from drained runners. + +There are two pool kinds: + +- **`normal`** — runners connect to the engine themselves (for example a long-running process started by you, Docker, or Kubernetes). The engine does not start or stop runners. +- **`serverless`** — the engine calls an HTTP endpoint to wake runners on demand. Used by serverless platforms (Vercel, Cloudflare Workers, Freestyle, etc.). See [Runtime Modes](/docs/general/runtime-modes). + +## Setting the Configuration + +Configure a pool from the [Rivet dashboard](https://dashboard.rivet.dev) under your namespace's runner settings. The dashboard is the recommended way to manage pool configuration. + +You can also set pool configuration directly through the API or the TypeScript SDK: + +```typescript SDK @nocheck +import { RivetClient } from "@rivetkit/engine-api-full"; + +const rivet = new RivetClient({ + environment: "https://api.rivet.dev", + token: process.env.RIVET_TOKEN!, +}); + +await rivet.runnerConfigsUpsert("default", { + namespace: "default", + datacenters: { + default: { + serverless: { + url: "https://my-app.example.com/api/rivet", + requestLifespan: 60 * 15, + actorEvictionDelay: 5, + actorEvictionPeriod: 60, + actorEvictionRate: 1, + }, + }, + }, +}); +``` + +```bash curl +curl -X PUT "https://api.rivet.dev/runner-configs/default?namespace=default" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "datacenters": { + "default": { + "serverless": { + "url": "https://my-app.example.com/api/rivet", + "request_lifespan": 900, + "actor_eviction_delay": 5, + "actor_eviction_period": 60, + "actor_eviction_rate": 1 + } + } + } + }' +``` + +The HTTP API uses `snake_case`. The TypeScript SDK uses `camelCase`. The field names below use `camelCase`. + +## Common Options + +These options apply to both `normal` and `serverless` pools. + +| Option | Type | Default | Description | +|---|---|---|---| +| `drainOnVersionUpgrade` | `bool` | `true` | When a new runner version is deployed, stop old runners and migrate their actors. See [Versions & Upgrades](/docs/actors/versions#drain-on-version-upgrade). | +| `actorEvictionDelay` | `u32` (seconds) | `0` | Delay before actor eviction begins after a drain is triggered. Gives clients time to receive the drain signal before migrations start. | +| `actorEvictionPeriod` | `u32` (seconds) | `0` | Window over which evictions are batched. Used together with `actorEvictionRate` to smooth eviction load on the rest of the pool. | +| `actorEvictionRate` | `f32` (actors/sec) | `1.0` | Maximum number of actors evicted per second once eviction is underway. Set higher for fast cutovers, lower to spread reschedule load. | +| `metadata` | `object` | — | Arbitrary JSON metadata attached to the pool. Useful for tagging and dashboards. | + +### Tuning eviction rate limiting + +Eviction kicks in whenever a runner is drained — most commonly during a version upgrade with `drainOnVersionUpgrade: true`, but also when a runner disconnects ungracefully or is replaced. + +A typical tuning starts from: + +- `actorEvictionDelay: 5` — five-second head start so clients see the drain notification before migrations begin. +- `actorEvictionPeriod: 60` — batch over a one-minute window. +- `actorEvictionRate: 1` — evict one actor per second. + +Increase `actorEvictionRate` for small pools where a full cutover finishes in seconds. Decrease it for large pools to avoid bursts of reschedule traffic. + +## Serverless-Only Options + +These options only apply when `kind: "serverless"`. + +| Option | Type | Default | Description | +|---|---|---|---| +| `url` | `string` | — | HTTP endpoint the engine calls to wake a runner. | +| `headers` | `map` | `{}` | Additional headers sent with the wake request (for example an auth token). | +| `requestLifespan` | `u32` (seconds) | — | Total lifespan of a serverless request before drain begins. Must be shorter than your platform's request timeout. | +| `maxConcurrentActors` | `u64` | `1000` | Soft cap on concurrent actors hosted across the pool. | +| `drainGracePeriod` | `u32` (seconds) | `1800` (30 min) | Time a serverless runner reserves at the end of its lifespan for actors to stop gracefully. | +| `metadataPollInterval` | `u64` (ms) | engine default | How often each runner re-fetches pool metadata to detect new versions. | + +### Deprecated options + +The following options still parse for backwards compatibility but should not be used in new configurations: + +- `slotsPerRunner` +- `minRunners` +- `maxRunners` +- `runnersMargin` + +## Related + +- [Runtime Modes](/docs/general/runtime-modes) — runner vs serverless behavior. +- [Versions & Upgrades](/docs/actors/versions) — how `drainOnVersionUpgrade` interacts with version detection. +- [Limits](/docs/actors/limits) — request lifespan and drain grace period limits. +- [Debugging](/docs/actors/debugging) — inspect a pool configuration via the API. + +_Source doc path: /docs/general/pool-configuration_ diff --git a/.agents/skills/chat-room/reference/general/production-checklist.md b/.agents/skills/chat-room/reference/general/production-checklist.md new file mode 100644 index 0000000..1ebe257 --- /dev/null +++ b/.agents/skills/chat-room/reference/general/production-checklist.md @@ -0,0 +1,98 @@ +# Production Checklist + +> Source: `src/content/docs/general/production-checklist.mdx` +> Canonical URL: https://rivet.dev/docs/general/production-checklist +> Description: Checklist for deploying Rivet Actors to production. + +--- +We recommend passing this page to your coding agent to verify your configuration before deploying. + +## Environment + +- **Set `NODE_ENV=production`.** Ensures optimized performance and disables development-only behavior. +- **Ensure log level is not set to debug.** Leave `RIVET_LOG_LEVEL` at its default or explicitly set it to `warn` to avoid excessive logging. See [Logging](/docs/general/logging). +- **Do not set `RIVET_EXPOSE_ERRORS=1` in production.** This exposes internal error details to clients. It is automatically enabled when `NODE_ENV=development`. See [Errors](/docs/actors/errors). + +## Runtime Mode + +- **Configure a runner version.** Required for graceful upgrades and draining of old actors. Applies to both serverless and runner modes. See [Versions & Upgrades](/docs/actors/versions). + +### Serverless + +- **Check platform timeouts.** Rivet handles migration between invocations automatically, but shorter timeouts increase migration frequency. See [Timeouts](/docs/general/runtime-modes#timeouts). +- **Verify `/api/rivet/start` body size limits.** Serverless actor starts carry actor config and preloaded KV or SQLite startup data in the request body. Keep `serverless.maxStartPayloadBytes` and your platform or proxy body limit at **16 MiB or higher**, or lower the preload budget if your platform cannot accept that size. See [Limits](/docs/actors/limits#kv-preloading). +- **Configure max runners.** Go to Settings > Providers > Edit Provider > Max Runners to set the limit. The default is 100,000 runners. This is effectively your max actor count. +- **Verify your platform rate limit accommodates your actor create and wake frequency.** Actor start requests are sent from Rivet's servers, so they all originate from the same IP. Per-IP rate limits will throttle the engine well before they would throttle real end-user traffic. Size your platform's rate limit to your peak actor create and wake rate, not your end-user request rate. +- **Set the per-instance max concurrent actor limit.** Each serverless instance hosts one actor per in-flight `/api/rivet/start` request, so your platform's per-instance concurrency (e.g. GCP Cloud Run `--concurrency`, AWS Lambda reserved concurrency, Vercel `maxDuration` + concurrency) directly caps actors per instance. Pick a value based on per-actor memory and CPU; the platform autoscales out additional instances once existing ones hit the cap. +- **Tune `requestLifespan` to your platform's hard request timeout.** `requestLifespan` (default `3600`, 60 minutes) is the total lifespan of each serverless request before actors migrate to a fresh instance. Set it just below your platform's hard timeout (e.g. `295` for Vercel Hobby, `3595` for Vercel Pro, `840` for Cloud Run's 15-min cap). Configure via [`configurePool`](/docs/general/registry-configuration). See [Timeouts](/docs/general/runtime-modes#timeouts). +- **Tune `drainGracePeriod` to cover graceful actor shutdown.** Time reserved at the end of `requestLifespan` for actors to stop gracefully before the request is forcibly closed. Default is 30 minutes from the engine; lower it for short-lived stateless actors, raise it if your actors do non-trivial cleanup or final SQLite writes. Configure via [`configurePool`](/docs/general/registry-configuration). See [Limits](/docs/actors/limits). + +### Runner + +- **Set a graceful shutdown period of at least 35 minutes.** Runners need up to 30 minutes to drain actors during upgrades, plus buffer for shutdown overhead. In Kubernetes, set `terminationGracePeriodSeconds: 2100` on the pod spec. + +## Actors + +### Design Patterns + +- **Do not use god actors.** Avoid putting all logic into a single actor type. See [Design Patterns](/docs/actors/design-patterns). +- **Do not use actor-per-request patterns.** Avoid creating a new actor for each request. See [Design Patterns](/docs/actors/design-patterns). + +### Lifecycle + +- **Do not rely on `onSleep` for critical cleanup.** `onSleep` is not called during crashes or forced terminations. See [Lifecycle](/docs/actors/lifecycle). + +### State + +- **Verify `c.state` does not grow unbounded.** Avoid using arrays or objects that grow over time in state. Use [SQLite](/docs/actors/sqlite) for unbounded or append-heavy data instead. +- **Verify actor data does not exceed 10 GB.** Contact [enterprise support](https://rivet.dev/sales) if you need more storage. +- **Use input parameters and `createState` for actor initialization.** See [Input Parameters](/docs/actors/input). + +### Events + +- **Use `conn.send()` instead of `c.broadcast()` for private events.** `c.broadcast()` sends to all connected clients. Use `conn.send()` to send events to a specific connection. See [Realtime](/docs/actors/events). + +### Actions + +- **Review action timeout configuration.** The default `actionTimeout` is 60 seconds. Increase it if you have long-running actions like API calls or file processing. See [Actor Configuration](/docs/general/actor-configuration). +- **Review message size limits.** The default `maxIncomingMessageSize` is 64 KiB and `maxOutgoingMessageSize` is 1 MiB. Increase if your actors send or receive large JSON payloads. See [Registry Configuration](/docs/general/registry-configuration). + +### Queues + +- **Review queue limits.** The default `maxQueueSize` is 1,000 messages and `maxQueueMessageSize` is 64 KiB. Increase if you expect burst traffic or large queue payloads. See [Actor Configuration](/docs/general/actor-configuration). +- **Ensure queue handlers are idempotent.** If processing fails before `message.complete()`, the message will be retried. See [Queues](/docs/actors/queues). + +### Workflows + +- **Verify workflows do not generate infinite steps.** Use `ctx.loop` to avoid creating unbounded step histories. See [Workflows](/docs/actors/workflows). + +## Security + +### Authentication + +- **Validate connections in `createConnState` or `onBeforeConnect`.** Do not trust client input without validation. See [Authentication](/docs/actors/authentication). + +### CORS + +- **Configure CORS for production.** Restrict allowed origins instead of allowing all. See [CORS](/docs/general/cors). + +### Tokens (Rivet Cloud) + +- **Use `pk_*` tokens for `RIVET_PUBLIC_ENDPOINT`.** Public tokens are safe to expose to clients. +- **Use `sk_*` tokens for `RIVET_ENDPOINT`.** Secret tokens should only be used server-side. +- **Do not leak your secret token.** Never expose `sk_*` tokens in client-side code, public repositories, or browser environments. See [Endpoints](/docs/general/endpoints). +- **Verify you're connecting to the correct region.** Use the nearest datacenter endpoint (e.g. `api-us-west-1.rivet.dev`) for lowest latency. + +### Access Control + +Access control is only needed if you want granular permissions for different clients. For most use cases, basic authentication in `onBeforeConnect` or `createConnState` is sufficient. + +- **Use deny-by-default rules.** Reject unknown roles in `onBeforeConnect`, action handlers, `canPublish`, and `canSubscribe`. See [Access Control](/docs/actors/access-control). +- **Authorize actions explicitly.** Check the caller's role in each action handler and throw `forbidden` for unauthorized access. +- **Gate event subscriptions and queue publishes.** Use `canSubscribe` and `canPublish` hooks to restrict which clients can subscribe to events or publish to queues. + +## Clients + +- **Dispose connections and/or client when not in use (JavaScript client).** Call `conn.dispose()` or `client.dispose()` when no longer needed to free resources. React and SwiftUI clients handle this automatically. See [Connection Lifecycle](/docs/clients/javascript#connection-lifecycle). + +_Source doc path: /docs/general/production-checklist_ diff --git a/.agents/skills/chat-room/reference/general/registry-configuration.md b/.agents/skills/chat-room/reference/general/registry-configuration.md new file mode 100644 index 0000000..3574c4a --- /dev/null +++ b/.agents/skills/chat-room/reference/general/registry-configuration.md @@ -0,0 +1,32 @@ +# Registry Configuration + +> Source: `src/content/docs/general/registry-configuration.mdx` +> Canonical URL: https://rivet.dev/docs/general/registry-configuration +> Description: This page documents the configuration options available when setting up a RivetKit registry. The registry configuration is passed to the `setup()` function. + +--- +## Example Configurations + +### Basic Setup + +### Connecting to Rivet Engine + +## Starting Your App + +After configuring your registry, start it: + +See [Runtime Modes](/docs/general/runtime-modes) for details on when to use each mode. + +## Environment Variables + +Many configuration options can be set via environment variables. See [Environment Variables](/docs/general/environment-variables) for a complete reference. + +## Configuration Reference + +## Related + +- [Actor Configuration](/docs/general/actor-configuration): Configure individual actors +- [HTTP Server Setup](/docs/general/http-server): Set up HTTP routing and middleware +- [Architecture](/docs/general/architecture): Understand how RivetKit works + +_Source doc path: /docs/general/registry-configuration_ diff --git a/.agents/skills/chat-room/reference/general/runtime-modes.md b/.agents/skills/chat-room/reference/general/runtime-modes.md new file mode 100644 index 0000000..43ba986 --- /dev/null +++ b/.agents/skills/chat-room/reference/general/runtime-modes.md @@ -0,0 +1,99 @@ +# Runtime Modes + +> Source: `src/content/docs/general/runtime-modes.mdx` +> Canonical URL: https://rivet.dev/docs/general/runtime-modes +> Description: RivetKit supports two runtime modes for running your actors: + +--- +- **Serverless**: Default mode. Responds to HTTP requests and scales automatically. +- **Runners**: Background processes without HTTP endpoints. Only needed for advanced scenarios. + +## Serverless + +Serverless is the default and recommended mode. Rivet sends HTTP requests to your backend to run actor logic, allowing your infrastructure to scale automatically. + +### Benefits + +- **Platform support**: Works with serverless platforms (Vercel, Cloudflare Workers, etc.) +- **Scale to zero**: No cost when idle +- **Edge deployments**: Easier to deploy to edge locations +- **Preview deployments**: Integrates with preview deployments on platforms like Vercel and Railway +- **Efficient autoscaling**: Request-based autoscaling can be faster and more efficient than CPU-based autoscaling depending on the platform + +### Example + +See [Server Setup](/docs/general/http-server/) for more configuration options. + +### Architecture + +When a client creates an actor, it sends a request to the Rivet Engine. The engine then calls `GET /api/rivet/start` on your serverless backend to run the actor. + +Serverless architecture diagram + +### Advanced + +#### Endpoints + +Rivet exposes the following endpoints: + +- `GET /api/rivet/metadata`: Validates configuration +- `GET /api/rivet/start`: Runs an actor + +You should never call these endpoints yourself, this is included purely for comprehension of how Rivet works under the hood. + +#### Timeouts + +Serverless platforms like Vercel have function timeouts. Rivet handles this automatically by migrating actors between function invocations, preserving state through `ctx.state`. Write your code as if it runs forever, Rivet handles the rest. + +Read more about [how we handle timeouts](/blog/2025-10-20-how-we-built-websocket-servers-for-vercel-functions/#timeouts-and-failover). + +#### Shutdown Sequence + +Each serverless request has a configurable lifespan (`requestLifespan`, default: 60 minutes). Set this to match your platform's function timeout (e.g. `requestLifespan: 3600` for Vercel Pro). + +When the request nears its lifespan, the engine reserves a grace period (`serverless_drain_grace_period`, default: 10 seconds) at the end to gracefully stop actors. For example, with a 3600-second lifespan, actors begin stopping at 3590 seconds. After the full lifespan elapses, the connection is forcibly closed and any remaining actors are rescheduled. + +See [Limits](/docs/actors/limits#serverless-shutdown) for configuration details. + +## Runners + +Runners run actors as long-running background processes without exposing an HTTP endpoint. + +### When to Use Runners + +- **No HTTP server**: Your app does not or cannot expose an HTTP server +- **No load balancer**: You don't have a load balancer to distribute HTTP requests across your servers +- **Custom scaling**: You have custom scaling requirements + +### Example + +The runner runs in the background, ready to run actors. + +### Architecture + +On startup, your backend calls `registry.startEnvoy()` which opens a persistent connection to the Rivet Engine. When a client creates an actor, the engine sends a command through this connection to start the actor on your backend. + +Runners architecture diagram + +### Configuration + +#### Runner Pool + +Use `RIVET_RUNNER` to assign runners to a pool. This lets you control which runners handle specific actors. + +```bash +RIVET_RUNNER=gpu-workers +``` + +See [Pool Configuration](/docs/general/pool-configuration) for how pools are scaled, drained on version upgrades, and rate-limited during actor eviction. + +## Comparison + +| Mode | Method | Use Case | +|------|--------|----------| +| Auto | `registry.start()` | Simplest setup. Starts server, serves static files, and runs actors. | +| Serverless | `registry.serve()` | Fetch handler for serverless platforms | +| Serverless | `registry.handler()` | Integrating with existing routers (Hono, Elysia, etc.) | +| Runner | `registry.startEnvoy()` | Long-running processes without HTTP endpoints | + +_Source doc path: /docs/general/runtime-modes_ diff --git a/.agents/skills/chat-room/reference/general/wasm-vs-native-sdk.md b/.agents/skills/chat-room/reference/general/wasm-vs-native-sdk.md new file mode 100644 index 0000000..18cdd13 --- /dev/null +++ b/.agents/skills/chat-room/reference/general/wasm-vs-native-sdk.md @@ -0,0 +1,79 @@ +# WASM vs Native SDK + +> Source: `src/content/docs/general/wasm-vs-native-sdk.mdx` +> Canonical URL: https://rivet.dev/docs/general/wasm-vs-native-sdk +> Description: RivetKit runs your actors on a native or a WebAssembly runtime depending on your platform. + +--- +RivetKit ships two runtimes for executing actor logic. Most projects use the +native runtime automatically. Edge and serverless platforms that cannot run +native binaries use the WebAssembly runtime. + +- **Native**: Default. Runs on Node.js and Bun via native bindings. Best performance. +- **WebAssembly (wasm)**: Runs anywhere a `WebAssembly.Module` can be instantiated, including Cloudflare Workers, Supabase Edge Functions, and Deno Deploy. + +## Native runtime + +The native runtime is the default and requires no configuration. It loads +platform-specific native bindings for the best performance and full feature +support on Node.js and Bun. + +## WebAssembly runtime + +Edge platforms run on isolates (V8, Deno) that cannot load native binaries, so +RivetKit provides a WebAssembly build of its core runtime in the +`@rivetkit/rivetkit-wasm` package. You select it with `runtime: "wasm"` and pass +the wasm bindings and binary through the `wasm` option. + +### Recommended: use a platform package + +For supported platforms, use the dedicated package instead of wiring the wasm +runtime by hand. They install the wasm runtime, load the binary, and (on +Cloudflare) provide the outbound WebSocket the engine tunnel needs. + +- **Cloudflare Workers**: [`@rivetkit/cloudflare-workers`](/docs/actors/quickstart/cloudflare) +- **Supabase Edge Functions**: [`@rivetkit/supabase`](/docs/actors/quickstart/supabase) + +```typescript @nocheck +// Cloudflare Workers +import { actor } from "rivetkit"; +import { createHandler } from "@rivetkit/cloudflare-workers"; + +const counter = actor({ state: { count: 0 }, actions: {} }); + +export default createHandler({ use: { counter } }); +``` + +### Manual configuration + +For platforms without a dedicated package, configure the wasm runtime directly. +Pass the bindings from `@rivetkit/rivetkit-wasm` and the wasm binary as +`initInput`. `initInput` accepts a `Uint8Array`, `URL`, `Response`, or a +`WebAssembly.Module`. + +```typescript @nocheck +import { actor, setup } from "rivetkit"; +import * as wasmBindings from "@rivetkit/rivetkit-wasm"; +import wasmModule from "@rivetkit/rivetkit-wasm/rivetkit_wasm_bg.wasm"; + +const counter = actor({ state: { count: 0 }, actions: {} }); + +const registry = setup({ + runtime: "wasm", + wasm: { bindings: wasmBindings, initInput: wasmModule }, + use: { counter }, +}); +``` + +On platforms without an outbound `new WebSocket(url)` constructor (such as +Cloudflare Workers), you must also install a fetch-based `globalThis.WebSocket` +shim so the actor can open its tunnel to the engine. The platform packages handle +this for you, which is why they are recommended. + +## Related + +- [Runtime Modes](/docs/general/runtime-modes) +- [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) +- [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) + +_Source doc path: /docs/general/wasm-vs-native-sdk_ diff --git a/.agents/skills/chat-room/reference/self-hosting/configuration.md b/.agents/skills/chat-room/reference/self-hosting/configuration.md new file mode 100644 index 0000000..a71d16e --- /dev/null +++ b/.agents/skills/chat-room/reference/self-hosting/configuration.md @@ -0,0 +1,74 @@ +# Configuration + +> Source: `src/content/docs/self-hosting/configuration.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/configuration +> Description: Rivet Engine can be configured through environment variables or configuration files. + +--- +The full JSON Schema for the configuration is available at [/docs/engine-config-schema.json](/docs/engine-config-schema.json). + +## Configuration Sources + +Rivet supports JSON, JSON5, JSONC, YAML, YML, and environment variable configurations. + +**Environment Variables** + +Use the `RIVET__` prefix with `__` as separator to configure properties in the config. For example: set the `RIVET__database__postgres__url` environment variable for `database.postgres.url`. + +**Configuration Paths** + +Configuration files are automatically discovered in platform-specific directories: + +- Linux: `/etc/rivet/config.json` +- macOS: `/Library/Application Support/rivet/config.json` +- Windows: `C:\ProgramData\rivet\config.json` + +**Multiple Files** + +Multiple configuration files in the same directory are loaded and merged together. For example: `/etc/rivet/config.json` and `/etc/rivet/database.json` will be merged together. + +**Override Configuration Path** + +You can override the default configuration path using the `--config` flag: + +```bash +# Load from a specific file +rivet-engine --config /path/to/config.json + +# Load from a directory +rivet-engine --config /etc/rivet + +# Load multiple paths (merged in order) +rivet-engine --config /etc/rivet/base.json --config /etc/rivet/override.json +``` + +## Configuration Reference + +### Pegboard Envoy Load Balancing + +`pegboard.envoy_load_balancer` supports the `hash` strategy for hash-ring-based envoy selection: + +```json +{ + "pegboard": { + "envoy_load_balancer": { + "hash": { + "virtual_nodes": 8, + "samples": 2, + "max_scan": 16, + "use_snapshot_read": true + } + } + } +} +``` + +Use `samples: 1` for a uniform random pick that skips slot reads. Use `samples >= 2` for power-of-K choices over envoy slot counts. Treat `virtual_nodes` as an operational invariant once envoys have registered. + +## Related + +- RivetKit actor runtime persistence lives in SQLite. Existing actor KV data is imported into SQLite the first time an actor wakes on the migrated runtime, then the original KV data is left frozen for downgrade safety. +- [PostgreSQL](/docs/self-hosting/postgres): Configure the experimental PostgreSQL backend +- [File System](/docs/self-hosting/filesystem): Configure file system storage for development + +_Source doc path: /docs/self-hosting/configuration_ diff --git a/.agents/skills/chat-room/reference/self-hosting/docker-compose.md b/.agents/skills/chat-room/reference/self-hosting/docker-compose.md new file mode 100644 index 0000000..8f2cea1 --- /dev/null +++ b/.agents/skills/chat-room/reference/self-hosting/docker-compose.md @@ -0,0 +1,188 @@ +# Docker Compose + +> Source: `src/content/docs/self-hosting/docker-compose.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/docker-compose +> Description: Deploy Rivet Engine with docker-compose for multi-container setups. + +--- +## Quick Start + +### Create docker-compose.yaml + +Create a `docker-compose.yaml` in your project root: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - rivet-data:/data + environment: + RIVET__FILE_SYSTEM__PATH: "/data" + restart: unless-stopped + +volumes: + rivet-data: +``` + +### Start the engine + +```bash +docker-compose up -d +``` + +## Connecting Your Project + +Once the engine is running, add your app as a service in the same Compose file. + +### Create your server + +Follow the [quickstart](/docs/actors/quickstart/backend) to create a working server with actors. + +### Create a Dockerfile + +Create a `Dockerfile` in your project root: + +```dockerfile @nocheck +FROM node:22-slim +WORKDIR /app +COPY package.json pnpm-lock.yaml ./ +RUN corepack enable && pnpm install --frozen-lockfile +COPY . . +RUN pnpm build +CMD ["node", "dist/index.js"] +``` + +### Add your app to docker-compose.yaml + +Update your `docker-compose.yaml` to include your app alongside the engine: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - rivet-data:/data + environment: + RIVET__FILE_SYSTEM__PATH: "/data" + restart: unless-stopped + + my-app: + build: . + environment: + RIVET_ENDPOINT: "http://default:admin@rivet-engine:6420" + depends_on: + - rivet-engine + restart: unless-stopped + +volumes: + rivet-data: +``` + +`RIVET_ENDPOINT` tells your app to connect to the engine as a runner instead of running standalone. The URL uses the format `http://namespace:token@host:port`. Inside the Docker network, your app reaches the engine at `rivet-engine:6420`. See [Endpoints](/docs/general/endpoints) for all options. + +### Start the services + +```bash +docker-compose up -d +``` + +### Register your runner with the engine + +### Dashboard + +1. Open the Rivet Engine dashboard at `http://localhost:6420`. +2. Enter your admin token when prompted. +3. In the namespace sidebar, click **Settings**. +4. Click **Add Provider**, then choose **Custom**. +5. Click **Next** (these settings can be changed later). +6. Click **Next** (you can safely skip the env ar step for Docker Compose). +5. Go to **Confirm Connection**, enter your app endpoint (`http://my-app:6420/api/rivet`), then click **Add**. + +### CLI (curl) + +Register your runner programmatically via the engine API: + +```bash @nocheck +curl -X PUT "http://localhost:6420/runner-configs/default?namespace=default" \ + -H "Content-Type: application/json" \ + -d '{ + "datacenters": { + "default": { + "normal": {} + } + } + }' +``` + +## Configuration + +### Config File + +Mount a JSON configuration file in your `docker-compose.yaml`: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - ./rivet-config.json:/etc/rivet/config.json:ro + - rivet-data:/data + restart: unless-stopped + +volumes: + rivet-data: +``` + +Create `rivet-config.json` in the same directory as your `docker-compose.yaml`. See the [Configuration](/docs/self-hosting/configuration) docs for all available options and the full [JSON Schema](/docs/engine-config-schema.json). + +```json +{ + "postgres": { + "url": "postgresql://rivet:password@postgres:5432/rivet" + } +} +``` + +### Postgres Setup + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +```yaml +services: + postgres: + image: postgres:15 + environment: + POSTGRES_DB: rivet + POSTGRES_USER: rivet + POSTGRES_PASSWORD: rivet_password + volumes: + - postgres-data:/var/lib/postgresql/data + restart: unless-stopped + + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + environment: + RIVET__POSTGRES__URL: postgresql://rivet:rivet_password@postgres:5432/rivet + depends_on: + - postgres + restart: unless-stopped + +volumes: + postgres-data: +``` + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/docker-compose_ diff --git a/.agents/skills/chat-room/reference/self-hosting/docker-container.md b/.agents/skills/chat-room/reference/self-hosting/docker-container.md new file mode 100644 index 0000000..e6983ae --- /dev/null +++ b/.agents/skills/chat-room/reference/self-hosting/docker-container.md @@ -0,0 +1,150 @@ +# Docker Container + +> Source: `src/content/docs/self-hosting/docker-container.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/docker-container +> Description: Run Rivet Engine in a single Docker container. + +--- +## Quick Start + +### Start the engine + +```bash +docker run -d \ + --name rivet-engine \ + -p 6420:6420 \ + -v rivet-data:/data \ + -e RIVET__FILE_SYSTEM__PATH="/data" \ + rivetdev/engine:latest +``` + +### Verify the engine is running + +```bash +curl http://localhost:6420/health +``` + +## Connecting Your Project + +Once the engine is running, connect your app to it. + +### Create your server + +Follow the [quickstart](/docs/actors/quickstart/backend) to create a working server with actors. + +### Start your app with RIVET_ENDPOINT + +Set `RIVET_ENDPOINT` to tell your app to connect to the engine as a runner instead of running standalone: + +```bash @nocheck +RIVET_ENDPOINT="http://default:admin@host.docker.internal:6420" npm start +``` + +If running your app outside of Docker, use `localhost` instead of `host.docker.internal`: + +```bash @nocheck +RIVET_ENDPOINT="http://default:admin@localhost:6420" npm start +``` + +See [Endpoints](/docs/general/endpoints) for all options. + +### Register your runner with the engine + +### Dashboard + +1. Open the Rivet Engine dashboard at `http://localhost:6420`. +2. Enter your admin token when prompted. +3. In the namespace sidebar, click **Settings**. +4. Click **Add Provider**, then choose **Custom**. +5. Click **Next**. +6. Go to **Confirm Connection**, enter your app endpoint, then click **Add**. + +### CLI (curl) + +Register your runner programmatically via the engine API: + +```bash @nocheck +curl -X PUT "http://localhost:6420/runner-configs/default?namespace=default" \ + -H "Content-Type: application/json" \ + -d '{ + "datacenters": { + "default": { + "normal": {} + } + } + }' +``` + +## Configuration + +### Environment Variables + +Configure Rivet using environment variables: + +```bash +docker run -d \ + --name rivet-engine \ + -p 6420:6420 \ + -v rivet-data:/data \ + -e RIVET__FILE_SYSTEM__PATH="/data" \ + -e RIVET__POSTGRES__URL="postgresql://postgres:password@localhost:5432/db" \ + rivetdev/engine:latest +``` + +### Config File + +Mount a JSON configuration file: + +```bash +docker run -d \ + --name rivet-engine \ + -p 6420:6420 \ + -v rivet-data:/data \ + -v $(pwd)/rivet-config.json:/etc/rivet/config.json:ro \ + rivetdev/engine:latest +``` + +Create `rivet-config.json` in your working directory. See the [Configuration](/docs/self-hosting/configuration) docs for all available options and the full [JSON Schema](/docs/engine-config-schema.json). + +```json +{ + "postgres": { + "url": "postgresql://postgres:password@localhost:5432/db" + } +} +``` + +### Postgres Setup + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +```bash +# Create network +docker network create rivet-net + +# Run PostgreSQL +docker run -d \ + --name postgres \ + --network rivet-net \ + -e POSTGRES_DB=rivet \ + -e POSTGRES_USER=rivet \ + -e POSTGRES_PASSWORD=rivet_password \ + -v postgres-data:/var/lib/postgresql/data \ + postgres:15 + +# Run Rivet Engine +docker run -d \ + --name rivet-engine \ + --network rivet-net \ + -p 6420:6420 \ + -e RIVET__POSTGRES__URL="postgresql://rivet:rivet_password@postgres:5432/rivet" \ + rivetdev/engine +``` + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- Use [Docker Compose](/docs/self-hosting/docker-compose) for multi-container setups +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/docker-container_ diff --git a/.agents/skills/chat-room/reference/self-hosting/filesystem.md b/.agents/skills/chat-room/reference/self-hosting/filesystem.md new file mode 100644 index 0000000..30f7bdb --- /dev/null +++ b/.agents/skills/chat-room/reference/self-hosting/filesystem.md @@ -0,0 +1,47 @@ +# File System + +> Source: `src/content/docs/self-hosting/filesystem.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/filesystem +> Description: The file system backend stores all data on the local disk. This is suitable for single-node deployments, development, and testing. + +--- +For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based); for multi-node deployments, PostgreSQL is the recommended backend today but remains experimental as we evaluate the best fit for scalability and performance, and Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB. + +## Configuration + +```json Configuration-file +{ + "database": { + "file_system": { + "path": "/var/lib/rivet/data" + } + } +} +``` + +```bash Environment-variables +RIVET__database__file_system__path="/var/lib/rivet/data" +``` + +## Default Paths + +If no path is specified, Rivet uses platform-specific default locations: + +- Linux: `~/.local/share/rivet-engine/db` +- macOS: `~/Library/Application Support/rivet-engine/db` +- Windows: `%APPDATA%\rivet-engine\db` + +When running in a container or as a service, the path defaults to `./data/db` relative to the working directory. + +## When to Use File System + +The file system backend is ideal for: + +- Local development +- Single-node deployments +- Testing and prototyping +- Air-gapped environments without database infrastructure + +If you need a production-ready Rivet deployment today, use this backend for smaller single-node setups; for multi-node deployments, PostgreSQL is the recommended backend today though still experimental, and Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +_Source doc path: /docs/self-hosting/filesystem_ diff --git a/.agents/skills/chat-room/reference/self-hosting/foundationdb.md b/.agents/skills/chat-room/reference/self-hosting/foundationdb.md new file mode 100644 index 0000000..b8331bb --- /dev/null +++ b/.agents/skills/chat-room/reference/self-hosting/foundationdb.md @@ -0,0 +1,35 @@ +# FoundationDB (Enterprise) + +> Source: `src/content/docs/self-hosting/foundationdb.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/foundationdb +> Description: FoundationDB is the recommended storage backend for scalable production Rivet deployments. + +--- +FoundationDB requires an enterprise license. Contact [enterprise support](https://rivet.dev/sales) for setup guidance and access. + +## Overview + +FoundationDB is the recommended storage backend for scalable, production-ready Rivet deployments. It is a distributed, ordered key-value store originally built by Apple. + +FoundationDB powers some of the largest infrastructure in the world: + +- **Apple**: iCloud and other Apple services +- **Snowflake**: Cloud data platform metadata layer +- **Datadog**: Observability and monitoring platform +- **Tigris Data**: Globally distributed object storage + +Its strict serializability guarantees, fault tolerance, and ability to scale linearly across nodes make it the ideal backend for Rivet's actor state and orchestration layer. + +## Why FoundationDB + +| | RocksDB (File System) | PostgreSQL | FoundationDB | +|---|---|---|---| +| **Scalability** | Single node | Primary/replica failover | Linear horizontal scaling | +| **Fault tolerance** | None | Primary/replica failover | Automatic recovery with no data loss | +| **Production readiness** | Development and small deployments | Experimental for multi-node | Battle-tested at global scale | + +## Getting Started + +FoundationDB configuration and cluster setup are handled as part of enterprise onboarding. Contact [enterprise support](https://rivet.dev/sales) to get started. + +_Source doc path: /docs/self-hosting/foundationdb_ diff --git a/.agents/skills/chat-room/reference/self-hosting/install.md b/.agents/skills/chat-room/reference/self-hosting/install.md new file mode 100644 index 0000000..344be8e --- /dev/null +++ b/.agents/skills/chat-room/reference/self-hosting/install.md @@ -0,0 +1,32 @@ +# Installing Rivet Engine + +> Source: `src/content/docs/self-hosting/install.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/install +> Description: Install Rivet Engine using Docker, binaries, or a source build. + +--- +For more options: + +- [Docker Container](/docs/self-hosting/docker-container) for persistent storage, configuration, and production setups +- [Docker Compose](/docs/self-hosting/docker-compose) for multi-container deployments with PostgreSQL + +## Docker + +```bash +docker run -p 6420:6420 rivetdev/engine +``` + +## Prebuilt Binaries + + Prebuilt binaries coming soon + +## Build From Source + +```bash +git clone https://github.com/rivet-dev/rivet.git +cd rivet +cargo build --release -p rivet-engine +./target/release/rivet-engine +``` + +_Source doc path: /docs/self-hosting/install_ diff --git a/.agents/skills/chat-room/reference/self-hosting/kubernetes.md b/.agents/skills/chat-room/reference/self-hosting/kubernetes.md new file mode 100644 index 0000000..a2c619c --- /dev/null +++ b/.agents/skills/chat-room/reference/self-hosting/kubernetes.md @@ -0,0 +1,236 @@ +# Kubernetes + +> Source: `src/content/docs/self-hosting/kubernetes.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/kubernetes +> Description: Deploy production-ready Rivet Engine to Kubernetes with PostgreSQL storage. + +--- +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Prerequisites + +- Kubernetes cluster +- `kubectl` configured +- [Metrics server](https://github.com/kubernetes-sigs/metrics-server) (required for HPA) — included by default in most distributions (k3d, GKE, EKS, AKS) + +## Deploy Rivet Engine + + +### Download Manifests + + Download the `self-host/k8s/engine` directory from the Rivet repository: + + ```bash + npx giget@latest gh:rivet-dev/rivet/self-host/k8s/engine rivet-k8s + cd rivet-k8s + ``` + + + +### Configure Engine + + In `02-engine-configmap.yaml`, set `public_url` to your engine's external URL. + + + +### Configure PostgreSQL + + In `11-postgres-secret.yaml`, update the PostgreSQL password. See [Using a Managed PostgreSQL Service](#using-a-managed-postgresql-service) for external databases. + + + +### Configure Admin Token + + Generate a secure admin token and save it somewhere safe: + + ```bash + openssl rand -hex 32 + ``` + + Create the namespace and store the token as a Kubernetes secret: + + ```bash + kubectl create namespace rivet-engine + kubectl -n rivet-engine create secret generic rivet-secrets --from-literal=admin-token=YOUR_TOKEN_HERE + ``` + + + +### Deploy + + ```bash + # Apply all manifests + kubectl apply -f . + + # Wait for all pods to be ready + kubectl -n rivet-engine wait --for=condition=ready pod -l app=nats --timeout=300s + kubectl -n rivet-engine wait --for=condition=ready pod -l app=postgres --timeout=300s + kubectl -n rivet-engine wait --for=condition=ready pod -l app=rivet-engine --timeout=300s + + # Verify all pods are running + kubectl -n rivet-engine get pods + ``` + + + +### Access the Engine + + Visit `/ui` on your `public_url` to access the dashboard. + + +## Connecting Your Project + +### Create your server + +Follow the [quickstart](/docs/actors/quickstart/backend) to create a working server with actors. + +### Create Kubernetes manifests + +Create these manifest files for your app: + +```yaml deployment.yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: rivetkit-app + namespace: your-namespace +spec: + replicas: 1 + selector: + matchLabels: + app: rivetkit-app + template: + metadata: + labels: + app: rivetkit-app + spec: + # Allow enough time for actors to gracefully stop on SIGTERM. + # The runner waits up to 30m for actors to finish. + # Add buffer for runner shutdown overhead after actors stop. + # See: /docs/actors/versions#graceful-shutdown-sigterm + terminationGracePeriodSeconds: 2100 + containers: + - name: rivetkit-app + image: registry.example.com/your-team/rivetkit-app:latest + envFrom: + - secretRef: + name: rivetkit-secrets +``` + +```yaml service.yaml +apiVersion: v1 +kind: Service +metadata: + name: rivetkit-app + namespace: your-namespace +spec: + selector: + app: rivetkit-app + ports: + - name: http + port: 8080 + targetPort: 8080 +``` + +### Configure the endpoint + +Create `rivetkit-secrets.yaml` with `RIVET_ENDPOINT` pointing to the engine. This tells your app to connect as a runner instead of running standalone. See [Endpoints](/docs/general/endpoints) for all options. + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: rivetkit-secrets + namespace: your-namespace +type: Opaque +stringData: + RIVET_ENDPOINT: http://my-app:your-admin-token@your-engine.example.com +``` + +### Deploy your app + +```bash +kubectl apply -f rivetkit-secrets.yaml +kubectl apply -f deployment.yaml +kubectl apply -f service.yaml +``` + +### Register your runner with the engine + +### Dashboard + +1. Open the Rivet Engine dashboard in your browser. +2. Enter your admin token when prompted. +3. In the namespace sidebar, click **Settings**. +4. Click **Add Provider**, then choose **Custom**. +5. Click **Next**. +6. Go to **Confirm Connection**, enter your app endpoint (e.g. `http://rivetkit-app.your-namespace:8080/api/rivet`), then click **Add**. + +### CLI (curl) + +Register your runner programmatically via the engine API: + +```bash @nocheck +curl -X PUT "https://your-engine.example.com/runner-configs/default?namespace=default" \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer your-admin-token" \ + -d '{ + "datacenters": { + "default": { + "normal": {} + } + } + }' +``` + +## Advanced + +### Using a Managed PostgreSQL Service + +If you prefer to use a managed PostgreSQL service (e.g. Amazon RDS, Cloud SQL, Azure Database) instead of the bundled Postgres deployment: + +- Update the `postgres.url` connection string in `02-engine-configmap.yaml` to point to your managed instance +- Delete the bundled PostgreSQL manifests: + - `10-postgres-configmap.yaml` + - `11-postgres-secret.yaml` + - `12-postgres-statefulset.yaml` + - `13-postgres-service.yaml` + +### Applying Configuration Updates + +When making subsequent changes to `02-engine-configmap.yaml`, restart the engine pods to pick up the new configuration: + +```bash +kubectl apply -f 02-engine-configmap.yaml +kubectl -n rivet-engine rollout restart deployment/rivet-engine +``` + +### Ingress and Load Balancer Timeouts + +Rivet uses long-lived WebSocket connections for both client traffic (browsers, SDKs) and envoy traffic (actor hosts connecting back to the engine). Default Ingress and cloud load balancer idle timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +Raise the idle / read / send timeout on every Ingress and load balancer in front of the engine to at least 1 hour (`3600` seconds). Examples: + +- **NGINX Ingress** (annotations on the Ingress): + + ```yaml + nginx.ingress.kubernetes.io/proxy-read-timeout: "3600" + nginx.ingress.kubernetes.io/proxy-send-timeout: "3600" + ``` + +- **AWS Load Balancer Controller (ALB)**: + + ```yaml + alb.ingress.kubernetes.io/load-balancer-attributes: idle_timeout.timeout_seconds=3600 + ``` + +- **GCE Ingress (GKE)**: set `timeoutSec: 3600` on the `BackendConfig` referenced by the Service. + +The same guidance applies to the load balancer fronting your RivetKit app, since envoys connect to it over WebSocket. + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all engine config options + +_Source doc path: /docs/self-hosting/kubernetes_ diff --git a/.agents/skills/chat-room/reference/self-hosting/multi-region.md b/.agents/skills/chat-room/reference/self-hosting/multi-region.md new file mode 100644 index 0000000..2ecca85 --- /dev/null +++ b/.agents/skills/chat-room/reference/self-hosting/multi-region.md @@ -0,0 +1,10 @@ +# Multi-Region + +> Source: `src/content/docs/self-hosting/multi-region.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/multi-region +> Description: Rivet Engine supports scaling transparently across multiple regions. + +--- +Documentation coming soon + +_Source doc path: /docs/self-hosting/multi-region_ diff --git a/.agents/skills/chat-room/reference/self-hosting/postgres.md b/.agents/skills/chat-room/reference/self-hosting/postgres.md new file mode 100644 index 0000000..e935246 --- /dev/null +++ b/.agents/skills/chat-room/reference/self-hosting/postgres.md @@ -0,0 +1,192 @@ +# PostgreSQL + +> Source: `src/content/docs/self-hosting/postgres.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/postgres +> Description: Configure PostgreSQL for self-hosted Rivet deployments. + +--- +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Basic Configuration + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://user:password@host:5432/database" + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://user:password@host:5432/database" +``` + +## Managed Postgres Compatibility + +Some hosted PostgreSQL platforms require additional configuration due to platform-specific restrictions. + +### PlanetScale + +Use direct connection (not connection pooler). + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://pscale_api_.:@.pg.psdb.cloud:5432/postgres?sslmode=require", + "unstable_disable_lock_customization": true + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://pscale_api_.:@.pg.psdb.cloud:5432/postgres?sslmode=require" +RIVET__database__postgres__unstable_disable_lock_customization=true +``` + +### Supabase + +Use direct connection on port `5432` (not connection pooler). + +#### Without SSL + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=disable", + "unstable_disable_lock_customization": true + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=disable" +RIVET__database__postgres__unstable_disable_lock_customization=true +``` + +#### With SSL + +Download the root certificate from your Supabase dashboard and specify its path. See [Supabase SSL Enforcement](https://supabase.com/docs/guides/platform/ssl-enforcement) for details. + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=require", + "unstable_disable_lock_customization": true, + "ssl": { + "root_cert_path": "/path/to/supabase-ca.crt" + } + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=require" +RIVET__database__postgres__unstable_disable_lock_customization=true +RIVET__database__postgres__ssl__root_cert_path="/path/to/supabase-ca.crt" +``` + +## SSL/TLS Support + +To enable SSL for Postgres, add `sslmode=require` to your PostgreSQL connection URL: + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://user:password@host.example.com:5432/database?sslmode=require" + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://user:password@host.example.com:5432/database?sslmode=require" +``` + +The `sslmode` parameter controls TLS usage: + +- `disable`: Do not use TLS +- `prefer`: Use TLS if available, otherwise connect without TLS (default) +- `require`: Require TLS connection (fails if TLS is not available) + +To verify the server certificate against a CA or verify the hostname, use custom SSL certificates (see below). + +### Custom SSL Certificates + +For databases using custom certificate authorities (e.g., Supabase) or requiring client certificate authentication, you can specify certificate paths in the configuration: + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://user:password@host:5432/database?sslmode=require", + "ssl": { + "root_cert_path": "/path/to/root-ca.crt", + "client_cert_path": "/path/to/client.crt", + "client_key_path": "/path/to/client.key" + } + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://user:password@host:5432/database?sslmode=require" +RIVET__database__postgres__ssl__root_cert_path="/path/to/root-ca.crt" +RIVET__database__postgres__ssl__client_cert_path="/path/to/client.crt" +RIVET__database__postgres__ssl__client_key_path="/path/to/client.key" +``` + +| Parameter | Description | PostgreSQL Equivalent | +|-----------|-------------|----------------------| +| `root_cert_path` | Path to the root certificate file for verifying the server's certificate | `sslrootcert` | +| `client_cert_path` | Path to the client certificate file for client certificate authentication | `sslcert` | +| `client_key_path` | Path to the client private key file for client certificate authentication | `sslkey` | + +All SSL paths are optional. If not specified, Rivet uses the default system root certificates from Mozilla's root certificate store. + +## Do Not Use Connection Poolers + +Rivet requires direct PostgreSQL connections for session-level features and does not support connection poolers. + +Do not use: + +- PgBouncer +- Supavisor +- AWS RDS Proxy + +## Troubleshooting + +### Permission Denied Errors + +If you see errors like: + +``` +ERROR: permission denied to set parameter "deadlock_timeout" +ERROR: current transaction is aborted, commands ignored until end of transaction block +``` + +Add `unstable_disable_lock_customization: true` to your configuration: + +```json +{ + "database": { + "postgres": { + "url": "postgresql://...", + "unstable_disable_lock_customization": true + } + } +} +``` + +This disables Rivet's attempt to set `lock_timeout = 0` and `deadlock_timeout = 10ms`. Since `lock_timeout` defaults to `0` in PostgreSQL, skipping these settings is safe. Deadlock detection will use the default `1s` timeout instead of `10ms`. + +_Source doc path: /docs/self-hosting/postgres_ diff --git a/.agents/skills/chat-room/reference/self-hosting/production-checklist.md b/.agents/skills/chat-room/reference/self-hosting/production-checklist.md new file mode 100644 index 0000000..3cefa5a --- /dev/null +++ b/.agents/skills/chat-room/reference/self-hosting/production-checklist.md @@ -0,0 +1,53 @@ +# Production Checklist + +> Source: `src/content/docs/self-hosting/production-checklist.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/production-checklist +> Description: Checklist for deploying a self-hosted Rivet Engine to production. + +--- +We recommend passing this page to your coding agent to verify your configuration before deploying. + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +Also review the [general production checklist](/docs/general/production-checklist). + +## Security + +- **Validate that you have an admin token configured.** Generate a strong, random token for engine authentication. See [Configuration](/docs/self-hosting/configuration). +- **Verify your admin token is not exposed publicly.** Do not include the admin token in `RIVET_PUBLIC_ENDPOINT` or anywhere accessible to clients. See [Endpoints](/docs/general/endpoints#public-endpoint). +- **Configure TLS termination.** Ensure connections to the engine are encrypted via a reverse proxy or load balancer. + +## Resources + +- **Set container resource limits.** Recommended at least 1 CPU and 2 GB of RAM per Rivet Engine instance. +- **Configure health checks.** Set up liveness and readiness probes on port `6421` at `/health`. Recommended timeout of 5 seconds. + +## Scaling + +- **Configure autoscaling for the Rivet Engine.** Set target CPU utilization to 70% and memory to 80% to ensure headroom for traffic spikes. In Kubernetes, this is configured via a Horizontal Pod Autoscaler (HPA). +- **Use 2+ engine nodes for redundancy.** Running a single engine node is a single point of failure. Deploy at least two engine instances behind a load balancer. +- **RocksDB only supports a single node.** Do not run multiple RocksDB nodes. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). For multi-node deployments, PostgreSQL is the recommended backend today, though it remains experimental as we evaluate the best fit for scalability and performance. +- **Validate the rate limit on your serverless actor host.** Actor start requests are sent from your engine instances, so they all originate from a small set of IPs. Per-IP rate limits on the actor host will throttle the engine before they would throttle end-user traffic. Size the limit to your peak actor create and wake rate, and configure platform max concurrency (e.g. on GCP Cloud Run) to match your expected concurrent actor count. + +## PostgreSQL + +- **PostgreSQL is recommended for multi-node deployments, but remains experimental.** Validate the deployment carefully before rollout. +- **Configure automated backups.** Set up regular backups for your PostgreSQL database to prevent data loss. +- **Configure failover.** Set up a standby replica with automatic failover to ensure high availability. +- **Use FoundationDB for the most scalable production-ready deployments.** FoundationDB provides the best performance, scalability, and uptime for Rivet. Contact [enterprise support](https://rivet.dev/sales) for FoundationDB guidance. + +## NATS + +- **Use NATS for pub/sub (recommended).** By default, Rivet uses PostgreSQL `LISTEN`/`NOTIFY` for pub/sub which has limited throughput. NATS significantly improves performance for high-traffic deployments. This is not needed if using RocksDB. See [Configuration](/docs/self-hosting/configuration). +- **Deploy 2+ NATS replicas.** Run at least two NATS replicas for high availability. + +## Monitoring + +- **Configure OpenTelemetry.** The Rivet Engine supports exporting traces and metrics via OpenTelemetry. Set `RIVET_OTEL_ENABLED=1` and `RIVET_OTEL_GRPC_ENDPOINT` to your collector endpoint (defaults to `http://localhost:4317`). Adjust `RIVET_OTEL_SAMPLER_RATIO` to control trace sampling (defaults to `0.001`). See [Configuration](/docs/self-hosting/configuration). +- **Set up alerts for critical metrics.** Monitor engine CPU, memory, request latency, and error rates. Configure alerts to notify your team before issues become outages. + +## Enterprise + +- **Contact [enterprise support](https://rivet.dev/sales) for production-ready deployments.** We can help with architecture review, scaling guidance, and FoundationDB support. + +_Source doc path: /docs/self-hosting/production-checklist_ diff --git a/.agents/skills/chat-room/reference/self-hosting/railway.md b/.agents/skills/chat-room/reference/self-hosting/railway.md new file mode 100644 index 0000000..c4bb922 --- /dev/null +++ b/.agents/skills/chat-room/reference/self-hosting/railway.md @@ -0,0 +1,99 @@ +# Railway Deployment + +> Source: `src/content/docs/self-hosting/railway.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/railway +> Description: Railway provides a simple platform for deploying Rivet Engine with automatic scaling and managed infrastructure. + +--- +## Video Tutorial + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Quick Deploy + +Choose the template that best fits your needs: + +| **Rivet Template** | **Rivet Starter** | +|-------------------|-------------------| +| [![Deploy on Railway](https://railway.com/button.svg)](https://railway.com/deploy/rivet?referralCode=RC7bza&utm_medium=integration&utm_source=template&utm_campaign=generic) | [![Deploy Rivet Starter](https://railway.com/button.svg)](https://railway.com/deploy/rivet-starter) | +| **Blank template** to start fresh | **Complete example** with chat app | +| - Rivet Engine | - Pre-configured Rivet Engine | +| - PostgreSQL database | - Example chat application with Actors | +| - Basic configuration | - PostgreSQL database | +| - Manual setup required | - Rivet Inspector for debugging | +| | - Ready to run immediately | + +You can also use the [Rivet Railway template](https://github.com/rivet-dev/template-railway) as a starting point for your application. + +After deploying either template, you can find the `RIVET__AUTH__ADMIN_TOKEN` under the **Variables** tab in the Railway dashboard. This token is required to access the Rivet Inspector. + +## Manual Deployment + +### Prerequisites + +1. [Railway account](https://railway.app) +2. [Railway CLI](https://docs.railway.app/develop/cli) (optional) + +### Step 1: Create New Project + +```bash +# Using Railway CLI +railway init + +# Or create via dashboard +# https://railway.app/new +``` + +### Step 2: Add Services + +#### Deploy PostgreSQL Database + +1. Click "New Service" → "Database" → "PostgreSQL" +2. Railway automatically provisions and configures PostgreSQL +3. Note the connection string from the service variables + +#### Deploy Rivet Engine + +1. Click "New Service" → "Docker Image" +2. Set image: `rivetdev/engine:latest` +3. Configure environment variables: + - `RIVET__POSTGRES__URL=${{Postgres.DATABASE_URL}}` +4. Configure graceful shutdown (see [Graceful Shutdown](#graceful-shutdown) below) + +### Step 3: Deploy Your Application + +Follow the [Railway Quick Start guide](https://docs.railway.com/quick-start) to deploy your repository: + +1. Connect your GitHub account to Railway +2. Select your repository containing your Rivet application +3. Railway will automatically detect and deploy your application +4. Configure environment variables for your application: + - `RIVET_ENDPOINT=${{Rivet.RAILWAY_PRIVATE_DOMAIN}}` - Points to the Rivet Engine service's private domain + +## WebSocket Timeouts + +Rivet uses long-lived WebSocket connections for both client traffic (browsers, SDKs) and envoy traffic (actor hosts connecting back to the engine). Railway's HTTP proxy supports WebSockets, but you must make sure no app-side timeout cuts them off. + +If you front the engine with your own reverse proxy (NGINX, Caddy, etc.) inside the Railway service, raise its idle / read timeout to at least 1 hour (`3600` seconds). The same guidance applies to the Railway service hosting your RivetKit app, since envoys connect to it over WebSocket. + +## Graceful Shutdown + +By default, Railway kills the old deploy 0 seconds after sending `SIGTERM` (see [Railway's docs](https://docs.railway.com/deployments/reference#singleton-deploys)), so in-flight requests are dropped and state flushes can be interrupted on every deploy. Rivet ships with a `SIGTERM` handler that drains cleanly, but it only gets to run if Railway is configured to give it time. + +Configure the following under **Settings → Deploy** on your service: + +- **Draining seconds** — the grace window between `SIGTERM` and `SIGKILL`. This is how long Rivet has to finish in-flight work and flush state. See [Railway's deployment teardown docs](https://docs.railway.com/deployments/deployment-teardown). + +Set draining seconds in the dashboard, via `drainingSeconds` in config-as-code, or via the `RAILWAY_DEPLOYMENT_DRAINING_SECONDS` service variable. A reasonable value is **60 seconds**. + +If your start command is a wrapper process (for example `npm start`, `yarn start`, `pnpm start`, or a shell script), the wrapper becomes PID 1 and swallows the signal — your app never drains and Railway force-kills it at the end of the window. + +- Invoke your binary directly as the start command (for example `node dist/index.js`, not `npm start`). +- Or run `dumb-init` / `tini` as PID 1 in your Dockerfile so signals forward to your process. + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/railway_ diff --git a/.agents/skills/chat-room/reference/self-hosting/render.md b/.agents/skills/chat-room/reference/self-hosting/render.md new file mode 100644 index 0000000..0bc6d6c --- /dev/null +++ b/.agents/skills/chat-room/reference/self-hosting/render.md @@ -0,0 +1,131 @@ +# Render Deployment + +> Source: `src/content/docs/self-hosting/render.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/render +> Description: Deploy Rivet Engine to Render with managed PostgreSQL and automatic HTTPS, using the experimental PostgreSQL backend. + +--- +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Prerequisites + +1. A [Render account](https://render.com) +2. A GitHub repository + +## Deploy Rivet Engine + + +### Create the Blueprint Files + + Add these three files to the root of your GitHub repository: + + **render.yaml** + + ```yaml + databases: + - name: rivet-db + plan: basic-256mb + databaseName: rivet + user: rivet + + services: + - type: web + name: rivet-engine + runtime: docker + dockerfilePath: ./Dockerfile.render + plan: starter + healthCheckPath: /health + envVars: + - key: DATABASE_URL + fromDatabase: + name: rivet-db + property: connectionString + - key: RIVET__AUTH__ADMIN_TOKEN + generateValue: true + ``` + + **Dockerfile.render** + + ```dockerfile + FROM rivetdev/engine:latest + + COPY entrypoint.render.sh /entrypoint.render.sh + RUN chmod +x /entrypoint.render.sh + + ENTRYPOINT ["/entrypoint.render.sh"] + ``` + + **entrypoint.render.sh** + + ```bash + #!/bin/sh + + if [ -n "$DATABASE_URL" ]; then + export RIVET__POSTGRES__URL="${DATABASE_URL}?sslmode=disable" + fi + + exec /usr/bin/rivet-engine start + ``` + + Commit and push these files to your repository. + + + +### Deploy to Render + + 1. Go to the [Render Dashboard](https://dashboard.render.com/) + 2. Click **Blueprints** in the left sidebar + 3. Click **New Blueprint Instance** + 4. Connect your GitHub account if you haven't already + 5. Select the repository containing the files from the previous step + 6. Click **Apply** + + Render will automatically create the PostgreSQL database and deploy the Rivet Engine. + + + +### Get Your Admin Token + + 1. Once deployed, go to your **rivet-engine** service in the Render Dashboard + 2. Click the **Environment** tab + 3. Find `RIVET__AUTH__ADMIN_TOKEN` and click the eye icon to reveal the value + 4. Copy this token — you'll need it to access the dashboard + + + +### Access the Rivet Dashboard + + Open your service URL in a browser: + + ``` + https://rivet-engine-xxxx.onrender.com/ui/ + ``` + + Replace `rivet-engine-xxxx` with your actual service name from the Render Dashboard. + + Enter the admin token from the previous step to log in. + + +## WebSocket Timeouts + +Rivet uses long-lived WebSocket connections for both client traffic (browsers, SDKs) and envoy traffic (actor hosts connecting back to the engine). Render's HTTP proxy supports WebSockets, but its default idle timeout will close connections that have no traffic for too long. + +If you front the engine with your own reverse proxy (NGINX, Caddy, etc.) on Render, raise its idle / read timeout to at least 1 hour (`3600` seconds). The same guidance applies to the Render service hosting your RivetKit app, since envoys connect to it over WebSocket. + +## Connecting Your Application + +To connect a RivetKit application to your self-hosted engine, set these environment variables in your app: + +```bash +RIVET_ENDPOINT=https://:@rivet-engine-xxxx.onrender.com +RIVET_PUBLIC_ENDPOINT=https://@rivet-engine-xxxx.onrender.com +``` + +See the [Connect guide](/docs/deploy/custom) for more details on connecting your application. + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/render_ diff --git a/.agents/skills/chat-room/reference/self-hosting/tls.md b/.agents/skills/chat-room/reference/self-hosting/tls.md new file mode 100644 index 0000000..63573d2 --- /dev/null +++ b/.agents/skills/chat-room/reference/self-hosting/tls.md @@ -0,0 +1,22 @@ +# TLS & Certificates + +> Source: `src/content/docs/self-hosting/tls.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/tls +> Description: How Rivet validates TLS root certificates. + +--- +Public CAs (Let's Encrypt, AWS ACM, and so on) work out of the box. You only need to read this page if you're running behind a corporate or private CA. + +Rivet reads the operating system trust store (`/etc/ssl/certs` on Linux, Keychain on macOS, Schannel on Windows) for all outbound HTTPS. Operator-installed corporate CAs live there and are honored automatically. + +To trust a private CA inside the official `rivetdev/engine` image, extend it the standard Debian way: + +```dockerfile +FROM rivetdev/engine:latest +COPY my-corp-ca.crt /usr/local/share/ca-certificates/ +RUN update-ca-certificates +``` + +Rebuild and redeploy. The same approach works for any machine running a Rivet client: install the CA into the OS trust store and Rivet picks it up. + +_Source doc path: /docs/self-hosting/tls_ diff --git a/.agents/skills/cron-jobs/BASE_SKILL.md b/.agents/skills/cron-jobs/BASE_SKILL.md new file mode 100644 index 0000000..ca710ba --- /dev/null +++ b/.agents/skills/cron-jobs/BASE_SKILL.md @@ -0,0 +1,537 @@ +--- +name: "rivetkit" +description: "RivetKit backend and Rivet Actor runtime guidance. Use for building, modifying, debugging, or testing Rivet Actors, registries, serverless/runner modes, deployment, or actor-based workflows." +--- + +# Rivet Actors + +Build high-performance, long-lived, in-memory processes on Rivet's actor runtime. Use this skill whenever HTTP endpoints, databases, or queues no longer meet the requirements for AI agents, realtime collaboration, workflow orchestration, or geo-distributed data. + +## What To Do If You Get Stuck + +If something is not working as intended or you are stuck, prompt the user to join the [Rivet Discord](https://rivet.dev/discord) or file an issue on the [Rivet GitHub](https://github.com/rivet-dev/rivet) to report an issue and get help. + +Provide the user with a pre-generated report with: + +- Symptoms + - If this is happening in local dev, deployed, or both + - The error you're seeing + - Relevant source code related to this +- What you've tried to solve it +- Environment + - RivetKit version + - Runtime (Node, Bun, etc) including version + - If applicable, provider in use (e.g. Vercel, Railway, etc) + - If applicable, HTTP router in use (e.g. Hono, Express, Elysia) + +## Debugging Actors + +Use the inspector HTTP API to examine running actors. These endpoints are accessible through the gateway at `/gateway/{actor_id}/inspector/*`. Key endpoints: + +- `GET /inspector/summary` - full actor snapshot (state, connections, RPCs, queue) +- `GET /inspector/state` / `PATCH /inspector/state` - read/write actor state +- `GET /inspector/connections` - active connections +- `GET /inspector/rpcs` - available actions +- `POST /inspector/action/{name}` - execute an action with `{"args": [...]}` +- `POST /inspector/database/execute` - run SQL with `{"sql": "...", "args": [...]}` or `{"sql": "...", "properties": {...}}` for reads or mutations +- `GET /inspector/queue?limit=50` - queue status +- `GET /inspector/traces?startMs=0&endMs=...&limit=1000` - trace spans (OTLP JSON) +- `GET /inspector/workflow-history` - workflow history and status as JSON (`nameRegistry`, `entries`, `entryMetadata`) +- `POST /inspector/workflow/replay` - replay a workflow from a specific step or from the beginning; returns `409 actor/workflow_in_flight` if the workflow is still running +- `GET /inspector/database/schema` - SQLite tables and views exposed by `c.db` +- `GET /inspector/database/rows?table=...&limit=100&offset=0` - paged SQLite rows for a table or view + +In local dev, no auth token is needed. In production, pass `Authorization: Bearer `, where the inspector token is the actor-specific token auto-generated on first start and persisted in the actor's internal KV at key `0x03`. The Rivet dashboard retrieves this token automatically; for direct API access, fetch it through the management KV endpoint. See the [debugging docs](https://rivet.dev/docs/actors/debugging) for details. + +## Citing Sources + +When providing information from Rivet documentation, cite the canonical URL so users can learn more. Each reference file includes its canonical URL in the header metadata. + +**How to cite:** + +- Use inline links for key concepts: "Use [actor keys](https://rivet.dev/docs/actors/keys) to uniquely identify instances." +- Add a "Learn more" link after explanations for complex topics + +**Finding canonical URLs:** + +The Reference Map below links to reference files. Each file's header contains: + +``` +> Canonical URL: https://rivet.dev/docs/actors/actions +``` + +Use that canonical URL when citing, not the reference file path. + +**Examples:** + +- Actions → `https://rivet.dev/docs/actors/actions` +- React client → `https://rivet.dev/docs/clients/react` +- Self-hosting on Kubernetes → `https://rivet.dev/docs/self-hosting/kubernetes` + +## Version Check + +Before starting any work, check if the user's project is on the latest version of RivetKit (latest: 2.3.4). Look at the `rivetkit` version in the user's `package.json` (check both `dependencies` and `devDependencies`). If the installed version is older than 2.3.4, inform the user and suggest upgrading: + +```bash +npm install rivetkit@2.3.4 +``` + +If the user also uses `@rivetkit/react`, `@rivetkit/next-js`, or other `@rivetkit/*` client packages, suggest upgrading those too. Outdated versions may have known bugs or missing features that cause issues. + +## First Steps + +1. Install RivetKit (latest: 2.3.4) + ```bash + npm install rivetkit@2.3.4 + ``` +2. Define a registry with `setup({ use: { /* actors */ } })`. +3. Call `registry.start()` to start the server. For custom HTTP server integration, use `registry.handler()` with a router like Hono. For serverless deployments, use `registry.serve()`. For runner-only mode, use `registry.startEnvoy()`. +4. Verify `/api/rivet/metadata` returns 200 before deploying. +5. Configure Rivet Cloud or self-hosted engine + - You must configure versioning for production builds. This is not needed for local development. See [Versions & Upgrades](https://rivet.dev/docs/actors/versions). +6. Integrate clients (see client guides below for JavaScript, React, or Swift) +7. Prompt the user if they want to deploy. If so, go to Deploying Rivet Backends. + +For more information, read the quickstart guide relevant to the user's project. + +## Project Setup + +### .gitignore + +Every RivetKit project should have a `.gitignore`. Include at minimum: + +``` +node_modules/ +dist/ +.env +``` + +### .dockerignore + +Every project with a Dockerfile should have a `.dockerignore` to keep the image small and avoid leaking secrets: + +``` +node_modules/ +dist/ +.env +.git/ +``` + +### Dockerfile + +Use this as a base Dockerfile for deploying a RivetKit project. The `RIVET_RUNNER_VERSION` build arg is only needed when self-hosting or using a custom runner (not needed for Rivet Compute). It lets Rivet track which version of the actor is running and drain old actors on deploy. See https://rivet.dev/docs/actors/versions for details. + +```dockerfile +FROM node:24-alpine + +ARG RIVET_RUNNER_VERSION +ENV RIVET_RUNNER_VERSION=$RIVET_RUNNER_VERSION + +WORKDIR /app + +COPY package.json package-lock.json ./ +RUN npm ci + +COPY . . +RUN npm run build --if-present + +CMD ["node", "dist/index.js"] +``` + +Build with: + +```bash +docker build --build-arg RIVET_RUNNER_VERSION=$(date +%s) . +``` + +Adjust the `CMD` to match the project's entry point. If the project uses a different output directory or start command, update accordingly. + +## Error Handling Policy + +- Prefer fail-fast behavior by default. +- Avoid `try/catch` unless it is required for a real recovery path, cleanup boundary, or to add actionable context. +- Never swallow errors. If you add a `catch`, you must handle the error explicitly, at minimum by logging it. +- When you cannot recover, log context and rethrow. + +## State vs Vars: Persistence Rules + +**`c.vars` is ephemeral.** Data in `c.vars` is lost on every restart, crash, upgrade, or sleep/wake cycle. Only use `c.vars` for non-serializable objects (e.g., physics engines, WebSocket references, event emitters, caches) or truly transient runtime data (e.g., current input direction that doesn't matter after disconnect). + +**Persistent storage options.** Any data that must survive restarts belongs in one of these, NOT in `c.vars`: + +- **`c.state`** — CBOR-serializable data for small, bounded datasets. Ideal for configuration, counters, small player lists, phase flags, etc. Keep under 128 KB. Do not store unbounded or growing data here (e.g., chat logs, event histories, spawned entity lists that grow without limit). State is read/written as a single blob on every persistence cycle. +- **`c.kv`** — Key-value store for unbounded data. This is what `c.state` uses under the hood. Supports binary values. Use for larger or variable-size data like user inventories, world chunks, file blobs, or any collection that may grow over time. Keys are scoped to the actor instance. +- **`c.db`** — SQLite database for structured or complex data. Use when you need queries, indexes, joins, aggregations, or relational modeling. Ideal for leaderboards, match histories, player pools, or any data that benefits from SQL. + +**Common mistake:** Storing meaningful game/application data in `c.vars` instead of persisting it. For example, if users can spawn objects in a physics simulation, the spawn definitions (position, size, type) must be persisted in `c.state` (or `c.kv` if unbounded), even though the physics engine handles (non-serializable) live in `c.vars`. On restart, `run()` should recreate the runtime objects from the persisted data. + +## Deploying Rivet Backends + +Assume the user is deploying to Rivet Cloud, unless otherwise specified. If user is self-hosting, read the self-hosting guides below. + +1. Verify that Rivet Actors are working in local dev +2. Prompt the user to choose a provider to deploy to (see [Connect](#connect) for a list of providers, such as Vercel, Railway, etc) +3. Follow the deploy guide for that given provider. You will need to instruct the user when you need manual intervention. + +## API Reference + +The RivetKit OpenAPI specification is available in the skill directory at `openapi.json`. This file documents all HTTP endpoints for managing actors. + +## Misc Notes + +- The Rivet domain is rivet.dev, not rivet.gg + +## TypeScript Caveat: Actor Client Inference + +- In multi-file TypeScript projects, bidirectional actor calls can create a circular type dependency when both actors use `c.client()`. +- Symptoms usually include `c.state` becoming `unknown`, actor methods becoming possibly `undefined`, or `TS2322` / `TS2722` errors after the first cross-actor call. +- If an action returns the result of another actor call, prefer an explicit return type annotation on that action instead of relying on inference through `c.client()`. +- If explicit return types are not enough, use a narrower client or registry type for only the actors that action needs. +- As a last resort, pass `unknown` for the registry type and be explicit that this gives up type safety at that call site. + +## Features + +- **Long-Lived, Stateful Compute**: Each unit of compute is like a tiny server that remembers things between requests – no need to re-fetch data from a database or worry about timeouts. Like AWS Lambda, but with memory and no timeouts. +- **Blazing-Fast Reads & Writes**: State is stored on the same machine as your compute, so reads and writes are ultra-fast. No database round trips, no latency spikes. State is persisted to Rivet for long term storage, so it survives server restarts. +- **Realtime**: Update state and broadcast changes in realtime with WebSockets. No external pub/sub systems, no polling – just built-in low-latency events. +- **Infinitely Scalable**: Automatically scale from zero to millions of concurrent actors. Pay only for what you use with instant scaling and no cold starts. +- **Fault Tolerant**: Built-in error handling and recovery. Actors automatically restart on failure while preserving state integrity and continuing operations. + +## When to Use Rivet Actors + +- **AI agents & sandboxes**: multi-step toolchains, conversation memory, sandbox orchestration. +- **Multiplayer or collaborative apps**: CRDT docs, shared cursors, realtime dashboards, chat. +- **Workflow automation**: background jobs, cron, rate limiters, durable queues, backpressure control. +- **Data-intensive backends**: geo-distributed or per-tenant databases, in-memory caches, sharded SQL. +- **Networking workloads**: WebSocket servers, custom protocols, local-first sync, edge fanout. + +## Minimal Project + +### Backend + +**index.ts** + +### Client Docs + +Use the client SDK that matches your app: + +- [JavaScript Client](/docs/clients/javascript) +- [React Client](/docs/clients/react) +- [Swift Client](/docs/clients/swift) + +## Actor Quick Reference + +### In-Memory State + +Persistent data that survives restarts, crashes, and deployments. State is persisted on Rivet Cloud or Rivet self-hosted, so it survives restarts if the current process crashes or exits. + +### Static Initial State + +### Dynamic Initial State + +[Documentation](/docs/actors/state) + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +[Documentation](/docs/actors/keys) + +### Input + +Pass initialization data when creating actors. Input is only available in `createState` and `onCreate`, so store it in state if you need it later. + +[Documentation](/docs/actors/input) + +### Temporary Variables + +Temporary data that doesn't survive restarts. Use for non-serializable objects (event emitters, connections, etc). + +### Static Initial Vars + +### Dynamic Initial Vars + +[Documentation](/docs/actors/state) + +### Actions + +Actions are the primary way clients and other actors communicate with an actor. + +[Documentation](/docs/actors/actions) + +### Events & Broadcasts + +Events enable real-time communication from actors to connected clients. + +[Documentation](/docs/actors/events) + +### Connections + +Access the current connection via `c.conn` or all connected clients via `c.conns`. Use `c.conn.id` or `c.conn.state` to securely identify who is calling an action. `c.conn` is only available for actions invoked through a connected client; stateless actor-handle calls run without a connection, so guard against that. Connection state is initialized via `connState` or `createConnState`, which receives parameters passed by the client on connect. + +### Static Connection Initial State + +### Dynamic Connection Initial State + +[Documentation](/docs/actors/connections) + +### Queues + +Use queues to process durable messages in order inside a `run` loop. + +[Documentation](/docs/actors/queues) + +### Workflows + +Use workflows when your `run` logic needs durable, replayable multi-step execution. + +[Documentation](/docs/actors/workflows) + +### Actor-to-Actor Communication + +Actors can call other actors using `c.client()`. + +[Documentation](/docs/actors/communicating-between-actors) + +### Scheduling + +Schedule actions to run after a delay or at a specific time. Schedules persist across restarts, upgrades, and crashes. + +[Documentation](/docs/actors/schedule) + +### Destroying Actors + +Permanently delete an actor and its state using `c.destroy()`. + +[Documentation](/docs/actors/destroy) + +### Lifecycle Hooks + +Actors support hooks for initialization, background processing, connections, networking, and state changes. Use `run` for long-lived background loops, and use `c.aborted` or `c.abortSignal` for graceful shutdown. + +[Documentation](/docs/actors/lifecycle) + +### Context Types + +When writing helper functions outside the actor definition, use `*ContextOf` to extract the correct context type. Helpers like `ActionContextOf`, `CreateContextOf`, `ConnContextOf`, and `ConnInitContextOf` are exported from `"rivetkit"`. Do not manually define your own context interface. Always derive it from the actor definition. + +[Documentation](/docs/actors/types) + +### Errors + +Use `UserError` to throw errors that are safely returned to clients. Pass `metadata` to include structured data. Other errors are converted to generic "internal error" for security. + +### Actor + +### Client + +[Documentation](/docs/actors/errors) + +### Low-Level HTTP & WebSocket Handlers + +For custom protocols or integrating libraries that need direct access to HTTP `Request`/`Response` or WebSocket connections, use `onRequest` and `onWebSocket`. + +[HTTP Handler Documentation](/docs/actors/request-handler) · [WebSocket Handler Documentation](/docs/actors/websocket-handler) + +### Icons & Names + +Customize how actors appear in the UI with display names and icons. It's recommended to always provide a name and icon to actors in order to make them easier to distinguish in the dashboard. + +```typescript +import { actor } from "rivetkit"; + +const chatRoom = actor({ + options: { + name: "Chat Room", + icon: "💬", // or FontAwesome: "comments", "chart-line", etc. + }, + // ... +}); +``` + +[Documentation](/docs/actors/appearance) + +## Client Documentation + +Find the full client guides here: + +- [JavaScript Client](/docs/clients/javascript) +- [React Client](/docs/clients/react) +- [Swift Client](/docs/clients/swift) + +## Common Patterns + +Actors scale naturally through isolated state and message-passing. Structure your applications with these patterns: + +[Documentation](/docs/actors/design-patterns) + +### Actor Per Entity + +Create one actor per user, document, or room. Use compound keys to scope entities: + +### Coordinator & Data Actors + +**Data actors** handle core logic (chat rooms, game sessions, user data). **Coordinator actors** track and manage collections of data actors—think of them as an index. + +### Run Loop + +Use a `run` loop for continuous background work inside an actor. Process queue messages in order, run logic on intervals, stream AI responses, or coordinate long-running tasks. + +### Workflow Loop + +Use this pattern for long-lived, durable workflows that initialize resources, process commands in a loop, then clean up. + +[Documentation](/docs/actors/workflows) + +### Actions vs Queues + +- **Actions** are not durable. Use them for realtime reads, ephemeral data, and low-latency communication like player input. +- **Queues** are durable. Use them to serialize mutations through the run loop, avoiding race conditions with SQLite and other local state. Callers can still wait for a response from queued work. + +### Authentication, Security, & CORS + +- Validate credentials in `onBeforeConnect` or `createConnState` and throw an error to reject unauthorized connections. +- Use `c.conn.state` to securely identify users in actions rather than trusting action parameters. +- For cross-origin access, validate the request origin in `onBeforeConnect`. + +[Authentication Documentation](/docs/actors/authentication) · [CORS Documentation](/docs/general/cors) + +### Versions & Upgrades + +When deploying new code, set a version number so Rivet can route new actors to the latest runner and optionally drain old ones. Use a build timestamp, git commit count, or CI build number as the version. It is very important to [configure versioning](/docs/actors/versions) before deploying to production. Without versioning, actors can regress by running on older runner versions, and existing actors will never be forced to migrate to new runners. They will continue running indefinitely on the old runners until they exit. + +[Documentation](/docs/actors/versions) + +### Anti-Patterns + +#### Never build a "god" actor + +Do not put all your logic in a single actor. A god actor serializes every operation through one bottleneck, kills parallelism, and makes the entire system fail as a unit. Split into focused actors per entity. + +#### Never create an actor per request + +Actors are long-lived and maintain state across requests. Creating a new actor for every incoming request throws away the core benefit of the model and wastes resources on actor creation and teardown. Use actors for persistent entities and regular functions for stateless work. + +## Reference Map + +### Actors + +- [Access Control](reference/actors/access-control.md) +- [Actions](reference/actors/actions.md) +- [Actor Keys](reference/actors/keys.md) +- [Actor Runtime Socket](reference/actors/actor-runtime-socket.md) +- [Actor Scheduling](reference/actors/schedule.md) +- [Actor Statuses](reference/actors/statuses.md) +- [Authentication](reference/actors/authentication.md) +- [Cloudflare Workers Quickstart](reference/actors/quickstart/cloudflare.md) +- [Communicating Between Actors](reference/actors/communicating-between-actors.md) +- [Connections](reference/actors/connections.md) +- [Custom Inspector Tabs](reference/actors/inspector-tabs.md) +- [Debugging](reference/actors/debugging.md) +- [Design Patterns](reference/actors/design-patterns.md) +- [Destroying Actors](reference/actors/destroy.md) +- [Effect.ts Quickstart (Beta)](reference/actors/quickstart/effect.md) +- [Errors](reference/actors/errors.md) +- [Fetch and WebSocket Handler](reference/actors/fetch-and-websocket-handler.md) +- [Helper Types](reference/actors/helper-types.md) +- [Icons & Names](reference/actors/appearance.md) +- [In-Memory State](reference/actors/state.md) +- [Input Parameters](reference/actors/input.md) +- [Lifecycle](reference/actors/lifecycle.md) +- [Limits](reference/actors/limits.md) +- [Low-Level HTTP Request Handler](reference/actors/request-handler.md) +- [Low-Level KV Storage](reference/actors/kv.md) +- [Low-Level WebSocket Handler](reference/actors/websocket-handler.md) +- [Metadata](reference/actors/metadata.md) +- [Next.js Quickstart](reference/actors/quickstart/next-js.md) +- [Node.js & Bun Quickstart](reference/actors/quickstart/backend.md) +- [Queues & Run Loops](reference/actors/queues.md) +- [React Quickstart](reference/actors/quickstart/react.md) +- [Realtime](reference/actors/events.md) +- [Rust Quickstart (Beta)](reference/actors/quickstart/rust.md) +- [Scaling & Concurrency](reference/actors/scaling.md) +- [Sharing and Joining State](reference/actors/sharing-and-joining-state.md) +- [SQLite](reference/actors/sqlite.md) +- [SQLite + Drizzle](reference/actors/sqlite-drizzle.md) +- [Supabase Functions Quickstart](reference/actors/quickstart/supabase.md) +- [Testing](reference/actors/testing.md) +- [Troubleshooting](reference/actors/troubleshooting.md) +- [Types](reference/actors/types.md) +- [Vanilla HTTP API](reference/actors/http-api.md) +- [Versions & Upgrades](reference/actors/versions.md) +- [Workflows](reference/actors/workflows.md) + +### Cli + +- [CLI](reference/cli.md) + +### Clients + +- [Node.js & Bun](reference/clients/javascript.md) +- [React](reference/clients/react.md) +- [Rust (Beta)](reference/clients/rust.md) +- [Swift](reference/clients/swift.md) +- [SwiftUI](reference/clients/swiftui.md) + +### Cookbook + +- [AI Agent](reference/cookbook/ai-agent.md) +- [Chat Room](reference/cookbook/chat-room.md) +- [Collaborative Text Editor](reference/cookbook/collaborative-text-editor.md) +- [Cron Jobs and Scheduled Tasks](reference/cookbook/cron-jobs.md) +- [Database per Tenant](reference/cookbook/per-tenant-database.md) +- [Deploying Rivet in a VPC or Air-Gapped Network](reference/cookbook/vpc-air-gapped.md) +- [Live Cursors and Presence](reference/cookbook/live-cursors.md) +- [Multiplayer Game](reference/cookbook/multiplayer-game.md) + +### Deploy + +- [Container Runner](reference/deploy/container-runner.md) +- [Deploy To Amazon Web Services Lambda](reference/deploy/aws-lambda.md) +- [Deploying to AWS ECS](reference/deploy/aws-ecs.md) +- [Deploying to Cloudflare Workers](reference/deploy/cloudflare.md) +- [Deploying to Freestyle](reference/deploy/freestyle.md) +- [Deploying to Google Cloud Run](reference/deploy/gcp-cloud-run.md) +- [Deploying to Hetzner](reference/deploy/hetzner.md) +- [Deploying to Kubernetes](reference/deploy/kubernetes.md) +- [Deploying to Railway](reference/deploy/railway.md) +- [Deploying to Rivet Compute](reference/deploy/rivet-compute.md) +- [Deploying to Supabase Functions](reference/deploy/supabase.md) +- [Deploying to Vercel](reference/deploy/vercel.md) +- [Deploying to VMs & Bare Metal](reference/deploy/vm-and-bare-metal.md) + +### General + +- [Actor Configuration](reference/general/actor-configuration.md) +- [Architecture](reference/general/architecture.md) +- [Cross-Origin Resource Sharing](reference/general/cors.md) +- [Documentation for LLMs & AI](reference/general/docs-for-llms.md) +- [Edge Networking](reference/general/edge.md) +- [Endpoints](reference/general/endpoints.md) +- [Environment Variables](reference/general/environment-variables.md) +- [HTTP Server](reference/general/http-server.md) +- [Logging](reference/general/logging.md) +- [Pool Configuration](reference/general/pool-configuration.md) +- [Production Checklist](reference/general/production-checklist.md) +- [Registry Configuration](reference/general/registry-configuration.md) +- [Runtime Modes](reference/general/runtime-modes.md) +- [WASM vs Native SDK](reference/general/wasm-vs-native-sdk.md) + +### Self Hosting + +- [Configuration](reference/self-hosting/configuration.md) +- [Docker Compose](reference/self-hosting/docker-compose.md) +- [Docker Container](reference/self-hosting/docker-container.md) +- [File System](reference/self-hosting/filesystem.md) +- [FoundationDB (Enterprise)](reference/self-hosting/foundationdb.md) +- [Installing Rivet Engine](reference/self-hosting/install.md) +- [Kubernetes](reference/self-hosting/kubernetes.md) +- [Multi-Region](reference/self-hosting/multi-region.md) +- [PostgreSQL](reference/self-hosting/postgres.md) +- [Production Checklist](reference/self-hosting/production-checklist.md) +- [Railway Deployment](reference/self-hosting/railway.md) +- [Render Deployment](reference/self-hosting/render.md) +- [TLS & Certificates](reference/self-hosting/tls.md) + diff --git a/.agents/skills/cron-jobs/SKILL.md b/.agents/skills/cron-jobs/SKILL.md new file mode 100644 index 0000000..430066f --- /dev/null +++ b/.agents/skills/cron-jobs/SKILL.md @@ -0,0 +1,252 @@ +--- +name: "cron-jobs" +description: "Durable cron jobs with Rivet Actors: schedule.after and schedule.at timers survive restarts and crashes, plus re-arming recurring jobs and idempotent handlers." +--- + +# Cron Jobs and Scheduled Tasks + +**IMPORTANT: Before doing anything, you MUST read `BASE_SKILL.md` in this skill's directory. It contains essential guidance on debugging, error handling, state management, deployment, and project setup. Those rules and patterns apply to all RivetKit work. Everything below assumes you have already read and understood it.** + +## Working Examples + +If you need a reference implementation, read the raw working example code in these templates: + +- [scheduling](https://github.com/rivet-dev/rivet/tree/main/examples/scheduling) + + +Patterns for running durable cron jobs and scheduled tasks on Rivet Actors. Actor schedules are persistent timers owned by the engine, so a job keeps its deadline through actor sleep, restarts, upgrades, deploys, and crashes. + +## Starter Code + +Start from the working [Scheduling example on GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/scheduling). It implements a reminder service with one-shot timers, a React frontend, and live trigger events. + +## The Scheduling API + +The full API is documented in [Scheduling](/docs/actors/schedule). There are two methods, both available on the actor context: + +| Method | Behavior | +| --- | --- | +| `c.schedule.after(duration, actionName, ...args)` | Runs the named action after `duration` milliseconds. | +| `c.schedule.at(timestamp, actionName, ...args)` | Runs the named action at an exact epoch timestamp in milliseconds. | + +Key properties: + +- **Durable**: The schedule is persisted by the engine and the timer survives actor sleep, restart, upgrade, and crash. If the actor is asleep at the deadline, the engine wakes it to run the action. See [Lifecycle](/docs/actors/lifecycle). +- **Plain actions as callbacks**: The scheduled callback is an ordinary [action](/docs/actors/actions) on the same actor, invoked by name. Arguments after the action name are forwarded positionally, for example `c.schedule.after(delayMs, "triggerReminder", reminder.id)`. +- **No cancellation API**: Rivet does not currently support canceling a scheduled action. The pattern is a tombstone guard: remove the entry from [state](/docs/actors/state) and have the scheduled action no-op when it cannot find its entry. The example's `cancelReminder` and `triggerReminder` actions implement exactly this. + +## Recurring Jobs Via Re-Arm + +`c.schedule` is one-shot, so recurring jobs are built by having the scheduled action re-arm itself at the end of each run: + +Arm the first run from `onCreate` or a setup action; after that, the action keeps the chain alive by rescheduling itself. + +Re-arming with `after` measures the next run from the end of the current one, so the cadence drifts later by the job's runtime on every cycle. If runs must stay aligned to a fixed cadence, re-arm with `c.schedule.at(c.state.lastRunAt + DAY_MS, "runReport")` instead. + +The Scheduling example itself only uses one-shot reminders. A real re-arm implementation lives in the [idle world actor](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/idle/), where the `collectProduction` action credits production, updates `lastCollectedAt`, and calls a `scheduleCollection` helper that re-arms with `c.schedule.after(delayMs, "collectProduction", { buildingId })`. It also shows catch-up handling: if the action runs late, it computes how many whole intervals elapsed since the last run and credits them in one batch before re-arming. + +For multi-step jobs that need retries and progress tracking inside a single run, consider [Workflows](/docs/actors/workflows) instead of chaining schedules. + +## Durability Comparison + +| Approach | Timer Durability | Horizontal Scaling | Deploys And Restarts | +| --- | --- | --- | --- | +| `setTimeout` / `setInterval` | In-process memory only | Every replica arms its own timer, so jobs run once per instance | All pending timers are lost on restart or crash | +| `node-cron` and similar libraries | In-process memory only | Every instance runs the job unless you add external locking | Schedule resets on deploy; runs missed during downtime are skipped | +| External cron service | Lives outside your app | Needs a public HTTP endpoint plus its own dedupe and retry state | Survives your deploys but is separate infrastructure to operate | +| Rivet Actor scheduling | Persisted by the engine as a durable timer | Exactly one actor per key, so the timer is armed once rather than once per replica | Survives actor sleep, restart, upgrade, and crash | + +## Idempotency + +A scheduled action can fire more than you expect: a crash between doing the work and re-arming can cause the action to run again, and because schedules cannot be cancelled, an action can fire for an entry that was already removed. Design handlers so a duplicate firing is harmless: + +- **Store a run marker in state**: Keep a `lastRunAt` timestamp or a sequence number in actor state and update it inside the action. On each firing, compute elapsed time since the marker and skip or batch accordingly. The idle world actor's `collectProduction` does this with `lastCollectedAt` and whole-interval batching. +- **Tombstone guard for cancelled entries**: The example's `triggerReminder` looks the reminder up in `c.state.reminders` first and returns with a warning if it is gone, so a fire-after-cancel is a safe no-op. +- **Keep work and marker updates in the same action**: Actor state writes are persisted with the action, so updating the marker in the same handler that does the work keeps the two consistent. + +## Topology + +| Topology | Use When | Example Key | +| --- | --- | --- | +| Singleton job actor | One global job such as a nightly report or cleanup pass | `job["daily-report"]` | +| Actor per scheduled entity | Per-user or per-resource timers such as reminders, trials, or billing periods | `reminder[userId]` | + +The Scheduling example uses a single shared `reminderActor["main"]` key for demo simplicity. For production reminder systems, prefer one actor per user so timers, state, and load are isolated per entity. See [Keys](/docs/actors/keys). + +## Reminder Service Example + +| Topic | Summary | +| --- | --- | +| Scheduling | One-shot timers armed with `c.schedule.after(delayMs, "triggerReminder", reminder.id)` or `c.schedule.at(timestamp, "triggerReminder", reminder.id)`. | +| State | JSON state holding `reminders` and `completedCount`; the scheduled action mutates state when it fires. | +| Events | `triggerReminder` broadcasts a `reminderTriggered` event to all connected clients. See [Events](/docs/actors/events). | +| Cancellation | `cancelReminder` only removes the reminder from state; the scheduled action may still fire and no-ops via a state lookup guard. | + +**Actors** + +- **Key**: `reminderActor["main"]` +- **Responsibility**: Stores reminders in persistent state, arms a future self-action per reminder via `c.schedule`, marks reminders completed when the scheduled action fires, and broadcasts `reminderTriggered` to connected clients. +- **Actions** + - `scheduleReminder` + - `scheduleReminderAt` + - `triggerReminder` + - `getReminders` + - `cancelReminder` + - `getStats` +- **Queues** + - None +- **State** + - JSON + - `reminders` + - `completedCount` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant R as reminderActor + participant E as Engine + + C->>R: scheduleReminder(message, delayMs) + R->>E: schedule.after(delayMs, triggerReminder, id) + Note over E: schedule persisted + alarm armed + R-->>C: reminder + Note over R: actor sleeps + E->>R: alarm fires, actor wakes + Note over R: triggerReminder(id) runs + R-->>C: reminderTriggered event + Note over R: recurring jobs re-arm here with schedule.after +``` + +## Security Checklist + +The example is intentionally open: any client can connect to the shared `["main"]` key and schedule or cancel anything. Treat all of the following as required extensions for production: + +- **Validate schedule inputs**: Clamp `delayMs` and `timestamp` from clients. Reject negative delays, timestamps in the past, and absurdly far-future deadlines, and bound message or payload sizes. +- **Never schedule client-chosen actions**: Expose specific actions like `scheduleReminder` that internally arm a fixed callback. Do not pass a client-supplied action name or unchecked args into `c.schedule`. +- **Authenticate and scope keys**: Add connection [authentication](/docs/actors/authentication) and use per-user actor keys instead of one global key, so users cannot read or cancel each other's schedules. +- **Prune completed entries**: The example's `reminders` array grows without bound. Remove or archive completed entries so state stays small. +- **Use stable IDs**: Generate entry IDs with `crypto.randomUUID()` rather than timestamp-plus-random strings. + +## Reference Map + +### Actors + +- [Access Control](reference/actors/access-control.md) +- [Actions](reference/actors/actions.md) +- [Actor Keys](reference/actors/keys.md) +- [Actor Runtime Socket](reference/actors/actor-runtime-socket.md) +- [Actor Scheduling](reference/actors/schedule.md) +- [Actor Statuses](reference/actors/statuses.md) +- [Authentication](reference/actors/authentication.md) +- [Cloudflare Workers Quickstart](reference/actors/quickstart/cloudflare.md) +- [Communicating Between Actors](reference/actors/communicating-between-actors.md) +- [Connections](reference/actors/connections.md) +- [Custom Inspector Tabs](reference/actors/inspector-tabs.md) +- [Debugging](reference/actors/debugging.md) +- [Design Patterns](reference/actors/design-patterns.md) +- [Destroying Actors](reference/actors/destroy.md) +- [Effect.ts Quickstart (Beta)](reference/actors/quickstart/effect.md) +- [Errors](reference/actors/errors.md) +- [Fetch and WebSocket Handler](reference/actors/fetch-and-websocket-handler.md) +- [Helper Types](reference/actors/helper-types.md) +- [Icons & Names](reference/actors/appearance.md) +- [In-Memory State](reference/actors/state.md) +- [Input Parameters](reference/actors/input.md) +- [Lifecycle](reference/actors/lifecycle.md) +- [Limits](reference/actors/limits.md) +- [Low-Level HTTP Request Handler](reference/actors/request-handler.md) +- [Low-Level KV Storage](reference/actors/kv.md) +- [Low-Level WebSocket Handler](reference/actors/websocket-handler.md) +- [Metadata](reference/actors/metadata.md) +- [Next.js Quickstart](reference/actors/quickstart/next-js.md) +- [Node.js & Bun Quickstart](reference/actors/quickstart/backend.md) +- [Queues & Run Loops](reference/actors/queues.md) +- [React Quickstart](reference/actors/quickstart/react.md) +- [Realtime](reference/actors/events.md) +- [Rust Quickstart (Beta)](reference/actors/quickstart/rust.md) +- [Scaling & Concurrency](reference/actors/scaling.md) +- [Sharing and Joining State](reference/actors/sharing-and-joining-state.md) +- [SQLite](reference/actors/sqlite.md) +- [SQLite + Drizzle](reference/actors/sqlite-drizzle.md) +- [Supabase Functions Quickstart](reference/actors/quickstart/supabase.md) +- [Testing](reference/actors/testing.md) +- [Troubleshooting](reference/actors/troubleshooting.md) +- [Types](reference/actors/types.md) +- [Vanilla HTTP API](reference/actors/http-api.md) +- [Versions & Upgrades](reference/actors/versions.md) +- [Workflows](reference/actors/workflows.md) + +### Cli + +- [CLI](reference/cli.md) + +### Clients + +- [Node.js & Bun](reference/clients/javascript.md) +- [React](reference/clients/react.md) +- [Rust (Beta)](reference/clients/rust.md) +- [Swift](reference/clients/swift.md) +- [SwiftUI](reference/clients/swiftui.md) + +### Cookbook + +- [AI Agent](reference/cookbook/ai-agent.md) +- [Chat Room](reference/cookbook/chat-room.md) +- [Collaborative Text Editor](reference/cookbook/collaborative-text-editor.md) +- [Cron Jobs and Scheduled Tasks](reference/cookbook/cron-jobs.md) +- [Database per Tenant](reference/cookbook/per-tenant-database.md) +- [Deploying Rivet in a VPC or Air-Gapped Network](reference/cookbook/vpc-air-gapped.md) +- [Live Cursors and Presence](reference/cookbook/live-cursors.md) +- [Multiplayer Game](reference/cookbook/multiplayer-game.md) + +### Deploy + +- [Container Runner](reference/deploy/container-runner.md) +- [Deploy To Amazon Web Services Lambda](reference/deploy/aws-lambda.md) +- [Deploying to AWS ECS](reference/deploy/aws-ecs.md) +- [Deploying to Cloudflare Workers](reference/deploy/cloudflare.md) +- [Deploying to Freestyle](reference/deploy/freestyle.md) +- [Deploying to Google Cloud Run](reference/deploy/gcp-cloud-run.md) +- [Deploying to Hetzner](reference/deploy/hetzner.md) +- [Deploying to Kubernetes](reference/deploy/kubernetes.md) +- [Deploying to Railway](reference/deploy/railway.md) +- [Deploying to Rivet Compute](reference/deploy/rivet-compute.md) +- [Deploying to Supabase Functions](reference/deploy/supabase.md) +- [Deploying to Vercel](reference/deploy/vercel.md) +- [Deploying to VMs & Bare Metal](reference/deploy/vm-and-bare-metal.md) + +### General + +- [Actor Configuration](reference/general/actor-configuration.md) +- [Architecture](reference/general/architecture.md) +- [Cross-Origin Resource Sharing](reference/general/cors.md) +- [Documentation for LLMs & AI](reference/general/docs-for-llms.md) +- [Edge Networking](reference/general/edge.md) +- [Endpoints](reference/general/endpoints.md) +- [Environment Variables](reference/general/environment-variables.md) +- [HTTP Server](reference/general/http-server.md) +- [Logging](reference/general/logging.md) +- [Pool Configuration](reference/general/pool-configuration.md) +- [Production Checklist](reference/general/production-checklist.md) +- [Registry Configuration](reference/general/registry-configuration.md) +- [Runtime Modes](reference/general/runtime-modes.md) +- [WASM vs Native SDK](reference/general/wasm-vs-native-sdk.md) + +### Self Hosting + +- [Configuration](reference/self-hosting/configuration.md) +- [Docker Compose](reference/self-hosting/docker-compose.md) +- [Docker Container](reference/self-hosting/docker-container.md) +- [File System](reference/self-hosting/filesystem.md) +- [FoundationDB (Enterprise)](reference/self-hosting/foundationdb.md) +- [Installing Rivet Engine](reference/self-hosting/install.md) +- [Kubernetes](reference/self-hosting/kubernetes.md) +- [Multi-Region](reference/self-hosting/multi-region.md) +- [PostgreSQL](reference/self-hosting/postgres.md) +- [Production Checklist](reference/self-hosting/production-checklist.md) +- [Railway Deployment](reference/self-hosting/railway.md) +- [Render Deployment](reference/self-hosting/render.md) +- [TLS & Certificates](reference/self-hosting/tls.md) + diff --git a/.agents/skills/cron-jobs/index.json b/.agents/skills/cron-jobs/index.json new file mode 100644 index 0000000..3ccf069 --- /dev/null +++ b/.agents/skills/cron-jobs/index.json @@ -0,0 +1,694 @@ +{ + "name": "cron-jobs", + "description": "Durable cron jobs with Rivet Actors: schedule.after and schedule.at timers survive restarts and crashes, plus re-arming recurring jobs and idempotent handlers.", + "skill_url": "/metadata/skills/cron-jobs/SKILL.md", + "generated_at": "2026-07-18T12:40:07.541Z", + "references": [ + { + "name": "actors/access-control", + "title": "Access Control", + "description": "Authorize actions, queue publishes, and event subscriptions with explicit hooks.", + "canonical_url": "https://rivet.dev/docs/actors/access-control", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/access-control.md" + }, + { + "name": "actors/actions", + "title": "Actions", + "description": "Actions are how your backend, frontend, or other actors can communicate with actors.", + "canonical_url": "https://rivet.dev/docs/actors/actions", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/actions.md" + }, + { + "name": "general/actor-configuration", + "title": "Actor Configuration", + "description": "This page documents the configuration options available when defining a RivetKit actor. The actor configuration is passed to the `actor()` function.", + "canonical_url": "https://rivet.dev/docs/general/actor-configuration", + "reference_url": "/metadata/skills/cron-jobs/reference/general/actor-configuration.md" + }, + { + "name": "actors/keys", + "title": "Actor Keys", + "description": "Actor keys uniquely identify actor instances within each actor type. Keys are used for addressing which specific actor to communicate with.", + "canonical_url": "https://rivet.dev/docs/actors/keys", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/keys.md" + }, + { + "name": "actors/actor-runtime-socket", + "title": "Actor Runtime Socket", + "description": "Connect trusted local tools to a running Rivet Actor over an experimental actor-local protocol.", + "canonical_url": "https://rivet.dev/docs/actors/actor-runtime-socket", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/actor-runtime-socket.md" + }, + { + "name": "actors/schedule", + "title": "Actor Scheduling", + "description": "Schedule actor actions in the future with persistent timers that survive restarts and upgrades.", + "canonical_url": "https://rivet.dev/docs/actors/schedule", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/schedule.md" + }, + { + "name": "actors/statuses", + "title": "Actor Statuses", + "description": "Understand the lifecycle statuses of Rivet Actors, what they mean, how they appear in the API, and how to troubleshoot common issues.", + "canonical_url": "https://rivet.dev/docs/actors/statuses", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/statuses.md" + }, + { + "name": "cookbook/ai-agent", + "title": "AI Agent", + "description": "Build an AI agent backend with persistent memory: one Rivet Actor per conversation, queued message handling, and streaming LLM responses as realtime events.", + "canonical_url": "https://rivet.dev/cookbook/ai-agent", + "reference_url": "/metadata/skills/cron-jobs/reference/cookbook/ai-agent.md" + }, + { + "name": "general/architecture", + "title": "Architecture", + "description": "- rivetkit is the typescript library used for both local development & to connect your application to rivet - a rivetkit instance is called a \"runner.\" you can run multiple runners to scale rivetkit horizontally. read omre about runners below.", + "canonical_url": "https://rivet.dev/docs/general/architecture", + "reference_url": "/metadata/skills/cron-jobs/reference/general/architecture.md" + }, + { + "name": "actors/authentication", + "title": "Authentication", + "description": "Secure your actors with authentication and authorization.", + "canonical_url": "https://rivet.dev/docs/actors/authentication", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/authentication.md" + }, + { + "name": "cookbook/chat-room", + "title": "Chat Room", + "description": "Build a realtime chat room backend with Rivet Actors: one actor per room, SQLite-backed message history, and WebSocket broadcast to every connected client.", + "canonical_url": "https://rivet.dev/cookbook/chat-room", + "reference_url": "/metadata/skills/cron-jobs/reference/cookbook/chat-room.md" + }, + { + "name": "cli", + "title": "CLI", + "description": "Reference for the optional rivet CLI: deploy to Rivet Compute and run local dev for serverless platforms.", + "canonical_url": "https://rivet.dev/docs/cli", + "reference_url": "/metadata/skills/cron-jobs/reference/cli.md" + }, + { + "name": "actors/quickstart/cloudflare", + "title": "Cloudflare Workers Quickstart", + "description": "Set up a Rivet project locally targeting Cloudflare Workers.", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/cloudflare", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/quickstart/cloudflare.md" + }, + { + "name": "cookbook/collaborative-text-editor", + "title": "Collaborative Text Editor", + "description": "Build a collaborative text editor backend with Yjs CRDTs and Rivet Actors: per-document actors relay sync and awareness updates and persist snapshots.", + "canonical_url": "https://rivet.dev/cookbook/collaborative-text-editor", + "reference_url": "/metadata/skills/cron-jobs/reference/cookbook/collaborative-text-editor.md" + }, + { + "name": "actors/communicating-between-actors", + "title": "Communicating Between Actors", + "description": "Learn how actors can call other actors and share data", + "canonical_url": "https://rivet.dev/docs/actors/communicating-between-actors", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/communicating-between-actors.md" + }, + { + "name": "self-hosting/configuration", + "title": "Configuration", + "description": "Rivet Engine can be configured through environment variables or configuration files.", + "canonical_url": "https://rivet.dev/docs/self-hosting/configuration", + "reference_url": "/metadata/skills/cron-jobs/reference/self-hosting/configuration.md" + }, + { + "name": "actors/connections", + "title": "Connections", + "description": "Connections represent client connections to your actor. They provide a way to handle client authentication, manage connection-specific data, and control the connection lifecycle.", + "canonical_url": "https://rivet.dev/docs/actors/connections", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/connections.md" + }, + { + "name": "deploy/container-runner", + "title": "Container Runner", + "description": "Run any containerized server as a Rivet Actor.", + "canonical_url": "https://rivet.dev/docs/deploy/container-runner", + "reference_url": "/metadata/skills/cron-jobs/reference/deploy/container-runner.md" + }, + { + "name": "cookbook/cron-jobs", + "title": "Cron Jobs and Scheduled Tasks", + "description": "Durable cron jobs with Rivet Actors: schedule.after and schedule.at timers survive restarts and crashes, plus re-arming recurring jobs and idempotent handlers.", + "canonical_url": "https://rivet.dev/cookbook/cron-jobs", + "reference_url": "/metadata/skills/cron-jobs/reference/cookbook/cron-jobs.md" + }, + { + "name": "general/cors", + "title": "Cross-Origin Resource Sharing", + "description": "Cross-Origin Resource Sharing (CORS) controls which origins (domains) can access your actors. When actors are exposed to the public internet, proper origin validation is critical to prevent security breaches and denial of service attacks.", + "canonical_url": "https://rivet.dev/docs/general/cors", + "reference_url": "/metadata/skills/cron-jobs/reference/general/cors.md" + }, + { + "name": "actors/inspector-tabs", + "title": "Custom Inspector Tabs", + "description": "Ship your own UI tabs alongside a Rivet Actor — embedded directly in the dashboard inspector.", + "canonical_url": "https://rivet.dev/docs/actors/inspector-tabs", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/inspector-tabs.md" + }, + { + "name": "cookbook/per-tenant-database", + "title": "Database per Tenant", + "description": "Multi-tenant data isolation with one Rivet Actor per tenant: the actor key is the tenant id, so each tenant gets its own isolated dataset and migrations.", + "canonical_url": "https://rivet.dev/cookbook/per-tenant-database", + "reference_url": "/metadata/skills/cron-jobs/reference/cookbook/per-tenant-database.md" + }, + { + "name": "actors/debugging", + "title": "Debugging", + "description": "Inspect and debug running Rivet Actors, runners, and provider configs using management, runner, and actor inspector HTTP APIs.", + "canonical_url": "https://rivet.dev/docs/actors/debugging", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/debugging.md" + }, + { + "name": "deploy/aws-lambda", + "title": "Deploy To Amazon Web Services Lambda", + "description": "_AWS Lambda is coming soon_", + "canonical_url": "https://rivet.dev/docs/deploy/aws-lambda", + "reference_url": "/metadata/skills/cron-jobs/reference/deploy/aws-lambda.md" + }, + { + "name": "cookbook/vpc-air-gapped", + "title": "Deploying Rivet in a VPC or Air-Gapped Network", + "description": "Run Rivet entirely inside your own perimeter: single-binary or Docker Compose install, file system storage with no database infrastructure, and no outbound telemetry by default.", + "canonical_url": "https://rivet.dev/cookbook/vpc-air-gapped", + "reference_url": "/metadata/skills/cron-jobs/reference/cookbook/vpc-air-gapped.md" + }, + { + "name": "deploy/aws-ecs", + "title": "Deploying to AWS ECS", + "description": "Run your backend on Amazon ECS with Fargate.", + "canonical_url": "https://rivet.dev/docs/deploy/aws-ecs", + "reference_url": "/metadata/skills/cron-jobs/reference/deploy/aws-ecs.md" + }, + { + "name": "deploy/cloudflare", + "title": "Deploying to Cloudflare Workers", + "description": "Deploy an existing Rivet project to Cloudflare Workers.", + "canonical_url": "https://rivet.dev/docs/deploy/cloudflare", + "reference_url": "/metadata/skills/cron-jobs/reference/deploy/cloudflare.md" + }, + { + "name": "deploy/freestyle", + "title": "Deploying to Freestyle", + "description": "Deploy RivetKit app to Freestyle.sh, a cloud platform for running AI-generated code with built-in security and scalability.", + "canonical_url": "https://rivet.dev/docs/deploy/freestyle", + "reference_url": "/metadata/skills/cron-jobs/reference/deploy/freestyle.md" + }, + { + "name": "deploy/gcp-cloud-run", + "title": "Deploying to Google Cloud Run", + "description": "Deploy your RivetKit app to Google Cloud Run.", + "canonical_url": "https://rivet.dev/docs/deploy/gcp-cloud-run", + "reference_url": "/metadata/skills/cron-jobs/reference/deploy/gcp-cloud-run.md" + }, + { + "name": "deploy/hetzner", + "title": "Deploying to Hetzner", + "description": "Please see the VM & Bare Metal guide.", + "canonical_url": "https://rivet.dev/docs/deploy/hetzner", + "reference_url": "/metadata/skills/cron-jobs/reference/deploy/hetzner.md" + }, + { + "name": "deploy/kubernetes", + "title": "Deploying to Kubernetes", + "description": "Deploy your RivetKit app to any Kubernetes cluster.", + "canonical_url": "https://rivet.dev/docs/deploy/kubernetes", + "reference_url": "/metadata/skills/cron-jobs/reference/deploy/kubernetes.md" + }, + { + "name": "deploy/railway", + "title": "Deploying to Railway", + "description": "Deploy your RivetKit app to Railway.", + "canonical_url": "https://rivet.dev/docs/deploy/railway", + "reference_url": "/metadata/skills/cron-jobs/reference/deploy/railway.md" + }, + { + "name": "deploy/rivet-compute", + "title": "Deploying to Rivet Compute", + "description": "Run your backend on Rivet Compute.", + "canonical_url": "https://rivet.dev/docs/deploy/rivet-compute", + "reference_url": "/metadata/skills/cron-jobs/reference/deploy/rivet-compute.md" + }, + { + "name": "deploy/supabase", + "title": "Deploying to Supabase Functions", + "description": "Deploy an existing Rivet project to Supabase Edge Functions.", + "canonical_url": "https://rivet.dev/docs/deploy/supabase", + "reference_url": "/metadata/skills/cron-jobs/reference/deploy/supabase.md" + }, + { + "name": "deploy/vercel", + "title": "Deploying to Vercel", + "description": "Deploy your Next.js Rivet app to Vercel.", + "canonical_url": "https://rivet.dev/docs/deploy/vercel", + "reference_url": "/metadata/skills/cron-jobs/reference/deploy/vercel.md" + }, + { + "name": "deploy/vm-and-bare-metal", + "title": "Deploying to VMs & Bare Metal", + "description": "Deploy your RivetKit app to any Linux VM or bare metal host.", + "canonical_url": "https://rivet.dev/docs/deploy/vm-and-bare-metal", + "reference_url": "/metadata/skills/cron-jobs/reference/deploy/vm-and-bare-metal.md" + }, + { + "name": "actors/design-patterns", + "title": "Design Patterns", + "description": "Common patterns and anti-patterns for building scalable actor systems.", + "canonical_url": "https://rivet.dev/docs/actors/design-patterns", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/design-patterns.md" + }, + { + "name": "actors/destroy", + "title": "Destroying Actors", + "description": "Actors can be permanently destroyed. Common use cases include:", + "canonical_url": "https://rivet.dev/docs/actors/destroy", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/destroy.md" + }, + { + "name": "self-hosting/docker-compose", + "title": "Docker Compose", + "description": "Deploy Rivet Engine with docker-compose for multi-container setups.", + "canonical_url": "https://rivet.dev/docs/self-hosting/docker-compose", + "reference_url": "/metadata/skills/cron-jobs/reference/self-hosting/docker-compose.md" + }, + { + "name": "self-hosting/docker-container", + "title": "Docker Container", + "description": "Run Rivet Engine in a single Docker container.", + "canonical_url": "https://rivet.dev/docs/self-hosting/docker-container", + "reference_url": "/metadata/skills/cron-jobs/reference/self-hosting/docker-container.md" + }, + { + "name": "general/docs-for-llms", + "title": "Documentation for LLMs & AI", + "description": "Rivet provides optimized documentation formats specifically designed for Large Language Models (LLMs) and AI integration tools.", + "canonical_url": "https://rivet.dev/docs/general/docs-for-llms", + "reference_url": "/metadata/skills/cron-jobs/reference/general/docs-for-llms.md" + }, + { + "name": "general/edge", + "title": "Edge Networking", + "description": "Actors automatically run near your users on your provider's global network.", + "canonical_url": "https://rivet.dev/docs/general/edge", + "reference_url": "/metadata/skills/cron-jobs/reference/general/edge.md" + }, + { + "name": "actors/quickstart/effect", + "title": "Effect.ts Quickstart (Beta)", + "description": "Build a Rivet Actor with the Effect SDK", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/effect", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/quickstart/effect.md" + }, + { + "name": "general/endpoints", + "title": "Endpoints", + "description": "Configure how your backend connects to Rivet and how clients reach your actors.", + "canonical_url": "https://rivet.dev/docs/general/endpoints", + "reference_url": "/metadata/skills/cron-jobs/reference/general/endpoints.md" + }, + { + "name": "general/environment-variables", + "title": "Environment Variables", + "description": "This page documents all environment variables that configure RivetKit behavior.", + "canonical_url": "https://rivet.dev/docs/general/environment-variables", + "reference_url": "/metadata/skills/cron-jobs/reference/general/environment-variables.md" + }, + { + "name": "actors/errors", + "title": "Errors", + "description": "Rivet provides robust error handling with security built in by default. Errors are handled differently based on whether they should be exposed to clients or kept private.", + "canonical_url": "https://rivet.dev/docs/actors/errors", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/errors.md" + }, + { + "name": "actors/fetch-and-websocket-handler", + "title": "Fetch and WebSocket Handler", + "description": "These docs have moved to [Low-Level WebSocket Handler](/docs/actors/websocket-handler) and [Low-Level Request Handler](/docs/actors/request-handler).", + "canonical_url": "https://rivet.dev/docs/actors/fetch-and-websocket-handler", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/fetch-and-websocket-handler.md" + }, + { + "name": "self-hosting/filesystem", + "title": "File System", + "description": "The file system backend stores all data on the local disk. This is suitable for single-node deployments, development, and testing.", + "canonical_url": "https://rivet.dev/docs/self-hosting/filesystem", + "reference_url": "/metadata/skills/cron-jobs/reference/self-hosting/filesystem.md" + }, + { + "name": "self-hosting/foundationdb", + "title": "FoundationDB (Enterprise)", + "description": "FoundationDB is the recommended storage backend for scalable production Rivet deployments.", + "canonical_url": "https://rivet.dev/docs/self-hosting/foundationdb", + "reference_url": "/metadata/skills/cron-jobs/reference/self-hosting/foundationdb.md" + }, + { + "name": "actors/helper-types", + "title": "Helper Types", + "description": "This page has moved to [Types](/docs/actors/types).", + "canonical_url": "https://rivet.dev/docs/actors/helper-types", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/helper-types.md" + }, + { + "name": "general/http-server", + "title": "HTTP Server", + "description": "Different ways to run your RivetKit HTTP server.", + "canonical_url": "https://rivet.dev/docs/general/http-server", + "reference_url": "/metadata/skills/cron-jobs/reference/general/http-server.md" + }, + { + "name": "actors/appearance", + "title": "Icons & Names", + "description": "Customize actors with display names and icons for the Rivet inspector and dashboard.", + "canonical_url": "https://rivet.dev/docs/actors/appearance", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/appearance.md" + }, + { + "name": "actors/state", + "title": "In-Memory State", + "description": "Actors store state in memory for instant reads and writes. State can be persisted automatically or kept ephemeral.", + "canonical_url": "https://rivet.dev/docs/actors/state", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/state.md" + }, + { + "name": "actors/input", + "title": "Input Parameters", + "description": "Pass initialization data to actors when creating instances", + "canonical_url": "https://rivet.dev/docs/actors/input", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/input.md" + }, + { + "name": "self-hosting/install", + "title": "Installing Rivet Engine", + "description": "Install Rivet Engine using Docker, binaries, or a source build.", + "canonical_url": "https://rivet.dev/docs/self-hosting/install", + "reference_url": "/metadata/skills/cron-jobs/reference/self-hosting/install.md" + }, + { + "name": "self-hosting/kubernetes", + "title": "Kubernetes", + "description": "Deploy production-ready Rivet Engine to Kubernetes with PostgreSQL storage.", + "canonical_url": "https://rivet.dev/docs/self-hosting/kubernetes", + "reference_url": "/metadata/skills/cron-jobs/reference/self-hosting/kubernetes.md" + }, + { + "name": "actors/lifecycle", + "title": "Lifecycle", + "description": "Learn about actor lifecycle hooks for initialization, state management, and cleanup.", + "canonical_url": "https://rivet.dev/docs/actors/lifecycle", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/lifecycle.md" + }, + { + "name": "actors/limits", + "title": "Limits", + "description": "Limits and constraints for Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/actors/limits", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/limits.md" + }, + { + "name": "cookbook/live-cursors", + "title": "Live Cursors and Presence", + "description": "Live cursors and multiplayer presence with Rivet Actors: per-connection cursor state, realtime updates over events or raw WebSockets, and throttling.", + "canonical_url": "https://rivet.dev/cookbook/live-cursors", + "reference_url": "/metadata/skills/cron-jobs/reference/cookbook/live-cursors.md" + }, + { + "name": "general/logging", + "title": "Logging", + "description": "Actors provide a built-in way to log complex data to the console.", + "canonical_url": "https://rivet.dev/docs/general/logging", + "reference_url": "/metadata/skills/cron-jobs/reference/general/logging.md" + }, + { + "name": "actors/request-handler", + "title": "Low-Level HTTP Request Handler", + "description": "Actors can handle HTTP requests through the `onRequest` handler.", + "canonical_url": "https://rivet.dev/docs/actors/request-handler", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/request-handler.md" + }, + { + "name": "actors/kv", + "title": "Low-Level KV Storage", + "description": "Use the built-in key-value store on ActorContext for durable string and binary data alongside actor state.", + "canonical_url": "https://rivet.dev/docs/actors/kv", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/kv.md" + }, + { + "name": "actors/websocket-handler", + "title": "Low-Level WebSocket Handler", + "description": "Actors can handle WebSocket connections through the `onWebSocket` handler.", + "canonical_url": "https://rivet.dev/docs/actors/websocket-handler", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/websocket-handler.md" + }, + { + "name": "actors/metadata", + "title": "Metadata", + "description": "Metadata provides information about the currently running actor.", + "canonical_url": "https://rivet.dev/docs/actors/metadata", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/metadata.md" + }, + { + "name": "self-hosting/multi-region", + "title": "Multi-Region", + "description": "Rivet Engine supports scaling transparently across multiple regions.", + "canonical_url": "https://rivet.dev/docs/self-hosting/multi-region", + "reference_url": "/metadata/skills/cron-jobs/reference/self-hosting/multi-region.md" + }, + { + "name": "cookbook/multiplayer-game", + "title": "Multiplayer Game", + "description": "Pragmatic patterns for building multiplayer games: matchmaking, tick loops, realtime state, interest management, and validation.", + "canonical_url": "https://rivet.dev/cookbook/multiplayer-game", + "reference_url": "/metadata/skills/cron-jobs/reference/cookbook/multiplayer-game.md" + }, + { + "name": "actors/quickstart/next-js", + "title": "Next.js Quickstart", + "description": "Get started with Rivet Actors in Next.js", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/next-js", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/quickstart/next-js.md" + }, + { + "name": "clients/javascript", + "title": "Node.js & Bun", + "description": "Connect JavaScript apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/javascript", + "reference_url": "/metadata/skills/cron-jobs/reference/clients/javascript.md" + }, + { + "name": "actors/quickstart/backend", + "title": "Node.js & Bun Quickstart", + "description": "Get started with Rivet Actors in Node.js and Bun", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/backend", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/quickstart/backend.md" + }, + { + "name": "general/pool-configuration", + "title": "Pool Configuration", + "description": "Reference for runner pool configuration, including drain behavior, actor eviction rate limiting, and serverless-specific options.", + "canonical_url": "https://rivet.dev/docs/general/pool-configuration", + "reference_url": "/metadata/skills/cron-jobs/reference/general/pool-configuration.md" + }, + { + "name": "self-hosting/postgres", + "title": "PostgreSQL", + "description": "Configure PostgreSQL for self-hosted Rivet deployments.", + "canonical_url": "https://rivet.dev/docs/self-hosting/postgres", + "reference_url": "/metadata/skills/cron-jobs/reference/self-hosting/postgres.md" + }, + { + "name": "general/production-checklist", + "title": "Production Checklist", + "description": "Checklist for deploying Rivet Actors to production.", + "canonical_url": "https://rivet.dev/docs/general/production-checklist", + "reference_url": "/metadata/skills/cron-jobs/reference/general/production-checklist.md" + }, + { + "name": "self-hosting/production-checklist", + "title": "Production Checklist", + "description": "Checklist for deploying a self-hosted Rivet Engine to production.", + "canonical_url": "https://rivet.dev/docs/self-hosting/production-checklist", + "reference_url": "/metadata/skills/cron-jobs/reference/self-hosting/production-checklist.md" + }, + { + "name": "actors/queues", + "title": "Queues & Run Loops", + "description": "Use actor-local durable queues for serial run loops and request/response workflows.", + "canonical_url": "https://rivet.dev/docs/actors/queues", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/queues.md" + }, + { + "name": "self-hosting/railway", + "title": "Railway Deployment", + "description": "Railway provides a simple platform for deploying Rivet Engine with automatic scaling and managed infrastructure.", + "canonical_url": "https://rivet.dev/docs/self-hosting/railway", + "reference_url": "/metadata/skills/cron-jobs/reference/self-hosting/railway.md" + }, + { + "name": "clients/react", + "title": "React", + "description": "Connect React apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/react", + "reference_url": "/metadata/skills/cron-jobs/reference/clients/react.md" + }, + { + "name": "actors/quickstart/react", + "title": "React Quickstart", + "description": "Build realtime React applications with Rivet Actors", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/react", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/quickstart/react.md" + }, + { + "name": "actors/events", + "title": "Realtime", + "description": "Events enable realtime communication from actors to clients. While clients use actions to send data to actors, events allow actors to push updates to connected clients instantly.", + "canonical_url": "https://rivet.dev/docs/actors/events", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/events.md" + }, + { + "name": "general/registry-configuration", + "title": "Registry Configuration", + "description": "This page documents the configuration options available when setting up a RivetKit registry. The registry configuration is passed to the `setup()` function.", + "canonical_url": "https://rivet.dev/docs/general/registry-configuration", + "reference_url": "/metadata/skills/cron-jobs/reference/general/registry-configuration.md" + }, + { + "name": "self-hosting/render", + "title": "Render Deployment", + "description": "Deploy Rivet Engine to Render with managed PostgreSQL and automatic HTTPS, using the experimental PostgreSQL backend.", + "canonical_url": "https://rivet.dev/docs/self-hosting/render", + "reference_url": "/metadata/skills/cron-jobs/reference/self-hosting/render.md" + }, + { + "name": "general/runtime-modes", + "title": "Runtime Modes", + "description": "RivetKit supports two runtime modes for running your actors:", + "canonical_url": "https://rivet.dev/docs/general/runtime-modes", + "reference_url": "/metadata/skills/cron-jobs/reference/general/runtime-modes.md" + }, + { + "name": "clients/rust", + "title": "Rust (Beta)", + "description": "Connect Rust apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/rust", + "reference_url": "/metadata/skills/cron-jobs/reference/clients/rust.md" + }, + { + "name": "actors/quickstart/rust", + "title": "Rust Quickstart (Beta)", + "description": "Build a Rivet Actor in Rust", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/rust", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/quickstart/rust.md" + }, + { + "name": "actors/scaling", + "title": "Scaling & Concurrency", + "description": "This page has moved to [design patterns](/docs/actors/design-patterns).", + "canonical_url": "https://rivet.dev/docs/actors/scaling", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/scaling.md" + }, + { + "name": "actors/sharing-and-joining-state", + "title": "Sharing and Joining State", + "description": "This page has moved to [design patterns](/docs/actors/design-patterns).", + "canonical_url": "https://rivet.dev/docs/actors/sharing-and-joining-state", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/sharing-and-joining-state.md" + }, + { + "name": "actors/sqlite", + "title": "SQLite", + "description": "Use embedded SQLite in Rivet Actors with raw SQL queries.", + "canonical_url": "https://rivet.dev/docs/actors/sqlite", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/sqlite.md" + }, + { + "name": "actors/sqlite-drizzle", + "title": "SQLite + Drizzle", + "description": "Use Drizzle ORM with embedded SQLite in Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/actors/sqlite-drizzle", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/sqlite-drizzle.md" + }, + { + "name": "actors/quickstart/supabase", + "title": "Supabase Functions Quickstart", + "description": "Set up a Rivet project locally targeting Supabase Edge Functions.", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/supabase", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/quickstart/supabase.md" + }, + { + "name": "clients/swift", + "title": "Swift", + "description": "Connect Swift apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/swift", + "reference_url": "/metadata/skills/cron-jobs/reference/clients/swift.md" + }, + { + "name": "clients/swiftui", + "title": "SwiftUI", + "description": "Build SwiftUI apps with Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/swiftui", + "reference_url": "/metadata/skills/cron-jobs/reference/clients/swiftui.md" + }, + { + "name": "actors/testing", + "title": "Testing", + "description": "Rivet provides a straightforward testing framework to build reliable and maintainable applications. This guide covers how to write effective tests for your actor-based services.", + "canonical_url": "https://rivet.dev/docs/actors/testing", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/testing.md" + }, + { + "name": "self-hosting/tls", + "title": "TLS & Certificates", + "description": "How Rivet validates TLS root certificates.", + "canonical_url": "https://rivet.dev/docs/self-hosting/tls", + "reference_url": "/metadata/skills/cron-jobs/reference/self-hosting/tls.md" + }, + { + "name": "actors/troubleshooting", + "title": "Troubleshooting", + "description": "Common issues with Rivet Actors and how to resolve them.", + "canonical_url": "https://rivet.dev/docs/actors/troubleshooting", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/troubleshooting.md" + }, + { + "name": "actors/types", + "title": "Types", + "description": "TypeScript types for working with Rivet Actors. This page covers context types used in lifecycle hooks and actions, as well as helper types for extracting types from actor definitions.", + "canonical_url": "https://rivet.dev/docs/actors/types", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/types.md" + }, + { + "name": "actors/http-api", + "title": "Vanilla HTTP API", + "description": "Use the low-level HTTP handler to send and receive requests from actors.", + "canonical_url": "https://rivet.dev/docs/actors/http-api", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/http-api.md" + }, + { + "name": "actors/versions", + "title": "Versions & Upgrades", + "description": "When you deploy new code, Rivet ensures actors are upgraded seamlessly without downtime.", + "canonical_url": "https://rivet.dev/docs/actors/versions", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/versions.md" + }, + { + "name": "general/wasm-vs-native-sdk", + "title": "WASM vs Native SDK", + "description": "RivetKit runs your actors on a native or a WebAssembly runtime depending on your platform.", + "canonical_url": "https://rivet.dev/docs/general/wasm-vs-native-sdk", + "reference_url": "/metadata/skills/cron-jobs/reference/general/wasm-vs-native-sdk.md" + }, + { + "name": "actors/workflows", + "title": "Workflows", + "description": "Build durable, replayable run loops in Rivet Actors with steps, queue waits, timers, and rollback.", + "canonical_url": "https://rivet.dev/docs/actors/workflows", + "reference_url": "/metadata/skills/cron-jobs/reference/actors/workflows.md" + } + ] +} \ No newline at end of file diff --git a/.agents/skills/cron-jobs/openapi.json b/.agents/skills/cron-jobs/openapi.json new file mode 100644 index 0000000..ca482f7 --- /dev/null +++ b/.agents/skills/cron-jobs/openapi.json @@ -0,0 +1,1311 @@ +{ + "openapi": "3.0.0", + "info": { + "version": "2.2.0", + "title": "RivetKit API" + }, + "components": { + "schemas": {}, + "parameters": {} + }, + "paths": { + "/actors": { + "get": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": false, + "name": "name", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "actor_ids", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "key", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "actors": { + "type": "array", + "items": { + "type": "object", + "properties": { + "actor_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "namespace_id": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "create_ts": { + "type": "number" + }, + "connectable_ts": { + "type": "number", + "nullable": true + }, + "destroy_ts": { + "type": "number", + "nullable": true + }, + "sleep_ts": { + "type": "number", + "nullable": true + }, + "start_ts": { + "type": "number", + "nullable": true + }, + "error": { + "nullable": true + } + }, + "required": [ + "actor_id", + "name", + "key", + "namespace_id", + "runner_name_selector", + "create_ts" + ] + } + } + }, + "required": [ + "actors" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + }, + "put": { + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "datacenter": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "crash_policy": { + "type": "string" + }, + "input": { + "type": "string", + "nullable": true + } + }, + "required": [ + "name", + "key", + "runner_name_selector", + "crash_policy" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "actor": { + "type": "object", + "properties": { + "actor_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "namespace_id": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "create_ts": { + "type": "number" + }, + "connectable_ts": { + "type": "number", + "nullable": true + }, + "destroy_ts": { + "type": "number", + "nullable": true + }, + "sleep_ts": { + "type": "number", + "nullable": true + }, + "start_ts": { + "type": "number", + "nullable": true + }, + "error": { + "nullable": true + } + }, + "required": [ + "actor_id", + "name", + "key", + "namespace_id", + "runner_name_selector", + "create_ts" + ] + }, + "created": { + "type": "boolean" + } + }, + "required": [ + "actor", + "created" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + }, + "post": { + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "datacenter": { + "type": "string" + }, + "name": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "crash_policy": { + "type": "string" + }, + "key": { + "type": "string", + "nullable": true + }, + "input": { + "type": "string", + "nullable": true + } + }, + "required": [ + "name", + "runner_name_selector", + "crash_policy" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "actor": { + "type": "object", + "properties": { + "actor_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "namespace_id": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "create_ts": { + "type": "number" + }, + "connectable_ts": { + "type": "number", + "nullable": true + }, + "destroy_ts": { + "type": "number", + "nullable": true + }, + "sleep_ts": { + "type": "number", + "nullable": true + }, + "start_ts": { + "type": "number", + "nullable": true + }, + "error": { + "nullable": true + } + }, + "required": [ + "actor_id", + "name", + "key", + "namespace_id", + "runner_name_selector", + "create_ts" + ] + } + }, + "required": [ + "actor" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/actors/names": { + "get": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "namespace", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "names": { + "type": "object", + "additionalProperties": { + "type": "object", + "properties": { + "metadata": { + "type": "object", + "additionalProperties": { + "nullable": true + } + } + }, + "required": [ + "metadata" + ] + } + } + }, + "required": [ + "names" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/actors/{actor_id}/kv/keys/{key}": { + "get": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "actor_id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "key", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "value": { + "type": "string", + "nullable": true + } + }, + "required": [ + "value" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/gateway/{actorId}/health": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + } + ], + "responses": { + "200": { + "description": "Health check", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + } + } + } + }, + "/gateway/{actorId}/action/{action}": { + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "action", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The name of the action to execute" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "args": {} + }, + "required": [ + "args" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Action executed successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "output": {} + }, + "required": [ + "output" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Invalid action" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/gateway/{actorId}/request/{path}": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "put": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "delete": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "patch": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "head": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "options": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + } + }, + "/gateway/{actorId}/inspector/state": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Current actor state", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": {} + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + }, + "patch": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": {} + }, + "required": [ + "state" + ] + } + } + } + }, + "responses": { + "200": { + "description": "State updated", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "ok": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/connections": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Current actor connections", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "connections": { + "type": "array", + "items": { + "type": "object" + } + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/rpcs": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Available actor actions/RPCs", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "rpcs": { + "type": "object" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/action/{name}": { + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The name of the action to execute" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "args": { + "type": "array", + "items": {} + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Action executed successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "output": {} + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/queue": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 50 + }, + "description": "Maximum number of queue messages to return" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Queue status", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "size": { + "type": "integer" + }, + "maxSize": { + "type": "integer" + }, + "truncated": { + "type": "boolean" + }, + "messages": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "createdAtMs": { + "type": "integer" + } + } + } + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/traces": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "startMs", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 0 + }, + "description": "Start of time range in epoch milliseconds" + }, + { + "name": "endMs", + "in": "query", + "required": false, + "schema": { + "type": "integer" + }, + "description": "End of time range in epoch milliseconds. Defaults to now." + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 1000 + }, + "description": "Maximum number of spans to return" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Trace spans in OTLP JSON format", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "otlp": { + "type": "object" + }, + "clamped": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/workflow-history": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Workflow history and status", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "history": {}, + "isWorkflowEnabled": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/workflow/replay": { + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "entryId": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Workflow history after scheduling a replay", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "history": {}, + "isWorkflowEnabled": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/summary": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Full actor inspector summary", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": {}, + "connections": { + "type": "array", + "items": { + "type": "object" + } + }, + "rpcs": { + "type": "object" + }, + "queueSize": { + "type": "integer" + }, + "isStateEnabled": { + "type": "boolean" + }, + "isDatabaseEnabled": { + "type": "boolean" + }, + "isWorkflowEnabled": { + "type": "boolean" + }, + "workflowHistory": {} + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + } + } +} \ No newline at end of file diff --git a/.agents/skills/cron-jobs/reference/actors/access-control.md b/.agents/skills/cron-jobs/reference/actors/access-control.md new file mode 100644 index 0000000..02dc4e8 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/access-control.md @@ -0,0 +1,48 @@ +# Access Control + +> Source: `src/content/docs/actors/access-control.mdx` +> Canonical URL: https://rivet.dev/docs/actors/access-control +> Description: Authorize actions, queue publishes, and event subscriptions with explicit hooks. + +--- +Use access control to decide what authenticated clients are allowed to do. + +This is authorization, not authentication: + +- Use [authentication](/docs/actors/authentication) to identify who is calling. +- Use access-control rules to decide what they can do after connecting. + +## Permission Surfaces + +RivetKit authorization is explicit per surface: + +- `onBeforeConnect` rejects unauthenticated or malformed connections. +- Action handlers (`actions.*`) enforce action permissions. +- `queues..canPublish` allows or denies inbound queue publishes. +- `events..canSubscribe` allows or denies event subscriptions. + +## Fail By Default + +Use deny-by-default rules everywhere: + +1. Keep `onBeforeConnect` strict and reject invalid credentials. +2. In each action, explicitly allow expected roles and throw `forbidden` otherwise. +3. In `canPublish` and `canSubscribe`, return `true` only for allowed roles and end with `return false`. + +## Return Value Contract + +`canPublish` and `canSubscribe` must return a boolean: + +- `true`: allow +- `false`: deny with `forbidden` + +Returning `undefined`, `null`, or any non-boolean throws an internal error. + +## Notes + +- `canPublish` only applies to queue names defined in `queues`. +- Incoming queue messages for undefined queues are ignored and the publish succeeds as completed. +- `canSubscribe` only applies to event names defined in `events`. +- Broadcasting an event not defined in `events` still publishes to subscribers. + +_Source doc path: /docs/actors/access-control_ diff --git a/.agents/skills/cron-jobs/reference/actors/actions.md b/.agents/skills/cron-jobs/reference/actors/actions.md new file mode 100644 index 0000000..d00324e --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/actions.md @@ -0,0 +1,98 @@ +# Actions + +> Source: `src/content/docs/actors/actions.mdx` +> Canonical URL: https://rivet.dev/docs/actors/actions +> Description: Actions are how your backend, frontend, or other actors can communicate with actors. + +--- +Actions are very lightweight. They can be called thousands of times per second safely. Actions are executed via HTTP requests or via WebSockets if [using `.connect()`](/docs/actors/connections). + +For advanced use cases that require direct access to HTTP requests or WebSocket connections, see [raw HTTP and WebSocket handling](/docs/actors/fetch-and-websocket-handler). + +By default, actions run in parallel. If you need advanced control over concurrency, use [queues](/docs/actors/queues). + +## Writing Actions + +Actions are defined in the `actions` object when creating an actor: + +Each action receives a context object (commonly named `c`) as its first parameter, which provides access to state, connections, and other utilities. Additional parameters follow after that. + +## Calling Actions + +Actions can be called in different ways depending on your use case: + +### Frontend (createClient) + +Learn more about [communicating with actors from the frontend](/docs/actors/communicating-between-actors). + +### Backend (registry.handler) + +Learn more about [communicating with actors from the backend](/docs/actors/communicating-between-actors). + +### Actor-to-Actor (c.client()) + +Learn more about [communicating between actors](/docs/actors/communicating-between-actors). + +Calling actions from the client are async and require an `await`, even if the action itself is not async. + +### Type Safety + +The actor client includes type safety out of the box. When you use `createClient()`, TypeScript automatically infers action parameter and return types: + +## Error Handling + +Actors provide robust error handling out of the box for actions. + +### User Errors + +`UserError` can be used to return rich error data to the client. You can provide: + +- A human-readable message +- A machine-readable code that's useful for matching errors in a try-catch (optional) +- A metadata object for providing richer error context (optional) + +For example: + +### Internal Errors + +All other errors will return an error with the code `internal_error` to the client. This helps keep your application secure, as errors can sometimes expose sensitive information. + +## Schema Validation + +If passing data to an actor from the frontend, use a library like [Zod](https://zod.dev/) to validate input data. + +For example, to validate action parameters: + +## Streaming Data + +Actions have a single return value. To stream realtime data in response to an action, use [events](/docs/actors/events). + +## Canceling Long-Running Actions + +For operations that should be cancelable on-demand, create your own `AbortController`. Chain it with `c.abortSignal` so actor shutdown also cancels the operation. + +See [Actor Shutdown Abort Signal](/docs/actors/lifecycle#actor-shutdown-abort-signal) for automatically canceling operations when the actor stops. + +## Using `ActionContext` Externally + +When writing complex logic for actions, you may want to extract parts of your implementation into separate helper functions. When doing this, you'll need a way to properly type the context parameter. + +Rivet provides the `ActionContextOf` utility type for exactly this purpose: + +See [types](/docs/actors/types) for more details on using `ActionContextOf` and other utility types. + +## Debugging + +- `GET /inspector/rpcs` lists all available actions on an actor. +- `POST /inspector/action/:name` executes an action with JSON args and returns output. +- In non-dev mode, inspector endpoints require authorization. + +## API Reference + +- [`Actions`](/typedoc/interfaces/rivetkit.mod.Actions.html) - Interface for defining actions +- [`ActionContext`](/typedoc/interfaces/rivetkit.mod.ActionContext.html) - Context available in action handlers +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining actors with actions +- [`ActorHandle`](/typedoc/types/rivetkit.client_mod.ActorHandle.html) - Handle for calling actions from client +- [`ActorActionFunction`](/typedoc/types/rivetkit.client_mod.ActorActionFunction.html) - Type for action functions + +_Source doc path: /docs/actors/actions_ diff --git a/.agents/skills/cron-jobs/reference/actors/actor-runtime-socket.md b/.agents/skills/cron-jobs/reference/actors/actor-runtime-socket.md new file mode 100644 index 0000000..2f736d5 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/actor-runtime-socket.md @@ -0,0 +1,54 @@ +# Actor Runtime Socket + +> Source: `src/content/docs/actors/actor-runtime-socket.mdx` +> Canonical URL: https://rivet.dev/docs/actors/actor-runtime-socket +> Description: Connect trusted local tools to a running Rivet Actor over an experimental actor-local protocol. + +--- +> **Experimental:** The Actor Runtime Socket protocol and API may change between releases. It is available only in the Unix native runtime and must be enabled per actor. + +The **Actor Runtime Socket** is a generic, actor-local protocol for trusted tools running in the same application environment as a Rivet Actor. SQLite is its first capability; Unix domain sockets are its current transport. + +Each running actor generation lazily creates its own socket. The socket is removed when that generation sleeps, stops, or is destroyed, so clients must request the current path again after the actor wakes or restarts. + +## Enable the socket + +Enable the feature under the actor's `options`, then provision it from the actor context: + +```ts @nocheck +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +export const example = actor({ + options: { + enableActorRuntimeSocket: true, + }, + db: db({ + onMigrate: async (db) => { + await db.execute("CREATE TABLE IF NOT EXISTS items (value TEXT)"); + }, + }), + run: async (c) => { + const { path } = await c.actorRuntimeSocket(); + // Give `path` only to trusted, application-local tooling. + }, +}); +``` + +Provisioning fails unless the actor has an enabled LocalNative SQLite database. The per-process socket directory uses mode `0700`, and each actor socket uses mode `0600`. + +## Protocol + +Unix `SOCK_STREAM` provides a reliable local byte stream but does not preserve message boundaries. Every frame is therefore a four-byte big-endian payload length followed by a versioned BARE (`vbare`) payload. The embedded protocol version is a two-byte little-endian prefix. Clients begin with `ClientHello`; the server returns `HelloOk` with the maximum frame size or rejects an unsupported version. + +The current protocol supports: + +- multi-statement SQLite scripts with `SqliteExec`; +- single-statement parameterized queries with `SqliteQuery`; +- transactions spanning requests with `SqliteBegin`, `SqliteCommit`, and `SqliteRollback`. + +A transaction is identified by a client-chosen `leaseKey` scoped to one connection. Other actor SQL and other socket transactions wait in FIFO order while it runs. Transactions default to a 60-second safety timeout; `SqliteBegin.timeoutMs` may override it. If the deadline fires, RivetKit rolls the transaction back and later requests for that key receive `LeaseExpired`. + +The socket is an application-local integration boundary, not a network authentication boundary. It intentionally has no bearer token. Clients must still honor framing and response limits, and should reconnect using a newly provisioned path after actor generation changes. + +_Source doc path: /docs/actors/actor-runtime-socket_ diff --git a/.agents/skills/cron-jobs/reference/actors/appearance.md b/.agents/skills/cron-jobs/reference/actors/appearance.md new file mode 100644 index 0000000..f60b1a1 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/appearance.md @@ -0,0 +1,50 @@ +# Icons & Names + +> Source: `src/content/docs/actors/appearance.mdx` +> Canonical URL: https://rivet.dev/docs/actors/appearance +> Description: Customize actors with display names and icons for the Rivet inspector and dashboard. + +--- +# Icons & Names + +Actors can be customized with a display name and icon that appear in the Rivet inspector & dashboard. This helps identify actors at a glance when managing your application. + +## Configuration + +Set the `name` and `icon` properties in your actor's `options`: + +## Icon Formats + +The `icon` property accepts two formats: + +### Emoji + +Use any emoji character directly: + +### FontAwesome Icons + +Use [FontAwesome](https://fontawesome.com/search) icon names without the "fa" prefix: + +## Default Behavior + +If no `icon` is specified, actors display the default actor icon. If no `name` is specified, the actor's registry key (e.g., `chatRoom`, `gameServer`) is displayed instead. + +## Examples + +Here are some common patterns: + +## Advanced: Run Handler Metadata + +For library developers creating reusable run handlers, you can bundle icon and name metadata directly with the `run` property. This allows libraries to provide sensible defaults without requiring users to configure them manually. + +Instead of returning a function from your run handler factory, return an object with `name`, `icon`, and `run`: + +Users can then use this directly: + +This run-handler metadata is currently applied through the registry and serverless metadata paths. The native runtime and inspector config read the actor's `options.name` and `options.icon` directly, so set those explicitly if you need the name or icon to appear everywhere. + +Actor-level `options.name` and `options.icon` always take precedence, allowing users to override library defaults: + +The built-in `workflow()` helper uses this pattern to automatically display the workflow icon for workflow-based actors. + +_Source doc path: /docs/actors/appearance_ diff --git a/.agents/skills/cron-jobs/reference/actors/authentication.md b/.agents/skills/cron-jobs/reference/actors/authentication.md new file mode 100644 index 0000000..c456dde --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/authentication.md @@ -0,0 +1,105 @@ +# Authentication + +> Source: `src/content/docs/actors/authentication.mdx` +> Canonical URL: https://rivet.dev/docs/actors/authentication +> Description: Secure your actors with authentication and authorization. + +--- +## Do You Need Authentication? + +### Rivet Cloud + + Actors are private by default on Rivet Cloud. Only requests with the publishable token can interact with actors. + + - **Backend-only actors**: If your publishable token is only included in your backend, then authentication is not necessary. + - **Frontend-accessible actors**: If your publishable token is included in your frontend, then implementing authentication is recommended. + +### Self-Hosted + + Actors are public by default on self-hosted Rivet. Anyone can access them without a token. + + - **Only accessible within private network**: If Rivet is only accessible within your private network, then authentication is not necessary. + - **Rivet exposed to the public internet**: If Rivet is configured to accept traffic from the public internet, then implementing authentication is recommended. + +## Authentication Connections + +Authentication is configured through either: + +- `onBeforeConnect` for simple pass/fail validation +- `createConnState` when you need to access user data in your actions via `c.conn.state` + +## Access Control + +After a connection is authenticated, use [Access Control](/docs/actors/access-control) to enforce authorization: + +- Check permissions in action handlers. +- Use `queues..canPublish` to gate inbound queue publishes. +- Use `events..canSubscribe` to gate event subscriptions. + +### `onBeforeConnect` + +The `onBeforeConnect` hook validates credentials before allowing a connection. Throw an error to reject the connection. + +### `createConnState` + +Use `createConnState` to extract user data from credentials and store it in connection state. This data is accessible in actions via `c.conn.state`. Like `onBeforeConnect`, throwing an error will reject the connection. See [connections](/docs/actors/connections) for more details. + +## Available Auth Data + +Authentication hooks have access to several properties: + +| Property | Description | +|----------|-------------| +| `params` | Custom data passed by the client when connecting (see [connection params](/docs/actors/connections#extracting-data-from-connection-params)) | +| `c.request` | The underlying HTTP request object | +| `c.request.headers` | Request headers for tokens, API keys (does not work for `.connect()`) | +| `c.state` | Actor state for authorization decisions (see [state](/docs/actors/state)) | +| `c.key` | The actor's key (see [keys](/docs/actors/keys)) | + +It's recommended to use `params` instead of `c.request.headers` whenever possible since it works for both HTTP & WebSocket connections. + +## Client Usage + +### Passing Credentials + +Pass authentication data when connecting. Use `getParams` when you need a fresh JWT for every connection or reconnect: + +### Handling Errors + +Authentication errors use the same system as regular errors. See [errors](/docs/actors/errors) for more details. + +## Examples + +### JWT + +Validate JSON Web Tokens and extract user claims: + +### External Auth Provider + +Validate credentials against an external authentication service: + +### Using `c.state` In Authorization + +Access actor state via `c.state` and the actor's key via `c.key` to make authorization decisions: + +### Role-Based Access Control + +Create helper functions for common authorization patterns: + +### Rate Limiting + +Use `c.vars` to track connection attempts and rate limit by user: + +The limits in this example are [ephemeral](/docs/actors/state#ephemeral-variables). If you wish to persist rate limits, you can optionally replace `vars` with `state`. + +### Caching Tokens + +Cache validated tokens in `c.vars` to avoid redundant validation on repeated connections. See [ephemeral variables](/docs/actors/state#ephemeral-variables) for more details. + +## API Reference + +- [`AuthIntent`](/typedoc/types/rivetkit.mod.AuthIntent.html) - Authentication intent type +- [`OnBeforeConnectContext`](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html) - Context for auth checks +- [`OnConnectContext`](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html) - Context after connection + +_Source doc path: /docs/actors/authentication_ diff --git a/.agents/skills/cron-jobs/reference/actors/communicating-between-actors.md b/.agents/skills/cron-jobs/reference/actors/communicating-between-actors.md new file mode 100644 index 0000000..8aeaf39 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/communicating-between-actors.md @@ -0,0 +1,42 @@ +# Communicating Between Actors + +> Source: `src/content/docs/actors/communicating-between-actors.mdx` +> Canonical URL: https://rivet.dev/docs/actors/communicating-between-actors +> Description: Learn how actors can call other actors and share data + +--- +Actors can communicate with each other using the server-side actor client, enabling complex workflows and data sharing between different actor instances. + +We recommend reading the [clients documentation](/docs/clients) first. This guide focuses specifically on communication between actors. + +## Using the Server-Side Actor Client + +The server-side actor client allows actors to call other actors within the same registry. Access it via `c.client()` in your actor context: + +If two actors call each other and their return types are inferred from the other actor's response, you may hit circular type errors (`TS2322`, `TS2722`, or `c.state` becoming `unknown`). Fix this by writing explicit return types on those actions. + +## Use Cases and Patterns + +### Actor Orchestration + +Use a coordinator actor to manage complex workflows: + +### Data Aggregation + +Collect data from multiple actors: + +### Event-Driven Architecture + +Use connections to listen for events from other actors: + +### Batch Operations + +Process multiple items in parallel: + +## API Reference + +- [`ActorHandle`](/typedoc/types/rivetkit.client_mod.ActorHandle.html) - Handle for calling other actors +- [`Client`](/typedoc/types/rivetkit.mod.Client.html) - Client type for actor communication +- [`ActorAccessor`](/typedoc/interfaces/rivetkit.client_mod.ActorAccessor.html) - Accessor for getting actor handles + +_Source doc path: /docs/actors/communicating-between-actors_ diff --git a/.agents/skills/cron-jobs/reference/actors/connections.md b/.agents/skills/cron-jobs/reference/actors/connections.md new file mode 100644 index 0000000..10ef081 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/connections.md @@ -0,0 +1,119 @@ +# Connections + +> Source: `src/content/docs/actors/connections.mdx` +> Canonical URL: https://rivet.dev/docs/actors/connections +> Description: Connections represent client connections to your actor. They provide a way to handle client authentication, manage connection-specific data, and control the connection lifecycle. + +--- +For documentation on connecting to actors from clients, see the [Clients documentation](/docs/clients). For worked presence and chat patterns, see the cookbook: [Live Cursors and Presence](/cookbook/live-cursors/) and [Chat Room](/cookbook/chat-room/). + +## Parameters + +When clients connect to an actor, they can pass connection parameters that are handled during the connection process. Use `params` for static values, or `getParams` when you need fresh connection data each time a connection opens. + +For example: + +## Connection State + +There are two ways to define an actor's connection state: + + +### connState + + Define connection state as a constant value: + + + + This value will be cloned for every new connection using `structuredClone`. + + + +### createConnState + + Create connection state dynamically with a function called for each connection: + + + + +## Connection Lifecycle + +Each client connection goes through a series of lifecycle hooks that allow you to validate, initialize, and clean up connection-specific resources. + +**On Connect** (per client) + +- `onBeforeConnect` +- `createConnState` +- `onConnect` + +Pending connections are not visible in `c.conns` while `onBeforeConnect` or `createConnState` is running. RivetKit adds the connection to `c.conns` after those hooks succeed and before `onConnect` runs. + +**On Disconnect** (per client) + +- `onDisconnect` + +### `createConnState` and `connState` + +[API Reference](/typedoc/interfaces/rivetkit.mod.CreateConnStateContext.html) + +There are two ways to define the initial state for connections: +1. `connState`: Define a constant object that will be used as the initial state for all connections +2. `createConnState`: A function that dynamically creates initial connection state based on connection parameters. Can be async. + +Connections are not visible in `c.conns` until `createConnState` completes successfully. + +### `onBeforeConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html) + +The `onBeforeConnect` hook is called whenever a new client connects to the actor. Can be async. Clients can pass parameters when connecting, accessible via `params`. This hook is used for connection validation and can throw errors to reject connections. + +The `onBeforeConnect` hook does NOT return connection state - it's used solely for validation. + +Connections are not visible in `c.conns` while `onBeforeConnect` is running. + +Connections cannot interact with the actor until this method completes successfully. Throwing an error will abort the connection. This can be used for authentication, see [Authentication](/docs/actors/authentication) for details. + +### `onConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html) + +Executed after the client has successfully connected. Can be async. Receives the connection object as a second parameter. + +By the time `onConnect` runs, the connection is visible in `c.conns`. + +Messages will not be processed for this actor until this hook succeeds. Errors thrown from this hook will cause the client to disconnect. + +### `onDisconnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Called when a client disconnects from the actor. Can be async. Receives the connection object as a second parameter. Use this to clean up any connection-specific resources. + +## Connection List + +All active connections can be accessed through the context object's `conns` property. This is a `Map` of all current connections, keyed by connection ID. + +This is frequently used with `conn.send(name, event)` to send messages directly to clients. To send an event to all connections at once, use `c.broadcast()` instead. See [Events](/docs/actors/events) for more details on broadcasting. + +For example: + +`conn.send()` has no effect on [low-level WebSocket connections](/docs/actors/websocket-handler). For low-level WebSockets, use the WebSocket API directly (e.g., `websocket.send()`). + +## Disconnecting clients + +Connections can be disconnected from within an action: + +If you need to wait for the disconnection to complete, you can use `await`: + +This ensures the underlying network connections close cleanly before continuing. + +## API Reference + +- [`Conn`](/typedoc/interfaces/rivetkit.mod.Conn.html) - Connection interface +- [`ConnInitContext`](/typedoc/interfaces/rivetkit.mod.ConnInitContext.html) - Connection initialization context +- [`CreateConnStateContext`](/typedoc/interfaces/rivetkit.mod.CreateConnStateContext.html) - Context for creating connection state +- [`OnBeforeConnectContext`](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html) - Pre-connection lifecycle hook context +- [`OnConnectContext`](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html) - Post-connection lifecycle hook context +- [`ActorConn`](/typedoc/types/rivetkit.client_mod.ActorConn.html) - Typed connection from client side + +_Source doc path: /docs/actors/connections_ diff --git a/.agents/skills/cron-jobs/reference/actors/debugging.md b/.agents/skills/cron-jobs/reference/actors/debugging.md new file mode 100644 index 0000000..409b381 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/debugging.md @@ -0,0 +1,644 @@ +# Debugging + +> Source: `src/content/docs/actors/debugging.mdx` +> Canonical URL: https://rivet.dev/docs/actors/debugging +> Description: Inspect and debug running Rivet Actors, runners, and provider configs using management, runner, and actor inspector HTTP APIs. + +--- +## Connecting to Rivet + +All debugging endpoints in this guide are available both locally and in production. In local development, the base URL is `http://localhost:6420` with no authentication. In production (Rivet Cloud or self-hosted), you connect to your Rivet Engine endpoint with a token. + +### Setup + +All examples in this guide use these shell variables. Extract them from your `RIVET_ENDPOINT` (`https://:@`): + +```bash +# From RIVET_ENDPOINT=https://my-namespace:sk_abc123@api.rivet.dev +export RIVET_API="https://api.rivet.dev" +export RIVET_NAMESPACE="my-namespace" +export RIVET_TOKEN="sk_abc123" + +# For local development: +# export RIVET_API="http://localhost:6420" +``` + +Rivet Cloud issues two token types: `sk_` (secret key, server-side only) and `pk_` (public key, client-safe). For debugging, always use `sk_`. See [Endpoints](/docs/general/endpoints) for more details. + +## Management API + +The management API runs on the manager base path (default root path) and is used to list, create, and look up actors. + +### Authentication + +| Environment | Authentication | +|---|---| +| **Local development** | No authentication required. All endpoints are accessible without tokens. | +| **Self-hosted engine** | Set `RIVET_TOKEN` to enable authenticated access to restricted endpoints like KV. | +| **Rivet Cloud** | Authentication is enforced by your deployment entrypoint. For manager KV access, use the bearer token header below when enabled. | + +Restricted endpoints (like KV reads) require the `Authorization: Bearer` header when `RIVET_TOKEN` is configured: + +```bash +curl "$RIVET_API/actors/{actor_id}/kv/keys/{base64_key}" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +### List Actors + +```bash +# List all actors with a given name +curl "$RIVET_API/actors?name=my-actor&namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" + +# Look up one actor by key (name is required when key is provided) +curl "$RIVET_API/actors?name=my-actor&key=%5B%22my-key%22%5D&namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" + +# List actors by IDs (comma-separated) +curl "$RIVET_API/actors?actor_ids=id1,id2&namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Rules: + +- `key` requires `name`. +- `actor_ids` cannot be combined with `name` or `key`. + +Returns: + +```json +{ + "actors": [ + { + "actor_id": "abc123", + "name": "my-actor", + "key": "[\"default\"]", + "namespace_id": "default", + "create_ts": 1706000000000 + } + ] +} +``` + +### Create Actor + +`POST /actors` creates a new actor. + +```bash +curl -X POST "$RIVET_API/actors?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H 'Content-Type: application/json' \ + -d '{ + "name": "my-actor", + "runner_name_selector": "default", + "crash_policy": "restart" + }' +``` + +### Create or Get Actor + +`PUT /actors` creates an actor if it does not exist, otherwise returns the existing one. + +```bash +curl -X PUT "$RIVET_API/actors?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H 'Content-Type: application/json' \ + -d '{ + "name": "my-actor", + "key": "[\"default\"]", + "runner_name_selector": "default", + "crash_policy": "restart" + }' +``` + +Returns the actor object with its `actor_id`. + +### List Actor Names + +```bash +curl "$RIVET_API/actors/names?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns all registered actor names and their metadata. + +### Read Actor KV + +Requires authentication (see above). + +```bash +curl "$RIVET_API/actors/{actor_id}/kv/keys/{base64_key}" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns the value stored at the given key in the actor KV compatibility snapshot. After an actor has migrated to SQLite-backed runtime storage, this endpoint is stale for user KV and internal runtime records; it continues to expose the frozen pre-migration KV data. The inspector token key is the exception and remains mirrored for dashboard compatibility. + +See the [OpenAPI spec](https://github.com/rivet-dev/rivet/tree/main/rivetkit-openapi) for the full schema of all management endpoints. + +## Runner API + +Use the runner endpoints to debug scheduler capacity and provider configuration (for example serverless URL, headers, and limits) through the Rivet API. + +### List Runner Names + +```bash +curl "$RIVET_API/runners/names?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns the runner pools available in the namespace: + +```json +{ + "names": ["default", "gpu-workers"], + "pagination": { "cursor": null } +} +``` + +### List Runners in a Pool + +```bash +curl "$RIVET_API/runners?namespace=$RIVET_NAMESPACE&name=default&include_stopped=true&limit=100" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Useful fields when debugging: + +- `remaining_slots` / `total_slots` for capacity. +- `drain_ts` and `stop_ts` for shutdown behavior. +- `last_ping_ts` and `last_connected_ts` for connectivity. + +### Inspect Provider Config (Runner Config) + +```bash +curl "$RIVET_API/runner-configs?namespace=$RIVET_NAMESPACE&runner_name=default" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns the configured provider settings per datacenter and the latest pool error (if any): + +```json +{ + "runner_configs": { + "default": { + "datacenters": { + "dc-1": { + "serverless": { + "url": "https://your-deployment.example.com/rivet", + "headers": { "Authorization": "Bearer token" }, + "request_lifespan": 55, + "slots_per_runner": 1, + "max_runners": 10 + }, + "runner_pool_error": null + } + } + } + }, + "pagination": { "cursor": null } +} +``` + +`runner_pool_error` mirrors actor scheduling errors such as `serverless_http_error`, `serverless_connection_error`, and `serverless_stream_ended_early`. + +### Check Serverless Provider Health + +Use this to test whether Rivet can reach your serverless provider URL and read runner metadata: + +```bash +curl -X POST "$RIVET_API/runner-configs/serverless-health-check?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "url": "https://your-deployment.example.com/rivet", + "headers": { + "Authorization": "Bearer token" + } + }' +``` + +Possible responses: + +```json +{ "success": { "version": "1.2.3" } } +``` + +```json +{ + "failure": { + "error": { + "message": "non-success status from metadata endpoint", + "details": "received status 503" + } + } +} +``` + +### Refresh Provider Metadata + +If you deploy new actor code or routes and metadata has not updated yet, force a refresh: + +```bash +curl -X POST "$RIVET_API/runner-configs/default/refresh-metadata?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{}' +``` + +## Actor API + +All actor-level endpoints are accessed through the gateway. The gateway routes requests to the correct actor instance using the actor ID in the URL path: + +``` +{RIVET_API}/gateway/{actor_id}/{path} +``` + +The gateway only accepts actor IDs, not names. Use `GET /actors?name=...` from the management API to look up actor IDs first. + +### Authentication + +Standard actor endpoints (health, actions, requests) and inspector endpoints have separate authentication requirements. + +#### Standard Endpoints + +| Environment | Authentication | +|---|---| +| **Local development** | No authentication required. | +| **Self-hosted engine** | The Rivet Engine handles authentication at the gateway level. | +| **Rivet Cloud** | Authentication is handled by the Rivet Cloud platform at the gateway level. | + +#### Inspector Endpoints + +Each actor generates a unique inspector token on first start and persists it in internal SQLite storage. It is also mirrored to legacy KV key `0x03` (base64 `Aw==`) for dashboard compatibility. Pass it as a bearer token in the `Authorization` header. + +Inspector endpoints always require the actor's inspector token, including in local development. There is no local-development bypass. + +| Environment | Authentication | +|---|---| +| **Local development** | Bearer the actor's inspector token in the `Authorization` header. Fetch it through the management KV endpoint (see below). | +| **Self-hosted engine** | Bearer the actor's inspector token in the `Authorization` header. The Rivet dashboard fetches it automatically; for direct API access, fetch it through the management KV endpoint (see below). | +| **Rivet Cloud** | Bearer the actor's inspector token in the `Authorization` header. The Rivet dashboard fetches it automatically; for direct API access, fetch it through the management KV endpoint (see below). | + +```bash +curl "$RIVET_API/gateway/{actor_id}/inspector/summary" \ + -H 'Authorization: Bearer YOUR_INSPECTOR_TOKEN' +``` + +#### Retrieving the Inspector Token + +Each actor generates a unique inspector token on first start and persists it in internal SQLite storage. The token is also mirrored to the legacy KV key below so the Rivet dashboard can continue to retrieve it through the management KV endpoint. This applies in every environment, including local development. + +The inspector token is stored at internal KV key `0x03` (base64: `Aw==`). The response value is also base64-encoded. + +```bash +# Fetch the inspector token for a specific actor +ACTOR_ID="your-actor-id" + +RESPONSE=$(curl -s "$RIVET_API/actors/$ACTOR_ID/kv/keys/Aw==" \ + -H "Authorization: Bearer $RIVET_TOKEN") + +# Extract and decode the base64 value +INSPECTOR_TOKEN=$(echo "$RESPONSE" | jq -r '.value' | base64 -d) + +# Use it to call inspector endpoints +curl "$RIVET_API/gateway/$ACTOR_ID/inspector/summary" \ + -H "Authorization: Bearer $INSPECTOR_TOKEN" +``` + +### Standard Actor Endpoints + +These are the built-in actor endpoints available through the gateway: + +```bash +# Health check +curl $RIVET_API/gateway/{actor_id}/health + +# Metadata +curl $RIVET_API/gateway/{actor_id}/metadata + +# Call an action +curl -X POST $RIVET_API/gateway/{actor_id}/action/myAction \ + -H 'Content-Type: application/json' \ + -d '{"args": [1, 2, 3]}' + +# Send queue message (queue name in path) +curl -X POST $RIVET_API/gateway/{actor_id}/queue/jobs \ + -H 'Content-Type: application/json' \ + -d '{"body":{"id":"job-1"}}' + +# Send queue message and wait for completion (optional timeout in ms) +curl -X POST $RIVET_API/gateway/{actor_id}/queue/jobs \ + -H 'Content-Type: application/json' \ + -d '{"body":{"id":"job-1"},"wait":true,"timeout":5000}' + +# Forward an HTTP request to the actor's onRequest handler +curl $RIVET_API/gateway/{actor_id}/request/my/custom/path +``` + +Queue send responses always include a `status` field: + +```json +{ "status": "completed" } +``` + +The `response` field is only present when the queue handler returns a value: + +```json +{ "status": "completed", "response": { "result": "ok" } } +``` + +If `wait: true` and the timeout is reached, `status` is `"timedOut"`. + +### Inspector Endpoints + +The inspector HTTP API exposes JSON endpoints for querying and modifying actor internals at runtime. These are designed for agent-based debugging and tooling. + +Every inspector endpoint requires the actor's inspector token as a bearer token, including in local development. The examples below omit the `Authorization` header for brevity, but you must add `-H "Authorization: Bearer $INSPECTOR_TOKEN"` to each request. See [Retrieving the Inspector Token](#retrieving-the-inspector-token) above. + +#### Get State + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/state +``` + +Returns the actor's current persisted state: + +```json +{ + "state": { "count": 42, "users": [] }, + "isStateEnabled": true +} +``` + +#### Set State + +```bash +curl -X PATCH $RIVET_API/gateway/{actor_id}/inspector/state \ + -H 'Content-Type: application/json' \ + -d '{"state": {"count": 0, "users": []}}' +``` + +Returns: + +```json +{ "ok": true } +``` + +#### Get Connections + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/connections +``` + +Returns all active connections with their params, state, and metadata: + +```json +{ + "connections": [ + { + "type": "websocket", + "id": "conn-id", + "details": { + "type": "websocket", + "params": {}, + "stateEnabled": true, + "state": {}, + "subscriptions": 2, + "isHibernatable": true + } + } + ] +} +``` + +#### Get RPCs + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/rpcs +``` + +Returns a list of available actions: + +```json +{ "rpcs": ["increment", "getCount"] } +``` + +#### Execute Action + +```bash +curl -X POST $RIVET_API/gateway/{actor_id}/inspector/action/increment \ + -H 'Content-Type: application/json' \ + -d '{"args": [5]}' +``` + +Returns: + +```json +{ "output": 47 } +``` + +#### Get Queue Status + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/queue?limit=10 +``` + +Returns queue status with messages: + +```json +{ + "size": 3, + "maxSize": 1000, + "truncated": false, + "messages": [ + { "id": 1, "name": "process", "createdAtMs": 1706000000000 } + ] +} +``` + +#### Get Workflow History + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/workflow-history +``` + +Returns: + +```json +{ + "history": null, + "isWorkflowEnabled": false +} +``` + +#### Get Database Schema + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/database/schema +``` + +Returns discovered SQLite tables and views when the actor has `c.db` enabled: + +```json +{ + "schema": { + "tables": [ + { + "table": { "schema": "main", "name": "test_data", "type": "table" }, + "columns": [ + { "cid": 0, "name": "id", "type": "", "notnull": 0, "dflt_value": null, "pk": 0 } + ], + "foreignKeys": [], + "records": 2 + } + ] + } +} +``` + +#### Get Database Rows + +```bash +curl "$RIVET_API/gateway/{actor_id}/inspector/database/rows?table=test_data&limit=100&offset=0" +``` + +Returns paged rows for a specific SQLite table or view: + +```json +{ + "rows": [ + { + "id": 1, + "value": "Alice", + "payload": "", + "created_at": 1706000000000 + } + ] +} +``` + +#### Execute SQLite + +Run manual SQL against an actor's SQLite database. This supports both read-only queries and mutations. + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/database/execute \ + -H 'Content-Type: application/json' \ + -d '{ + "sql": "SELECT id, value FROM test_data WHERE value = ? ORDER BY id DESC", + "args": ["alpha"] + }' +``` + +Returns: + +```json +{ + "rows": [ + { "id": 2, "value": "alpha" } + ] +} +``` + +You can also use named SQLite bindings through a `properties` object: + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/database/execute \ + -H 'Content-Type: application/json' \ + -d '{ + "sql": "SELECT id, value FROM test_data WHERE value = :value ORDER BY id DESC", + "properties": { + "value": "alpha" + } + }' +``` + +For mutations, use `RETURNING` if you want rows back. Otherwise the statement still runs and `rows` is empty: + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/database/execute \ + -H 'Content-Type: application/json' \ + -d '{ + "sql": "INSERT INTO test_data (value, created_at) VALUES (?, ?) RETURNING id, value", + "args": ["beta", 1706000000000] + }' +``` + +For workflow-enabled actors, `history` is a JSON object with `nameRegistry`, `entries`, and `entryMetadata`. Step outputs, loop state, and message payloads are decoded from CBOR into normal JSON values. + +#### Replay Workflow From Step + +Reset a workflow to a specific step and restart execution immediately. Omitting `entryId` replays the workflow from the beginning. + +If the workflow is still running when you call replay, the endpoint rejects the request with `409 Conflict` and an `actor/workflow_in_flight` error instead of cancelling the live run for you. + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/workflow/replay \ + -H 'Content-Type: application/json' \ + -d '{"entryId":"workflow-step-id"}' +``` + +Returns the same JSON shape as `/inspector/workflow-history`: + +```json +{ + "history": { + "nameRegistry": ["step-one", "step-two"], + "entries": [], + "entryMetadata": {} + }, + "isWorkflowEnabled": true +} +``` + +While a workflow is in flight, the response shape is: + +```json +{ + "group": "actor", + "code": "workflow_in_flight", + "message": "Workflow replay is unavailable while the workflow is currently in flight.", + "metadata": null +} +``` + +#### Summary + +Get a full snapshot of the actor in a single request: + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/summary +``` + +Returns: + +```json +{ + "state": { "count": 42 }, + "connections": [], + "rpcs": ["increment", "getCount"], + "queueSize": 0, + "isStateEnabled": true, + "isDatabaseEnabled": false, + "isWorkflowEnabled": false, + "workflowHistory": null +} +``` + +When workflow history is present in `/inspector/summary`, `workflowHistory` is returned as the same decoded JSON shape as `/inspector/workflow-history`. + +### Polling + +Inspector endpoints are safe to poll. For live monitoring, poll at 1-5 second intervals. The `/inspector/summary` endpoint is useful for periodic snapshots since it returns all data in a single request. + +## OpenAPI Spec + +An OpenAPI specification covering many of the management and actor endpoints is available: + +- In the repository at [`rivetkit-openapi/openapi.json`](https://github.com/rivet-dev/rivet/tree/main/rivetkit-openapi) +- Served at `/doc` on the manager when running locally + +The checked-in spec does not yet list every endpoint documented on this page (for example the actor metadata and queue routes and the inspector database routes), so treat this page as the authoritative reference where they differ. + +_Source doc path: /docs/actors/debugging_ diff --git a/.agents/skills/cron-jobs/reference/actors/design-patterns.md b/.agents/skills/cron-jobs/reference/actors/design-patterns.md new file mode 100644 index 0000000..77ecb40 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/design-patterns.md @@ -0,0 +1,163 @@ +# Design Patterns + +> Source: `src/content/docs/actors/design-patterns.mdx` +> Canonical URL: https://rivet.dev/docs/actors/design-patterns +> Description: Common patterns and anti-patterns for building scalable actor systems. + +--- +## How Actors Scale + +Actors are inherently scalable because of how they're designed: + +- **Isolated state:** Each actor manages its own private data. No shared state means no conflicts and no locks, so actors run concurrently without coordination. +- **Actor-to-actor communication:** Actors interact through [actions](/docs/actors/actions) and [events](/docs/actors/events), so they don't need to coordinate access to shared data. This makes it easy to distribute them across machines. +- **Small, focused units:** Each actor handles a limited scope (a single user, document, or chat room), so load naturally spreads across many actors rather than concentrating in one place. +- **Horizontal scaling:** Adding more machines automatically distributes actors across them. + +These properties form the foundation for the patterns described below. + +## Actor Per Entity + +The core pattern is creating one actor per entity in your system. Each actor represents a single user, document, chat room, or other distinct object. This keeps actors small, independent, and easy to scale. + +**Good examples** + +- `User`: Manages user profile, preferences, and authentication +- `Document`: Handles document content, metadata, and versioning +- `ChatRoom`: Manages participants and message history + +**Bad examples** + +- `Application`: Too broad, handles everything +- `DocumentWordCount`: Too granular, should be part of Document actor + +## Coordinator & Data Actors + +Actors scale by splitting state into isolated entities. However, it's common to need to track and coordinate actors in a central place. This is where coordinator actors come in. + +**Data actors** handle the main logic in your application. Examples: chat rooms, user sessions, game lobbies. + +**Coordinator actors** track other actors. Think of them as an index of data actors. Examples: a list of chat rooms, a list of active users, a list of game lobbies. + +**Example: Chat Room Coordinator** + +### Actor + +### Client + +## Sharding + +Sharding splits a single actor's workload across multiple actors based on a key. Use this when one actor can't handle all the load or data for an entity. + +**How it works:** +- Partition data using a shard key (user ID, region, time bucket, or random) +- Requests are routed to shards based on the key +- Shards operate independently without coordination + +**Example: Sharding by Time** + +### Actor + +### Client + +**Example: Random Sharding** + +### Actor + +### Client + +Choose shard keys that distribute load evenly. Note that cross-shard queries require coordination. + +## Fan-In & Fan-Out + +Fan-in and fan-out are patterns for distributing work and aggregating results. + +**Fan-Out**: One actor spawns work across multiple actors. Use for parallel processing or broadcasting updates. + +**Fan-In**: Multiple actors send results to one aggregator. Use for collecting results or reducing data. + +**Example: Map-Reduce** + +### Actor + +### Client + +## Integrating With External Databases & APIs + +Actors can integrate with external resources like databases or external APIs. + +### Loading State + +Load external data during actor initialization using `createVars`. This keeps your actor's persisted state clean while caching expensive lookups. + +Use this when: + +- Fetching user profiles, configs, or permissions from a database +- Loading data that changes externally and shouldn't be persisted +- Caching expensive API calls or computations + +**Example: Loading User Profile** + +### Actor + +### Client + +### Syncing State Changes + +Use `onStateChange` to automatically sync actor state changes to external resources. This hook runs after state changes are flushed, which is coalesced to once per event loop tick rather than once per individual field mutation. + +Use this when: + +- You need to mirror actor state in an external database +- Triggering external side effects when state changes +- Keeping external systems in sync with actor state + +**Example: Syncing to Database** + +### Actor + +### Client + +`onStateChange` is called once per flush with the final coalesced state, ensuring external resources stay in sync. In the `updateEmail` example above, the two synchronous assignments produce a single `onStateChange` call. + +Do not mutate `c.state` inside `onStateChange`; re-entrant state mutation is rejected. + +## Anti-Patterns + +### "God" Actor + +Avoid creating a single actor that handles everything. This defeats the purpose of the actor model and creates a bottleneck. + +**Problem:** +```ts +import { actor } from "rivetkit"; + +// Bad: one actor doing everything +const app = actor({ + state: { users: {}, orders: {}, inventory: {}, analytics: {} }, + actions: { + createUser: (c, user) => { /* ... */ }, + processOrder: (c, order) => { /* ... */ }, + updateInventory: (c, item) => { /* ... */ }, + trackEvent: (c, event) => { /* ... */ }, + }, +}); +``` + +**Solution:** Split into focused actors per entity (User, Order, Inventory, Analytics). + +### Actor-Per-Request + +Actors are designed to maintain state across multiple requests. Creating a new actor for each request wastes resources and loses the benefits of persistent state. + +**Problem:** + +**Solution:** Use actors for entities that persist (users, sessions, documents), not for one-off operations. For stateless request handling, use regular functions. + +## API Reference + +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for pattern examples +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - Context usage patterns +- [`ActionContext`](/typedoc/interfaces/rivetkit.mod.ActionContext.html) - Action patterns + +_Source doc path: /docs/actors/design-patterns_ diff --git a/.agents/skills/cron-jobs/reference/actors/destroy.md b/.agents/skills/cron-jobs/reference/actors/destroy.md new file mode 100644 index 0000000..87e1b76 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/destroy.md @@ -0,0 +1,71 @@ +# Destroying Actors + +> Source: `src/content/docs/actors/destroy.mdx` +> Canonical URL: https://rivet.dev/docs/actors/destroy +> Description: Actors can be permanently destroyed. Common use cases include: + +--- +- User account deletion +- Ending a user session +- Closing a room or game +- Cleaning up temporary resources +- GDPR/compliance data removal + +Actors sleep when idle, so destruction is only needed to permanently remove data — not to save compute. + +## Destroying An Actor + +### Destroy via Action + +To destroy an actor, use `c.destroy()` like this: + +### Destroy via HTTP + +Send a DELETE request to destroy an actor. This requires a token for authentication: + +- **Rivet Cloud**: Use the service key (`sk_*`) from your `RIVET_ENDPOINT` URL. Find this in the dashboard under **Settings > Advanced > Backend Configuration** (e.g. the `sk_...` portion of `https://default:sk_abc123@api.rivet.dev`). +- **Self-hosted**: Use an admin token. + +```typescript +const actorId = "your-actor-id"; +const namespace = "default"; +const token = "your-token"; + +await fetch(`https://api.rivet.dev/actors/${actorId}?namespace=${namespace}`, { + method: "DELETE", + headers: { + Authorization: `Bearer ${token}`, + }, +}); +``` + +```bash +curl -X DELETE "https://api.rivet.dev/actors/{actorId}?namespace={namespace}" \ + -H "Authorization: Bearer {token}" +``` + +To find the actor ID, you can list actors first: + +```bash +curl "https://api.rivet.dev/actors?namespace={namespace}" \ + -H "Authorization: Bearer {token}" +``` + +### Destroy via Dashboard + +To destroy an actor via the dashboard, navigate to the actor and press the red "X" in the top right. + +## Lifecycle Hook + +Once destroyed, the `onDestroy` hook will be called. This can be used to clean up resources related to the actor. For example: + +## Accessing Actor After Destroy + +Once an actor is destroyed, any subsequent requests to it will fail with an `actor.not_found` error (`{ group: "actor", code: "not_found" }`). The actor's state is permanently deleted. + +## API Reference + +- [`ActorHandle`](/typedoc/types/rivetkit.client_mod.ActorHandle.html) - Has destroy methods +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - Context during destruction + +_Source doc path: /docs/actors/destroy_ diff --git a/.agents/skills/cron-jobs/reference/actors/errors.md b/.agents/skills/cron-jobs/reference/actors/errors.md new file mode 100644 index 0000000..af24c4c --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/errors.md @@ -0,0 +1,81 @@ +# Errors + +> Source: `src/content/docs/actors/errors.mdx` +> Canonical URL: https://rivet.dev/docs/actors/errors +> Description: Rivet provides robust error handling with security built in by default. Errors are handled differently based on whether they should be exposed to clients or kept private. + +--- +There are two types of errors: + +- **UserError**: Thrown from actors and safely returned to clients with full details +- **Internal errors**: All other errors that are converted to a generic error message for security + +## Throwing and Catching Errors + +`UserError` lets you throw custom errors that will be safely returned to the client. + +Throw a `UserError` with just a message: + +### Actor + +### Client (Connection) + +### Client (Stateless) + +## Error Codes + +Use error codes for explicit error matching in try-catch blocks: + +### Actor + +### Client (Connection) + +### Client (Stateless) + +## Errors With Metadata + +Include metadata to provide additional context for rich error handling: + +### Actor + +### Client (Connection) + +### Client (Stateless) + +## Internal Errors + +All errors that are not UserError instances are automatically converted to a generic "internal error" response. This prevents accidentally leaking sensitive information like stack traces, database details, or internal system information. + +### Actor + +### Client (Connection) + +### Client (Stateless) + +### Server-Side Logging + +**All internal errors are logged server-side with full details.** When an internal error occurs, the complete error message, stack trace, and context are written to your server logs. This is where you should look first when debugging internal errors in production. + +The client receives only a generic "Internal error" message for security, but you can find the full error details in your server logs including: + +- Complete error message +- Stack trace +- Request context (actor ID, action name, connection ID, etc.) +- Timestamp + +**Always check your server logs to see the actual error details when debugging internal errors.** + +### Exposing Errors to Clients (Development Only) + +**Warning:** Only enable error exposure in development environments. In production, this will leak sensitive internal details to clients. + +For faster debugging during development, you can expose internal error details to clients by setting `RIVET_EXPOSE_ERRORS=1`. + +With error exposure enabled, clients will see the full error message instead of the generic "Internal error" response: + +## API Reference + +- [`UserError`](/typedoc/classes/rivetkit.actor_errors.UserError.html) - User-facing error class +- [`ActorError`](/typedoc/classes/rivetkit.client_mod.ActorError.html) - Errors received by the client + +_Source doc path: /docs/actors/errors_ diff --git a/.agents/skills/cron-jobs/reference/actors/events.md b/.agents/skills/cron-jobs/reference/actors/events.md new file mode 100644 index 0000000..ec4a7d5 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/events.md @@ -0,0 +1,145 @@ +# Realtime + +> Source: `src/content/docs/actors/events.mdx` +> Canonical URL: https://rivet.dev/docs/actors/events +> Description: Events enable realtime communication from actors to clients. While clients use actions to send data to actors, events allow actors to push updates to connected clients instantly. + +--- +Events can be sent to clients connected using `.connect()`. They have no effect on [low-level WebSocket connections](/docs/actors/websocket-handler). + +For worked realtime patterns, see the cookbook: [Live Cursors and Presence](/cookbook/live-cursors/) and [Chat Room](/cookbook/chat-room/). + +## Publishing Events from Actors + +### Broadcasting to All Clients + +Define event names and payload types with `events` and `event()`, then use `c.broadcast(eventName, ...args)` to send events to all connected clients: + +### Sending to Specific Connections + +Send events to individual connections using `conn.send(eventName, ...args)`: + +Send events to all connections except the sender: + +## Subscribing to Events from Clients + +Clients must establish a connection to receive events from actors. Use `.connect()` to create a persistent connection, then listen for events. + +### Basic Event Subscription + +Use `connection.on(eventName, callback)` to listen for events: + +```tsx React @nocheck +import { useState } from "react"; +import { useActor } from "./rivetkit"; + +function ChatRoom() { + const [messages, setMessages] = useState>([]); + + const chatRoom = useActor({ + name: "chatRoom", + key: ["general"] + }); + + // Listen for events + chatRoom.useEvent("messageReceived", (message) => { + setMessages(prev => [...prev, message]); + }); + + // ...rest of component... +} +``` + +### One-time Event Listeners + +Use `connection.once(eventName, callback)` for events that should only trigger once: + +```tsx React @nocheck +import { useState, useEffect } from "react"; +import { useActor } from "./rivetkit"; + +function GameLobby() { + const [gameStarted, setGameStarted] = useState(false); + + const gameRoom = useActor({ + name: "gameRoom", + key: ["room-456"], + params: { + playerId: "player-789", + role: "player" + } + }); + + // Listen for game start (only once) + useEffect(() => { + if (!gameRoom.connection) return; + + const handleGameStart = () => { + console.log('Game has started!'); + setGameStarted(true); + }; + + gameRoom.connection.once('gameStarted', handleGameStart); + }, [gameRoom.connection]); + + // ...rest of component... +} +``` + +### Removing Event Listeners + +Use the callback returned from `.on()` to remove event listeners: + +```tsx React @nocheck +import { useState, useEffect } from "react"; +import { useActor } from "./rivetkit"; + +function ConditionalListener() { + const [isListening, setIsListening] = useState(false); + const [messages, setMessages] = useState([]); + + const chatRoom = useActor({ + name: "chatRoom", + key: ["general"] + }); + + useEffect(() => { + if (!chatRoom.connection || !isListening) return; + + // Add listener + const unsubscribe = chatRoom.connection.on('messageReceived', (message) => { + setMessages(prev => [...prev, message.text]); + }); + + // Cleanup - remove listener when component unmounts or listening stops + return () => { + unsubscribe(); + }; + }, [chatRoom.connection, isListening]); + + // ...rest of component... +} +``` + +## Debugging + +- `GET /inspector/connections` shows active connections and connection metadata. +- Use this to confirm clients are connected before expecting broadcasts. +- `GET /inspector/summary` provides connections, RPCs, and queue size in one response. +- In non-dev mode, inspector endpoints require authorization. + +## More About Connections + +For more details on actor connections, including connection lifecycle, authentication, and advanced connection patterns, see the [Connections documentation](/docs/actors/connections). + +## API Reference + +- [`RivetEvent`](/typedoc/interfaces/rivetkit.mod.RivetEvent.html) - Base event interface +- [`RivetMessageEvent`](/typedoc/interfaces/rivetkit.mod.RivetMessageEvent.html) - Message event type +- [`RivetCloseEvent`](/typedoc/interfaces/rivetkit.mod.RivetCloseEvent.html) - Close event type +- [`UniversalEvent`](/typedoc/interfaces/rivetkit.mod.UniversalEvent.html) - Universal event type +- [`UniversalMessageEvent`](/typedoc/interfaces/rivetkit.mod.UniversalMessageEvent.html) - Universal message event +- [`UniversalErrorEvent`](/typedoc/interfaces/rivetkit.mod.UniversalErrorEvent.html) - Universal error event +- [`EventUnsubscribe`](/typedoc/types/rivetkit.client_mod.EventUnsubscribe.html) - Unsubscribe function type + +_Source doc path: /docs/actors/events_ diff --git a/.agents/skills/cron-jobs/reference/actors/fetch-and-websocket-handler.md b/.agents/skills/cron-jobs/reference/actors/fetch-and-websocket-handler.md new file mode 100644 index 0000000..b8b0509 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/fetch-and-websocket-handler.md @@ -0,0 +1,10 @@ +# Fetch and WebSocket Handler + +> Source: `src/content/docs/actors/fetch-and-websocket-handler.mdx` +> Canonical URL: https://rivet.dev/docs/actors/fetch-and-websocket-handler +> Description: These docs have moved to [Low-Level WebSocket Handler](/docs/actors/websocket-handler) and [Low-Level Request Handler](/docs/actors/request-handler). + +--- + + +_Source doc path: /docs/actors/fetch-and-websocket-handler_ diff --git a/.agents/skills/cron-jobs/reference/actors/helper-types.md b/.agents/skills/cron-jobs/reference/actors/helper-types.md new file mode 100644 index 0000000..55555c7 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/helper-types.md @@ -0,0 +1,10 @@ +# Helper Types + +> Source: `src/content/docs/actors/helper-types.mdx` +> Canonical URL: https://rivet.dev/docs/actors/helper-types +> Description: This page has moved to [Types](/docs/actors/types). + +--- + + +_Source doc path: /docs/actors/helper-types_ diff --git a/.agents/skills/cron-jobs/reference/actors/http-api.md b/.agents/skills/cron-jobs/reference/actors/http-api.md new file mode 100644 index 0000000..1d8d5be --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/http-api.md @@ -0,0 +1,10 @@ +# Vanilla HTTP API + +> Source: `src/content/docs/actors/http-api.mdx` +> Canonical URL: https://rivet.dev/docs/actors/http-api +> Description: Use the low-level HTTP handler to send and receive requests from actors. + +--- +TODO + +_Source doc path: /docs/actors/http-api_ diff --git a/.agents/skills/cron-jobs/reference/actors/input.md b/.agents/skills/cron-jobs/reference/actors/input.md new file mode 100644 index 0000000..c5c5dde --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/input.md @@ -0,0 +1,51 @@ +# Input Parameters + +> Source: `src/content/docs/actors/input.mdx` +> Canonical URL: https://rivet.dev/docs/actors/input +> Description: Pass initialization data to actors when creating instances + +--- +Actors can receive input parameters when created, allowing for flexible initialization and configuration. Input is passed during actor creation and is available in lifecycle hooks. + +## Passing Input to Actors + +Input is provided when creating actor instances using the `input` property: + +## Accessing Input in Lifecycle Hooks + +Input is available as the second argument to the `createState` and `onCreate` lifecycle hooks: + +## Input Validation + +You can validate input parameters in the `createState` or `onCreate` hooks: + +## Input vs Connection Parameters + +Input parameters are different from connection parameters: + +- **Input**: + - Passed when creating the actor instance + - Use for actor-wide configuration + - Available in lifecycle hooks +- **Connection parameters**: + - Passed when connecting to an existing actor + - Used for connection-specific configuration + - Available in connection hooks + +## Input Best Practices + +### Use Type Safety + +Define input types to ensure type safety: + +### Store Input in State + +Input is only available in `createState` and `onCreate` lifecycle hooks. If you need to access input data later (in actions, timers, or other hooks), store it in the actor's state during creation. This is the recommended pattern because input shapes can evolve over time, and persisting input in state ensures you always have access to the values the actor was created with: + +## API Reference + +- [`CreateOptions`](/typedoc/interfaces/rivetkit.client_mod.CreateOptions.html) - Options for creating actors +- [`CreateRequest`](/typedoc/types/rivetkit.client_mod.CreateRequest.html) - Request type for creation +- [`ActorDefinition`](/typedoc/classes/rivetkit.mod.ActorDefinition.html) - Actor definition returned by `actor()` + +_Source doc path: /docs/actors/input_ diff --git a/.agents/skills/cron-jobs/reference/actors/inspector-tabs.md b/.agents/skills/cron-jobs/reference/actors/inspector-tabs.md new file mode 100644 index 0000000..34de206 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/inspector-tabs.md @@ -0,0 +1,251 @@ +# Custom Inspector Tabs + +> Source: `src/content/docs/actors/inspector-tabs.mdx` +> Canonical URL: https://rivet.dev/docs/actors/inspector-tabs +> Description: Ship your own UI tabs alongside a Rivet Actor — embedded directly in the dashboard inspector. + +--- +Custom inspector tabs let you embed your own UI directly in the Rivet +dashboard, next to the built-in tabs. Declare a tab on your actor, point +it at a folder of static files, and the dashboard picks it up +automatically. + +Common uses: + +- Domain-specific debugging panels (queue depth, connection maps, log + filters). +- Operational tools (admin buttons, drain controls, snapshot uploaders). +- Any author-defined view that ships with your actor. + +A runnable example lives at +[`examples/inspector-tabs`](https://github.com/rivet-dev/rivet/tree/main/examples/inspector-tabs). + +## Quickstart + +Declare a tab on your actor: + +Drop an `index.html` in the `source` directory: + +```html + + + + + + + +

Counter: …

+ + + +``` + +Open the dashboard and the "Counter" tab appears alongside the built-ins. + +## Configuration + +Each entry in `inspector.tabs[]` is either a **custom tab** or a +**hide modifier** for a built-in. + +### Custom tab + +```ts @nocheck +{ + id: string, // URL-safe id: /^[A-Za-z0-9_-]+$/ + label: string, // Shown in the tab strip + source: string, // Directory of static assets + icon?: string, // Optional icon id +} +``` + +- **`id`** — used as the URL segment and tab-strip key. Cannot collide + with a built-in id (`workflow`, `database`, `state`, `queue`, + `connections`, `console`). +- **`source`** — directory of static files. The bytes you put there are + the bytes the browser sees. Point it at a Vite/webpack `dist/` and + any framework works (React, Vue, Svelte, vanilla — all fine). +- **`icon`** — one of `workflow`, `database`, `state`, `queue`, `plug`, + `terminal`, `tag`, `logs`. Anything else falls back to a neutral icon. + +### Hide a built-in tab + +```ts @nocheck +{ + id: "workflow" | "database" | "state" | "queue" | "connections" | "console", + hidden: true, +} +``` + +Use this to clean up the strip when the actor doesn't use a given +subsystem — e.g. a counter actor with no queues: + +```ts +inspector: { tabs: [{ id: "queue", hidden: true }] } +``` + +Misconfigurations (missing directory, duplicate id, invalid characters, +empty label) throw at registry construction, so problems show up +immediately. + +## Talking to the dashboard + +The tab loads in an iframe and communicates with the dashboard via +`postMessage`. The contract is small. + +### From the dashboard + +The dashboard sends an `init` message on load and again whenever the +inspector token rotates. Always overwrite the cached token when it +arrives. + +```ts @nocheck +{ + type: "init", + v: 1, + actorId: string, + authToken: string, // Per-actor inspector bearer token + theme?: "light" | "dark", + activeTab?: string, // For multi-view tabs +} +``` + +Multi-view tabs can read the optional `activeTab` field on `init` to +seed their initial sub-view. The dashboard does not send a separate +message when the user switches custom tabs — it navigates the iframe +`src` instead, so the tab reloads and receives a fresh `init`. + +### From the tab + +Send `ready` once your message listener is registered: + +```ts @nocheck +{ type: "ready", v: 1 } +``` + +If a fetch returns 401, the token has rotated. Ask the dashboard for a +fresh one and wait for the next `init` — don't retry with the stale +token: + +```ts @nocheck +{ type: "token-refresh-needed", v: 1 } +``` + +### Security check + +Always reject messages whose `event.origin` doesn't match the +`?shellOrigin=` URL parameter. Without this check, any page that frames +your tab could forge an `init` and feed you a fake token. + +### TypeScript types + +If you build the tab with TypeScript, the message and response types +are exported as types-only: + +## Reading state and calling actions + +The tab can hit any inspector endpoint with the supplied bearer token. +Use relative paths so the tab doesn't need to know the engine origin or +actor id: + +```js +fetch("../../state", { headers: { Authorization: `Bearer ${token}` } }); +fetch("../../action/increment", { method: "POST", headers: { ... }, body: ... }); +fetch("../../rpcs", { headers: { Authorization: `Bearer ${token}` } }); +fetch("../../connections", { headers: { Authorization: `Bearer ${token}` } }); +fetch("../../queue", { headers: { Authorization: `Bearer ${token}` } }); +``` + +The action body shape is `{ args: [...] }` — the array is passed as +positional arguments to the action. + +Full endpoint reference: +[Debugging → Inspector Endpoints](/docs/actors/debugging#inspector-endpoints). + +For high-frequency UIs, prefer the inspector WebSocket +(`/inspector/connect`) over polling. + +## Styling + +A shared stylesheet matching the dashboard's design tokens is served at +`../../tab.css`: + +```html + +``` + +It defines `--rivet-*` tokens for colors, spacing, radius, and +typography, plus sensible defaults so a bare tab looks at home without +custom CSS: + +```css +.my-card { + background: var(--rivet-card); + color: var(--rivet-foreground); + border: 1px solid var(--rivet-border); + border-radius: var(--rivet-radius-md); + padding: var(--rivet-space-4); +} +``` + +Toggle dark mode by adding the `dark` class to `` — the dashboard +sends the active theme in the `init` message. + +Color tokens come in both pre-wrapped (`--rivet-card`) and raw HSL +(`--rivet-card-raw`) forms, so you can compose with alpha: + +```css +.overlay { background: hsl(var(--rivet-background-raw) / 0.6); } +``` + +You're free to skip the stylesheet entirely and bring your own. + +## Security + +The tab runs in an iframe at the engine origin and can call any +inspector endpoint with the supplied token. Treat the bundle like any +author code that ships with your actor: + +- **Don't inline secrets.** The bundle is fetchable by anyone who can + reach the actor. +- **Always validate `event.origin`.** Reject inbound messages from + anywhere other than the dashboard origin. +- **Never retry silently on 401.** Post `token-refresh-needed` and wait + for a fresh `init`. + +## See also + +- [Debugging](/docs/actors/debugging) — full inspector HTTP API +- [Actions](/docs/actors/actions) — actions your tab can invoke +- [State](/docs/actors/state) — state your tab can read +- [`examples/inspector-tabs`](https://github.com/rivet-dev/rivet/tree/main/examples/inspector-tabs) — runnable example + +_Source doc path: /docs/actors/inspector-tabs_ diff --git a/.agents/skills/cron-jobs/reference/actors/keys.md b/.agents/skills/cron-jobs/reference/actors/keys.md new file mode 100644 index 0000000..b8f1614 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/keys.md @@ -0,0 +1,51 @@ +# Actor Keys + +> Source: `src/content/docs/actors/keys.mdx` +> Canonical URL: https://rivet.dev/docs/actors/keys +> Description: Actor keys uniquely identify actor instances within each actor type. Keys are used for addressing which specific actor to communicate with. + +--- +## Key Format + +Actor keys can be either a string or an array of strings: + +### Compound Keys & User Data + +Array keys are useful when you need compound keys with user-provided data. Using arrays makes adding user data safe by preventing key injection attacks: + +This allows you to create hierarchical addressing schemes and organize actors by multiple dimensions. + +Don't build keys using string interpolation like `"foo:${userId}:bar"` when `userId` contains user data. If a user provides a value containing the delimiter (`:` in this example), it can break your key structure and cause key injection attacks. + +### Omitting Keys + +You can create actors without specifying a key in situations where there is a singleton actor (i.e. only one actor of a given type). For example: + +This pattern should be avoided, since a singleton actor usually means you have a single actor serving all traffic & your application will not scale. See [scaling documentation](/docs/actors/scaling) for more information. + +### Key Uniqueness + +Keys are unique within each actor name. Different actor types can use the same key: + +## Accessing Keys in Metadata + +Access the actor's key within the actor using the [metadata](/docs/actors/metadata) API: + +## Configuration Examples + +### Simple Configuration with Keys + +Use keys to provide basic actor configuration: + +### Complex Configuration with Input + +For more complex configuration, use [input parameters](/docs/actors/input): + +## API Reference + +- [`ActorKey`](/typedoc/types/rivetkit.mod.ActorKey.html) - Key type for actors +- [`ActorQuery`](/typedoc/types/rivetkit.mod.ActorQuery.html) - Query type using keys +- [`GetOptions`](/typedoc/interfaces/rivetkit.client_mod.GetOptions.html) - Options for getting by key +- [`QueryOptions`](/typedoc/interfaces/rivetkit.client_mod.QueryOptions.html) - Options for querying + +_Source doc path: /docs/actors/keys_ diff --git a/.agents/skills/cron-jobs/reference/actors/kv.md b/.agents/skills/cron-jobs/reference/actors/kv.md new file mode 100644 index 0000000..384769b --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/kv.md @@ -0,0 +1,44 @@ +# Low-Level KV Storage + +> Source: `src/content/docs/actors/kv.mdx` +> Canonical URL: https://rivet.dev/docs/actors/kv +> Description: Use the built-in key-value store on ActorContext for durable string and binary data alongside actor state. + +--- +KV is deprecated. It is a low-level escape hatch kept for backward compatibility. For new actors, prefer [in-memory state](/docs/actors/state) for small serializable values or [SQLite](/docs/actors/sqlite) for larger or queryable data. + +Every Rivet Actor includes a lightweight key-value store on `c.kv`. It is useful for dynamic keys, blobs, or data that does not fit well in structured state. + +If your data has a known schema, prefer [state](/docs/actors/state). KV is best for flexible or user-defined keys. + +## Basic Usage + +Keys and values default to `text`, so you can use strings without extra options. + +## Value Types + +You can store binary values by passing `Uint8Array` or `ArrayBuffer`. Use `type` on both reads and writes to get the right value type: `binary` for `Uint8Array` and `arrayBuffer` for `ArrayBuffer`. + +TypeScript returns a concrete type based on the option you pass in: + +## Key Types + +Keys accept either `string` or `Uint8Array`. String keys are encoded as UTF-8 by default. + +When listing by prefix, you can control how keys are decoded with `keyType`. Returned keys have the prefix removed. + +If you use binary keys, set `keyType: "binary"` so the returned keys stay as `Uint8Array`. + +## Range Operations + +Use `listRange(start, end)` to read an arbitrary half-open range `[start, end)`. Use `deleteRange(start, end)` to clear that same range efficiently. + +## Batch Operations + +KV supports batch operations for efficiency. `batchPut` and `batchGet` work on raw `Uint8Array` keys and values, so encode strings before passing them in. + +## API Reference + +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - `c.kv` is available on the context + +_Source doc path: /docs/actors/kv_ diff --git a/.agents/skills/cron-jobs/reference/actors/lifecycle.md b/.agents/skills/cron-jobs/reference/actors/lifecycle.md new file mode 100644 index 0000000..89955bb --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/lifecycle.md @@ -0,0 +1,388 @@ +# Lifecycle + +> Source: `src/content/docs/actors/lifecycle.mdx` +> Canonical URL: https://rivet.dev/docs/actors/lifecycle +> Description: Learn about actor lifecycle hooks for initialization, state management, and cleanup. + +--- +# Lifecycle + +Actors follow a well-defined lifecycle with hooks at each stage. Understanding these hooks is essential for proper initialization, state management, and cleanup. + +## Lifecycle + +Actors transition through several states during their lifetime. Each transition triggers specific hooks that let you initialize resources, manage connections, and clean up state. + +``` +Loading ──Start──▶ Ready ──spawn driver──▶ Started + │ + ┌────────────────────────────────────────┤ + │ │ + │ idle timer + can_sleep │ Destroy command + ▼ ▼ + SleepGrace ─── grace window closes ──▶ Destroying + │ │ + ▼ │ + SleepFinalize ──── stop sequence ───────────┤ + ▼ + Terminated +``` + +**On Create** (runs once per actor) + +1. `onMigrate` +2. `createState` +3. `onCreate` +4. `createVars` +5. `onWake` +6. `run` (background, does not block) + +**On Destroy** + +1. `onDestroy` + +**On Wake** (after sleep, restart, or crash) + +1. `onMigrate` +2. `createVars` +3. `onWake` +4. `run` (background, does not block) + +**On Sleep** (after idle period) + +1. Wait for `run` to complete (with timeout) +2. `onSleep` + +**On Connect** (per client) + +1. `onBeforeConnect` +2. `createConnState` +3. `onConnect` + +**On Disconnect** (per client) + +1. `onDisconnect` + +**On Inbound Action Invoke** (per action call) + +1. Action handler executes + +**On Inbound Queue Publish** (per `handle.send(...)`) + +1. `queues..canPublish` (if defined) +2. Queue message is enqueued + +**On Event Subscription Request** (per subscribe request) + +1. `events..canSubscribe` (if defined) +2. Subscription is applied + +## Lifecycle Hooks + +Actor lifecycle hooks are defined as functions in the actor configuration. + +### `state` + +The `state` constant defines the initial state of the actor. See [state documentation](/docs/actors/state) for more information. + +### `onMigrate` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onMigrate` hook runs on every actor start, before `createState`, `onCreate`, `createVars`, and `onWake`. Can be async. It runs early so that database migrations are applied before any other lifecycle hook accesses the database. The second parameter is `true` when the actor is being created for the first time. + +### `createState` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `createState` function dynamically initializes state based on input. Called only once when the actor is first created. Can be async. See [state documentation](/docs/actors/state) for more information. + +### `vars` + +The `vars` constant defines ephemeral variables for the actor. These variables are not persisted and are useful for storing runtime-only data. The value for `vars` must be clonable via `structuredClone`. See [ephemeral variables documentation](/docs/actors/state#ephemeral-variables) for more information. + +### `createVars` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `createVars` function dynamically initializes ephemeral variables. Can be async. Use this when you need to initialize values at runtime. See [ephemeral variables documentation](/docs/actors/state#ephemeral-variables) for more information. + +### `onCreate` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onCreate` hook is called when the actor is first created. Can be async. Use this hook for initialization logic that doesn't affect the initial state. + +### `onDestroy` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onDestroy` hook is called when the actor is being permanently destroyed. Can be async. Use this for final cleanup operations like closing external connections, releasing resources, or performing any last-minute state persistence. + +The actor is still fully functional when `onDestroy` runs. You can access the database, broadcast events, call `waitUntil`, send queue messages, and use `schedule.after`. State mutations made during `onDestroy` are persisted before the actor is torn down. + +### `onWake` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +This hook is called any time the actor is started (e.g. after restarting, upgrading code, or crashing). Can be async. + +This is called after the actor has been initialized but before any connections are accepted. + +Use this hook to set up any resources or start any background tasks, such as `setInterval`. + +### `onSleep` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +This hook is called when the actor is going to sleep. Can be async. Use this to clean up resources, close connections, or perform any shutdown operations. + +The actor is still fully functional when `onSleep` runs. You can access the database, broadcast events, call `waitUntil`, send queue messages, and use `schedule.after`. State mutations made during `onSleep` are persisted before the actor finishes sleeping. + +This hook may not always be called in situations like crashes or forced terminations. Don't rely on it for critical cleanup operations. + +Not supported on Cloudflare Workers. + +### `run` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `run` hook is called after the actor starts and runs in the background without blocking actor startup. This is ideal for long-running background tasks like: + +- Reading from message queues in a loop +- Tick loops for periodic work +- Custom workflow logic +- Background processing + +The handler exposes `c.aborted` for loop checks and `c.abortSignal` for canceling operations when the actor is stopping. You should always check or listen for shutdown to exit gracefully. + +**Important behavior:** +- The actor may go to sleep at any time during the `run` handler. Wrap work that must keep the actor awake with `c.keepAwake(promise)` to block idle sleep until the promise settles. +- If the `run` handler exits (returns), the actor follows its normal idle sleep timeout once it becomes idle +- If the `run` handler throws an error, the actor logs the error and then follows its normal idle sleep timeout once it becomes idle +- On shutdown, `c.abortSignal` fires so the `run` handler can exit within the graceful shutdown window. + +Finite `run` handlers leave the actor alive after they finish. If you want a one shot task to clean itself up when it is done, call `c.destroy()` before returning. + +### `onStateChange` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Called whenever the actor's state changes. Cannot be async. This is often used to broadcast state updates. + +Do not mutate `c.state` inside `onStateChange`; re-entrant state mutation is rejected. + +### `createConnState` and `connState` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +There are two ways to define the initial state for connections: +1. `connState`: Define a constant object that will be used as the initial state for all connections +2. `createConnState`: A function that dynamically creates initial connection state based on connection parameters. Can be async. + +### `onBeforeConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.BeforeConnectContext.html) + +The `onBeforeConnect` hook is called whenever a new client connects to the actor. Can be async. Clients can pass parameters when connecting, accessible via `params`. This hook is used for connection validation and can throw errors to reject connections. + +The `onBeforeConnect` hook does NOT return connection state - it's used solely for validation. + +Connections cannot interact with the actor until this method completes successfully. Throwing an error will abort the connection. This can be used for authentication - see [Authentication](/docs/actors/authentication) for details. + +### `onConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ConnectContext.html) + +Executed after the client has successfully connected. Can be async. Receives the connection object as a second parameter. + +Messages will not be processed for this actor until this hook succeeds. Errors thrown from this hook will cause the client to disconnect. + +### `canPublish` and `canSubscribe` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Use schema-level hooks to authorize queue publishes and event subscriptions. Both hooks can be async and must return booleans: + +- `queues..canPublish` runs before inbound queue publishes. +- `events..canSubscribe` runs before inbound event subscription requests. + +For actions, enforce authorization directly inside each action handler. + +Use deny-by-default rules for each hook and return `false` unless explicitly allowed. See [Access Control](/docs/actors/access-control) for full guidance. + +### `onDisconnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Called when a client disconnects from the actor. Can be async. Receives the connection object as a second parameter. Use this to clean up any connection-specific resources. + +### `onRequest` + +[API Reference](/typedoc/interfaces/rivetkit.mod.RequestContext.html) + +The `onRequest` hook handles HTTP requests sent to your actor at `/actors/{actorName}/http/*` endpoints. Can be async. It receives the request context and a standard `Request` object, and should return a `Response` object. + +See [Request Handler](/docs/actors/request-handler) for more details. + +### `onWebSocket` + +[API Reference](/typedoc/interfaces/rivetkit.mod.WebSocketContext.html) + +The `onWebSocket` hook handles WebSocket connections to your actor. Can be async. It receives the actor context and a `WebSocket` object. Use this to set up WebSocket event listeners and handle real-time communication. + +See [WebSocket Handler](/docs/actors/websocket-handler) for more details. + +### `onBeforeActionResponse` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onBeforeActionResponse` hook is called before sending an action response to the client. Can be async. Use this hook to modify or transform the output of an action before it's sent to the client. This is useful for formatting responses, adding metadata, or applying transformations to the output. + +## Sleeping + +Actors automatically sleep after a period of inactivity to free up resources. When a request arrives for a sleeping actor, it wakes up, restores its state, and handles the request. + +### When Actors Sleep + +#### Idle Timeout + +An actor is considered idle and eligible to sleep when **all** of the following are true: + +- No active HTTP requests +- No active connections (unless they are hibernatable WebSockets) +- No active `run` handler (unless it is waiting on a queue) +- No outstanding `c.keepAwake(promise)` promises +- No pending disconnect callbacks +- No async `onWebSocket` event handlers (eg `open`, `message`, `close`) still running + +Once the actor becomes idle, the sleep timer starts. After `sleepTimeout` (default 30 seconds) of continuous inactivity, the actor begins the sleep process. Any activity resets the timer. + +Outbound requests (e.g. `fetch` calls) do not count as activity and will not keep the actor awake. Wrap them with `c.waitUntil()` if they must complete before the actor sleeps. + +#### Upgrades & Eviction + +The platform may force an actor to migrate to a new machine during version upgrades or when a serverless request is about to timeout. The same [shutdown sequence](#shutdown-sequence) runs, then the actor is rescheduled on a new machine and wakes up with its persisted state. + +Use `onSleep`, `waitUntil`, or `keepAwake` to control the length of the grace period before the actor moves to another machine. + +### Manual Lifecycle Controls + +You can also trigger lifecycle transitions from the Rivet Cloud API. These endpoints are useful for operational workflows, debugging, and forcing an actor to move through the same sleep or reschedule path that the platform would normally trigger. + +```bash +curl -X POST \ + "https://cloud-api.rivet.dev/actors/$ACTOR_ID/sleep?namespace=$NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{}' +``` + +```bash +curl -X POST \ + "https://cloud-api.rivet.dev/actors/$ACTOR_ID/reschedule?namespace=$NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{}' +``` + +`/sleep` asks the actor to enter the normal sleep shutdown sequence. `/reschedule` asks the platform to allocate the actor again, which is useful after crashes or when you need to force a fresh placement. Both endpoints require the actor ID and namespace. + +### Skip Ready Wait + +The gateway normally holds requests until the actor is ready. The actor is not ready during startup (before `onWake` finishes) or during the sleep grace period (while `onSleep` and `waitUntil` are running). Probes and readiness checks can opt out with `skipReadyWait` to reach the actor's `onRequest` or `onWebSocket` handler in either window. + +See [Skip Ready Wait](/docs/clients/javascript#skip-ready-wait) on the JavaScript client page for usage. + +### Keeping the Actor Awake + +RivetKit gives you two primitives for holding the actor awake across background work. Both take a `Promise` and differ in how they interact with idle sleep and the grace period. + +| Method | Accepts | Blocks idle sleep | Blocks grace finalize | Use case | +| --- | --- | --- | --- | --- | +| `c.keepAwake(promise)` | `Promise` (returns same promise) | Yes | Yes | Critical work that must keep the actor running end to end (for example a turn in a game, an ongoing tool call). | +| `c.waitUntil(promise)` | `Promise` (returns void) | No | Yes | Best-effort finalization work that may complete during the grace window (for example analytics flushes, cleanup writes). | + +`c.keepAwake(promise)` is the preferred primitive for long-running work the actor should not sleep through. It holds a keep-awake counter until the promise settles, which blocks both idle sleep and the grace finalize step. The promise is returned unchanged, so you can `await` it if you need the value. + +`setPreventSleep(enabled)` is deprecated and now a no-op. Wrap the work you want to keep alive with `c.keepAwake(promise)` instead. + +### On Sleep Hook + +The [`onSleep`](#onsleep) hook runs during shutdown for cleanup like clearing intervals or closing connections. It is best-effort and will not run if the actor crashes. + +### Wait Before Sleep + +`c.waitUntil(promise)` registers a background promise that must resolve before the actor finishes sleeping. Use this to flush data or finish in-flight work during shutdown without blocking the main execution flow. + +The actor waits up to `sleepGracePeriod` for graceful sleep work during the [shutdown sequence](#shutdown-sequence). That single budget covers `onSleep`, `waitUntil`, `keepAwake`, async raw WebSocket handlers such as `message` and `close`. By default, this graceful sleep window is 15 seconds total. If the timeout is exceeded, the actor proceeds with sleep anyway. + +### Sleep Timeouts + +| Option | Default | Description | +|--------|---------|-------------| +| `sleepTimeout` | 30 seconds | Time of inactivity before the actor begins sleeping. | +| `sleepGracePeriod` | 15 seconds | Total graceful shutdown window for hooks, `waitUntil`, `keepAwake`, async raw WebSocket handlers, and disconnects. | + +Rivet enforces a hard limit of **30 minutes** for the entire stop process. These can be configured in the [options](#options). + +### WebSocket Hibernation + +WebSocket connections are preserved across sleep cycles by default and transparently migrated to the new actor instance. Client stays connected and sees no interruption. Actor migration is very fast, realtime workloads are not interrupted. + +### Shutdown Sequence + +When an actor sleeps or is destroyed, it enters the graceful shutdown window: + +1. `c.abortSignal` fires and `c.aborted` becomes `true`. New connections and dispatch are rejected. Alarm timeouts are cancelled. On sleep, scheduled events are persisted and will be re-armed when the actor wakes. +2. `onSleep` or `onDestroy` and `onDisconnect` for each closing connection run during the same window. User `waitUntil` promises and async raw WebSocket handlers are drained. Hibernatable WebSocket connections are preserved on sleep and closed on destroy. +3. Once graceful work has completed, state is saved and final cleanup runs. + +The entire window is bounded by `sleepGracePeriod` on both sleep and destroy. Defaults to 15 seconds. If the window is exceeded, the actor proceeds to state save anyway. + +#### Graceful shutdown window + +During steps 1 through 6, the actor is still fully functional. Database access, `broadcast`, `waitUntil`, `queue.send`, and `schedule.after` all work. State mutations are persisted at step 7. Actions invoked by pre-existing connections or lifecycle hooks continue to execute normally. + +New connections and raw WebSocket upgrades are rejected as soon as the shutdown sequence begins. New requests that arrive during shutdown are held until the actor wakes up again. The caller does not need to retry. + +If `schedule.after` is called during shutdown, the event is persisted so it survives the sleep/wake cycle, but no local timeout is scheduled. The event will fire after the actor wakes. + +In-flight actions are **not** waited on during shutdown. If an action must complete before the actor stops, wrap the critical work with `c.waitUntil()`. + +## Options + +The `options` object allows you to configure various timeouts and behaviors for your actor. + +| Option | Default | Description | +|--------|---------|-------------| +| `createVarsTimeout` | 5000ms | Timeout for `createVars` function | +| `createConnStateTimeout` | 5000ms | Timeout for `createConnState` function | +| `onConnectTimeout` | 5000ms | Timeout for `onConnect` hook | +| `sleepGracePeriod` | 15000ms | Total graceful shutdown window for both sleep and destroy | +| `stateSaveInterval` | 1000ms | Interval for persisting state | +| `actionTimeout` | 60000ms | Timeout for action execution | +| `connectionLivenessTimeout` | 2500ms | Timeout for connection liveness check | +| `connectionLivenessInterval` | 5000ms | Interval for connection liveness check | +| `sleepTimeout` | 30000ms | Time before actor sleeps due to inactivity | +| `canHibernateWebSocket` | false | Whether WebSockets can hibernate (experimental) | + +## Advanced + +### Actor Shutdown Abort Signal + +The `c.abortSignal` provides an `AbortSignal` that fires when the actor is stopping, and `c.aborted` is the shorthand boolean for loop checks. Use these to cancel ongoing operations when the actor sleeps or is destroyed. + +The abort signal fires at the very start of the [shutdown sequence](#shutdown-sequence), before `onSleep` or `onDestroy` runs. This means `c.aborted` is already `true` inside those lifecycle hooks. The signal fires early so that the `run` handler can exit promptly, but the actor remains fully functional throughout the graceful shutdown window. + +See [Canceling Long-Running Actions](/docs/actors/actions#canceling-long-running-actions) for manually canceling operations on-demand. + +### Using `ActorContext` Type Externally + +When extracting logic from lifecycle hooks or actions into external functions, you'll often need to define the type of the context parameter. Rivet provides helper types that make it easy to extract and pass these context types to external functions. + +See [Types](/docs/actors/types) for more details on using `ActorContextOf`. + +## Full Example + +_Source doc path: /docs/actors/lifecycle_ diff --git a/.agents/skills/cron-jobs/reference/actors/limits.md b/.agents/skills/cron-jobs/reference/actors/limits.md new file mode 100644 index 0000000..57d7194 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/limits.md @@ -0,0 +1,169 @@ +# Limits + +> Source: `src/content/docs/actors/limits.mdx` +> Canonical URL: https://rivet.dev/docs/actors/limits +> Description: Limits and constraints for Rivet Actors. + +--- +This page documents the limits for Rivet Actors. + +There are two types of limits: + +- **Soft Limit**: Application-level limit, configurable in RivetKit. These cannot exceed the hard limit. +- **Hard Limit**: Infrastructure-level limit that cannot be configured. + +Soft limits are configured in two places. Registry-level WebSocket message-size limits are passed to `setup`: + +Per-actor limits such as queue sizes and lifecycle timeouts are passed to `actor(...)` via `options`: + +## Limits + +### WebSocket + +These limits affect actions that use `.connect()` and [low-level WebSockets](/docs/actors/websocket-handler). + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max incoming message size | 64 KiB | 32 MiB | Maximum size of incoming WebSocket messages. Soft limit configurable via `maxIncomingMessageSize`; hard limit configurable in self-hosted engine config via `guard.websocket_max_message_size`. | +| Max outgoing message size | 1 MiB | 32 MiB | Maximum size of outgoing WebSocket messages. Soft limit configurable via `maxOutgoingMessageSize`; hard limit configurable in self-hosted engine config via `guard.websocket_max_message_size`. | +| Max WebSocket frame size | — | 32 MiB | Maximum size of a single WebSocket frame accepted by Rivet's transport edge. Configurable in self-hosted engine config via `guard.websocket_max_frame_size`. This is not configurable by browser clients and is not negotiated during the WebSocket handshake. | +| WebSocket open timeout | — | 15 seconds | Time allowed for WebSocket connection to be established, including `onBeforeConnect` and `createConnState` hooks. Connection is closed if exceeded. | +| Message ack timeout | — | 30 seconds | Time allowed for message acknowledgment before connection is closed. Only relevant in the case of a network issue and does not affect your application. | + +### Hibernating WebSocket + +Hibernating WebSockets allow actors to sleep while keeping client connections alive. All WebSocket limits above also apply to hibernating WebSockets. See [WebSocket Hibernation](/docs/actors/websocket-handler#web-socket-hibernation) for details. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max pending buffer size | — | 128 MiB | Total size of all buffered messages per connection while actor is sleeping. | +| Max pending message count | — | 65,535 | Maximum number of buffered messages per connection while actor is sleeping. | +| Hibernation timeout | — | 90 seconds | Maximum time an actor has to wake up before the client is disconnected. Only relevant if something is wrong with starting actors. | + +### HTTP + +These limits affect actions that do not use `.connect()` and [low-level HTTP requests](/docs/actors/request-handler). + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max request body size | — | 20 MiB | Maximum size of HTTP request bodies. | +| Max response body size | — | 20 MiB | Maximum size of HTTP response bodies. | +| Request timeout | 60 seconds | — | Maximum time for an `onRequest` handler to complete. Defaults to `actionTimeout`; configure with `actionTimeout`. | + +### Networking + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Connection ping timeout | — | 30 seconds | Connection is closed if a ping is not acknowledged within this time. Applies to both HTTP and WebSocket. Only relevant in the case of a network issue and does not affect your application. | + +### Queue + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max queue size | 1,000 messages | — | Maximum number of messages in the queue before new messages are rejected. Configurable via `maxQueueSize`. | +| Max queue message size | 64 KiB | 128 KiB (effective) | Maximum size of each individual queue message. Configurable via `maxQueueMessageSize`. Actual payload is slightly lower after queue serialization overhead. | + +### Actor KV Storage + +These limits apply to the low-level KV storage interface powering Rivet Actors. They likely do not affect your application, but are documented for completeness. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max key size | — | 2 KiB | Maximum size of a single key. | +| Max value size | — | 128 KiB | Maximum size of a single value. | +| Max keys per operation | — | 128 | Maximum number of keys in a single batch get/put/delete operation. Does not apply to range operations (`listRange`, `deleteRange`). | +| Max batch put payload size | — | 976 KiB | Maximum total size of all key-value pairs in a single batch put operation. | +| Max storage size per actor | — | 10 GiB | Maximum total KV storage size for a single actor. | +| List default limit | — | 16,384 | Default maximum number of keys returned by a list operation. | + +### Actor SQLite Storage + +These limits apply to the [SQLite database](/docs/actors/state#sqlite-database) available via `this.sql`. SQLite data is stored through the KV layer, so the storage limit is shared with KV storage. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max storage size per actor | — | 10 GiB | Maximum total storage size for a single actor. This limit is shared with KV storage. | +| Max dirty data per commit | — | 1,310,720 bytes | Maximum raw SQLite page data that can be written in a single commit. This is 320 dirty pages at 4 KiB per page. | +| Transaction deadline | 60 seconds | — | Safety backstop for `db.transaction()`. Configure per transaction with `{ timeout: milliseconds }`; there is no product-level maximum. | +| Transaction coordinator queue | — | 128 operations | Maximum admitted SQLite operations waiting behind an active coordinated transaction. Additional operations fail with `sqlite.transaction_queue_full`. | + +SQLite commit deltas are compressed and split into internal chunks before storage, but all chunks for one commit are published atomically. The commit limit is therefore based on raw dirty page bytes before compression, not the compressed delta size. + +Avoid `VACUUM` inside actor databases. It rewrites the database in one transaction and can exceed the dirty-page commit limit even when ordinary incremental writes fit. + +### Actor Runtime Socket + +The experimental [Actor Runtime Socket](/docs/actors/actor-runtime-socket) negotiates its active frame limit during the handshake. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Frame payload size | 32 MiB | — | Default maximum request or response payload. Self-hosted native runtimes can configure `RIVET_ACTOR_RUNTIME_SOCKET_MAX_FRAME_BYTES`; oversized responses return `ResponseTooLarge`. | + +### KV Preloading + +When an actor starts, the engine can pre-fetch KV data declared in the actor name metadata and deliver it alongside the start command. This removes round-trips to storage during actor startup. RivetKit emits the preload manifest from its own key layout and exposes per-actor overrides via `options`. Operators can still enforce a global cap in the [engine config](/docs/self-hosting/configuration) with `pegboard.preload_max_total_bytes`. In serverless mode, this data is serialized into the `/api/rivet/start` request body along with actor config and protocol metadata, so the accepted body size must be larger than the preload budget. RivetKit defaults `serverless.maxStartPayloadBytes` to 16 MiB to leave margin for the default 1 MiB preload budget and larger SQLite startup page preloads. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max total preload size | 1 MiB | — | Maximum total size of all preloaded KV data sent with the start command. Configurable via `pegboard.preload_max_total_bytes`. Setting to 0 disables all preloading. | +| Max workflow preload size | 128 KiB | — | Default maximum size of preloaded workflow data for RivetKit actors. Configurable per actor via `options.preloadMaxWorkflowBytes`. Setting to 0 disables workflow preloading for that actor. | +| Max connections preload size | 64 KiB | — | Default maximum size of preloaded connection data for RivetKit actors. Configurable per actor via `options.preloadMaxConnectionsBytes`. Setting to 0 disables connections preloading for that actor. | + +### Actor Input + +See [Actor Input](/docs/actors/input) for details. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max actor input size | — | 4 MiB | Maximum size of the input passed when creating an actor. | +| Max connection params size | — | 4 KiB | Maximum size of connection parameters passed when connecting to an actor. | +| Max actor key component size | — | 128 bytes | Maximum size of each component in an actor key array. | +| Max actor key total size | — | 1,024 bytes | Maximum total size of the serialized actor key string. | +| Max actor name length | — | 64 characters | Maximum length for actor and project identifiers. | + +### Rate Limiting + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Rate limit | — | 1200 requests/minute | Default rate limit per actor per IP address with a 1 minute time bucket. | +| Max in-flight requests | — | 32 | Default maximum concurrent requests to an actor per IP address. | + +### Timeouts + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Action timeout | 60 seconds | — | Timeout for RPC actions. Configurable via `actionTimeout`. | +| On request timeout | 60 seconds | — | Timeout for raw `onRequest` handlers. Defaults to `actionTimeout`; configure with `actionTimeout`. | +| On before connect timeout | 5 seconds | — | Timeout for the `onBeforeConnect` hook. Configurable via `onBeforeConnectTimeout`. | +| Create vars timeout | 5 seconds | — | Timeout for `createVars` hook. Configurable via `createVarsTimeout`. | +| Create conn state timeout | 5 seconds | — | Timeout for `createConnState` hook. Configurable via `createConnStateTimeout`. | +| On connect timeout | 5 seconds | — | Timeout for `onConnect` hook. Configurable via `onConnectTimeout`. | +| On migrate timeout | 30 seconds | — | Timeout for `onMigrate` hook. Configurable via `onMigrateTimeout`. | +| Sleep grace period | 15 seconds | — | Total graceful shutdown budget for both sleep and destroy. Covers `onSleep`/`onDestroy`, run handler shutdown, `waitUntil`, `keepAwake`, async raw WebSocket handlers, and connection cleanup. Configurable via `sleepGracePeriod`. | +| Sleep timeout | 30 seconds | — | Time of inactivity before actor hibernates. Configurable via `sleepTimeout`. | +| State save interval | 1 second | — | Interval between automatic state saves. Configurable via `stateSaveInterval`. | +| Connection liveness timeout | 2.5 seconds | — | Time a stateful connection can miss liveness checks before RivetKit treats it as unhealthy. Configurable via `connectionLivenessTimeout`. | +| Connection liveness interval | 5 seconds | — | Interval between stateful connection liveness checks. Configurable via `connectionLivenessInterval`. | + +### Serverless Shutdown + +These timeouts control how actors are shut down when a serverless request reaches its lifespan limit. See [Shutdown Sequence](/docs/general/runtime-modes#shutdown-sequence) for details. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Request lifespan | 3600 seconds (60 min) | — | Total lifespan of a serverless request before drain begins. Configurable via `requestLifespan` in [`configurePool`](/docs/general/registry-configuration). | +| Runner config drain grace period | — | 30 minutes | Time a serverless runner reserves for actors to stop gracefully. Configurable via `drainGracePeriod` in [`configurePool`](/docs/general/registry-configuration). | +| Engine serverless drain fallback | — | 10 seconds | Engine-level fallback used when no per-runner config applies. Configurable via [engine config](/docs/self-hosting/configuration) (`pegboard.serverless_drain_grace_period`). | + +### Actor Lifecycle + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Actor start threshold | — | 30 seconds | Maximum time for an actor to start before it is considered lost and rescheduled. | +| Actor stop threshold | — | 30 minutes | Maximum time for an actor to stop before it is considered lost. | + +## Increasing Limits + +These limits are sane defaults designed to protect your application from exploits and accidental runaway bugs. If you have a use case that requires different limits, [contact us](https://rivet.dev/contact) to discuss your requirements. + +_Source doc path: /docs/actors/limits_ diff --git a/.agents/skills/cron-jobs/reference/actors/metadata.md b/.agents/skills/cron-jobs/reference/actors/metadata.md new file mode 100644 index 0000000..d3dcc24 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/metadata.md @@ -0,0 +1,39 @@ +# Metadata + +> Source: `src/content/docs/actors/metadata.mdx` +> Canonical URL: https://rivet.dev/docs/actors/metadata +> Description: Metadata provides information about the currently running actor. + +--- +## Actor ID + +Get the unique instance ID of the actor: + +## Actor Name + +Get the actor type name: + +This is useful when you need to know which actor type is running, especially if you have generic utility functions that are shared between different actor implementations. + +## Actor Key + +Get the actor key used to identify this actor instance: + +The key is used to route requests to the correct actor instance and can include parameters passed when creating the actor. + +Learn more about using keys for actor addressing and configuration in the [keys documentation](/docs/actors/keys). + +## Region + +Region can be accessed from the context object via `c.region`. + +`c.region` is only supported on Rivet at the moment. + +## Example Usage + +## API Reference + +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining metadata +- [`CreateOptions`](/typedoc/interfaces/rivetkit.client_mod.CreateOptions.html) - Options for creating an actor, including `region` and `input` + +_Source doc path: /docs/actors/metadata_ diff --git a/.agents/skills/cron-jobs/reference/actors/queues.md b/.agents/skills/cron-jobs/reference/actors/queues.md new file mode 100644 index 0000000..8ebeb7b --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/queues.md @@ -0,0 +1,122 @@ +# Queues & Run Loops + +> Source: `src/content/docs/actors/queues.mdx` +> Canonical URL: https://rivet.dev/docs/actors/queues +> Description: Use actor-local durable queues for serial run loops and request/response workflows. + +--- +## What are queues? + +- **Realtime**: messages are delivered to a live actor as soon as possible. +- **Durable**: messages are persisted and survive actor sleep/restart. +- **Request/response**: clients can wait for a queue completion response. +- **Scalable**: queues absorb large bursts and handle heavy backpressure safely. +- **Local per actor**: each actor instance has its own queue storage (scoped by actor key/id). + +Queues are commonly referred to as "mailboxes" in other actor frameworks. + +For a worked queue-driven pattern, see the cookbook: [AI Agent](/cookbook/ai-agent/). + +## What are queues good for? + +- Great for any task that changes actor state. +- Helps avoid race conditions by handling work in order. +- Makes complex behavior easier to organize. + +## Basic queue + +This is the default pattern. Define queue names in `queues`, process them in `run`, and publish from the client with `handle.send(...)`. + +## Completable messages + +Use this when you want explicit completion/ack semantics but do not need to return data. + +- `message.complete()` resolves a sender waiting on `wait: true` (or `enqueueAndWait`). It does not change durability: messages are removed from queue storage when they are received, not when they are completed. +- If processing fails before `message.complete()`, the message is not redelivered, and any waiting sender times out instead of receiving a completion. +- `status: "timedOut"` means sender timeout elapsed before `message.complete(...)`. + +## Request/reply pattern + +Use this when the sender needs data back from queued work. + +## Queue messages from within an actor + +Queueing is useful from inside actor logic too, not just from clients. + +- Use actions as entrypoints, then enqueue into the run loop to keep mutations serialized. +- You can also call `c.queue.send(...)` from other parts of `run` when needed. +- `c.queue.send(...)` confirms durable enqueue. It does not wait for processing to finish. + +## Defining queue schemas + +You can define queue types with `queue()` or with schema objects. Schema objects support [Standard Schema](https://standardschema.dev/) validators, including [Zod](https://zod.dev/). + +## Pull messages with `next` and `nextBatch` + +Use `next` when you want to wait for one queue message. +Use `nextBatch` when you want to wait for multiple queue messages. + +- Waits until messages are available unless timeout is hit. +- Omit `timeout` to wait indefinitely. + +## Poll messages + +Use `tryNext` when you need one non-blocking read. +Use `tryNextBatch` for non-blocking batch reads. + +- Returns immediately and never waits. + +## Abort signals + +Use `signal` when your receive loop needs external cancellation semantics in addition to actor shutdown behavior. + +## Multiple queues + +Multiple queues let you separate message flows by purpose. By default, receive calls race across all queues when `names` is not specified. In this pattern, prompt messages run through a streaming loop while stop messages act as control signals on a separate receive path. + +Use `iter({ names: ["prompt"] })` as the main stream and `next({ names: ["stop"] })` as a stop signal. + +## Sleeping behavior + +If an actor has a `run` handler, it does not sleep while that handler is actively doing work. It only can sleep when the run loop is blocked waiting for queue entries (for example inside `iter(...)` or `next(...)`). + +This means you can run normal code in `run` without worrying about sleep interrupting it mid-call. + +## Debugging + +- `GET /inspector/queue?limit=50` returns queue size and pending message metadata. +- `GET /inspector/summary` includes `queueSize` for quick queue health checks. +- `POST /queue/:name` with `wait: true` is useful to verify completable/request-response behavior. +- In non-dev mode, inspector endpoints require authorization. + +## Recommendations + +- Actions are for getting data, queue entries are for mutating data. +- Implement connection auth in `onBeforeConnect`. See [Authentication](/docs/actors/authentication). +- Route most state changes through one queue loop so ordering stays predictable. +- If you need more complex multi-step run loops, consider using workflows. +- Use `c.aborted` and `c.abortSignal` for actor shutdown. Use your own `AbortController` for earlier loop cancellation. +- Add `timeout` when callers need bounded wait behavior. +- Use `wait: true` only when the caller actually needs a response. + +## Pitfalls + +### Avoid `wait: true` between actors + +`wait: true` blocks the sender's run loop until the receiver finishes. Between actors, this adds unnecessary overhead and risks deadlocks, especially if the target actor needs to communicate back. If an actor sends a `wait: true` message to *itself*, it is a guaranteed deadlock because the run loop is already busy processing the current message. + +Reserve `wait: true` for external callers (HTTP handlers, CLI tools, client apps). For actor-to-actor communication, send a queue message to the other actor without `wait: true`, then have that actor send a queue message back when the work is done. + +## Tips + +### Message TTL + +Every queue message includes a `createdAt` timestamp. Use this to skip or discard stale messages in your run loop: + +### Delayed delivery + +Use [`c.schedule`](/docs/actors/schedule) to enqueue messages at a future time instead of processing them immediately: + +See [Schedule](/docs/actors/schedule) for the full scheduling API. + +_Source doc path: /docs/actors/queues_ diff --git a/.agents/skills/cron-jobs/reference/actors/quickstart/backend.md b/.agents/skills/cron-jobs/reference/actors/quickstart/backend.md new file mode 100644 index 0000000..86cbdf2 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/quickstart/backend.md @@ -0,0 +1,64 @@ +# Node.js & Bun Quickstart + +> Source: `src/content/docs/actors/quickstart/backend.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/backend +> Description: Get started with Rivet Actors in Node.js and Bun + +--- +Prefer to start from a complete project? See the runnable [`hello-world`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world) example. + +## Steps + +### Add Rivet Skill to Coding Agent (Optional) + +If you're using an AI coding assistant (like Claude Code, Cursor, Windsurf, etc.), add Rivet skills for enhanced development assistance: + +```sh +npx skills add rivet-dev/skills +``` + +### Install Rivet + +```sh +npm install rivetkit +``` + +### Create Actors and Start Server + +Create a file with your actors, set up the registry, and start the server: + +### Run Server + +```sh Node.js +npx tsx --watch index.ts +``` + +```sh Bun +bun --watch index.ts +``` + +```sh Deno +deno run --allow-net --allow-read --allow-env --watch index.ts +``` + +Your server is now running on `http://localhost:6420`. Clients connect directly to the Rivet Engine on this port. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend: + +### TypeScript + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### React + +See the [React documentation](/docs/clients/react) for more information. + +### Deploy + +## Configuration Options + +_Source doc path: /docs/actors/quickstart/backend_ diff --git a/.agents/skills/cron-jobs/reference/actors/quickstart/cloudflare.md b/.agents/skills/cron-jobs/reference/actors/quickstart/cloudflare.md new file mode 100644 index 0000000..e39cbe4 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/quickstart/cloudflare.md @@ -0,0 +1,165 @@ +# Cloudflare Workers Quickstart + +> Source: `src/content/docs/actors/quickstart/cloudflare.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/cloudflare +> Description: Set up a Rivet project locally targeting Cloudflare Workers. + +--- +Set up a Rivet project locally that runs on Cloudflare Workers. The `@rivetkit/cloudflare-workers` package wires the WebAssembly runtime for you. + +Prefer to start from a complete project? See the runnable [`hello-world-cloudflare-workers`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-cloudflare-workers) example (with [Hono](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-cloudflare-workers-hono) and [raw router](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-cloudflare-workers-raw) variants). + +## Steps + +### Install Packages + +```sh +npm install rivetkit @rivetkit/cloudflare-workers +npm install --save-dev wrangler +``` + +### Configure Wrangler + +```toml wrangler.toml +name = "rivetkit-cloudflare" +main = "src/index.ts" +compatibility_date = "2025-04-01" +compatibility_flags = ["nodejs_compat"] +``` + +The `nodejs_compat` flag is required so the runtime can read its connection config from `process.env`. + +### Create the Worker + +`createHandler` serves the Rivet manager API on `/api/rivet`. Pick how you want to handle your own routes: + +- **Default**: Rivet handles everything. +- **Hono**: Mount a [Hono](https://hono.dev) app for your routes (`npm install hono`). +- **Raw**: Provide a `fetch` and route requests yourself. + +```ts Default @nocheck +import { actor } from "rivetkit"; +import { createHandler } from "@rivetkit/cloudflare-workers"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +export default createHandler({ use: { counter } }); +``` + +```ts Hono @nocheck +import { actor } from "rivetkit"; +import { createClient } from "rivetkit/client"; +import { createHandler, setup } from "@rivetkit/cloudflare-workers"; +import { Hono } from "hono"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +// `setup` returns a typed registry, so the client below is fully typed. +const registry = setup({ use: { counter } }); + +const app = new Hono(); + +app.get("/", (c) => c.text("Hello from Hono + Rivet Actors!")); + +app.post("/increment/:name", async (c) => { + // `createClient` reads RIVET_ENDPOINT from the environment (passed by `rivet + // dev`, or set as a Worker secret in production). + const client = createClient(); + const count = await client.counter.getOrCreate(c.req.param("name")).increment(1); + return c.json({ count }); +}); + +// Rivet keeps `/api/rivet`; Hono handles everything else. +export default createHandler(registry, { fetch: app.fetch }); +``` + +```ts Raw @nocheck +import { actor } from "rivetkit"; +import { createClient } from "rivetkit/client"; +import { createHandler, setup } from "@rivetkit/cloudflare-workers"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +// `setup` returns a typed registry, so the client below is fully typed. +const registry = setup({ use: { counter } }); + +// Rivet keeps `/api/rivet`; your `fetch` handles everything else. +export default createHandler(registry, { + fetch: async (request: Request) => { + const url = new URL(request.url); + + if (url.pathname === "/") { + return new Response("Hello from a raw Rivet Worker router!"); + } + + const increment = url.pathname.match(/^\/increment\/(.+)$/); + if (request.method === "POST" && increment) { + // `createClient` reads RIVET_ENDPOINT from the environment (passed by + // `rivet dev`, or set as a Worker secret in production). + const client = createClient(); + const count = await client.counter.getOrCreate(increment[1]).increment(1); + return Response.json({ count }); + } + + return new Response("Not found", { status: 404 }); + }, +}); +``` + +### Run Locally + +Start Rivet. The CLI runs the local engine and spawns `wrangler dev` for you: + +```sh +npx @rivetkit/cli dev --provider cloudflare +``` + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend. It connects directly to the local engine on `http://localhost:6420`: + +### TypeScript + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### React + +See the [React documentation](/docs/clients/react) for more information. + +### Deploy + +Ready to ship? See [Deploying to Cloudflare Workers](/docs/deploy/cloudflare). + +## Related + +- [Quickstart](/docs/actors/quickstart) +- [Deploying to Cloudflare Workers](/docs/deploy/cloudflare) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/actors/quickstart/cloudflare_ diff --git a/.agents/skills/cron-jobs/reference/actors/quickstart/effect.md b/.agents/skills/cron-jobs/reference/actors/quickstart/effect.md new file mode 100644 index 0000000..fc252e9 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/quickstart/effect.md @@ -0,0 +1,239 @@ +# Effect.ts Quickstart (Beta) + +> Source: `src/content/docs/actors/quickstart/effect.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/effect +> Description: Build a Rivet Actor with the Effect SDK + +--- +Effect support is in beta. The `@rivetkit/effect` API may change between releases. See the [`hello-world-effect`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-effect) and [`chat-room-effect`](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room-effect) examples for complete runnable projects. + +## Steps + +### Install Rivet + +Add `rivetkit`, the Effect SDK, and its Effect peers: + +```sh +npm install rivetkit @rivetkit/effect effect @effect/platform-node +``` + +### Define Your Actor + +Split each actor into a public contract and a server-only implementation so the contract can be imported from client code without leaking server details. + +The contract declares the actor and its actions. Actions are standalone values with explicit [`effect/Schema`](https://effect.website/docs/schema/introduction/) payloads and successes, validated end to end: + +```ts src/actors/counter/api.ts @nocheck +import { Action, Actor } from "@rivetkit/effect"; +import { Schema } from "effect"; + +export const Increment = Action.make("Increment", { + payload: { amount: Schema.Number }, + success: Schema.Number, +}); + +export const GetCount = Action.make("GetCount", { + success: Schema.Number, +}); + +export const Counter = Actor.make("Counter", { + actions: [Increment, GetCount], +}); +``` + +The implementation registers the actor with `.toLayer`. The wake function runs once when the actor awakes and returns the action handlers. Persisted state is accessed through a `SubscriptionRef`-like `State` API: + +```ts src/actors/counter/live.ts @nocheck +import { Actor, State } from "@rivetkit/effect"; +import { Effect, Schema } from "effect"; +import { Counter } from "./api.ts"; + +export const CounterLive = Counter.toLayer( + Effect.fnUntraced(function* ({ rawRivetkitContext, state }) { + return Counter.of({ + Increment: Effect.fnUntraced(function* ({ payload }) { + const next = yield* State.updateAndGet(state, (current) => ({ + count: current.count + payload.amount, + })).pipe(Effect.orDie); + + // Broadcast the new value to every connected client. + rawRivetkitContext.broadcast("newCount", next.count); + + return next.count; + }), + GetCount: () => + State.get(state).pipe( + Effect.map((current) => current.count), + Effect.orDie, + ), + }); + }), + { + state: { + schema: Schema.Struct({ count: Schema.Number }), + initialValue: () => ({ count: 0 }), + }, + name: "Counter", + icon: "calculator", + }, +); +``` + +### Serve The Registry + +Compose the actor layers and serve them with `Registry.serve`. `Registry.layer()` reads engine config from the environment, and the actor layer is provided a `Client` so actors can call other actors: + +```ts src/main.ts @nocheck +import { NodeRuntime } from "@effect/platform-node"; +import { Client, Registry } from "@rivetkit/effect"; +import { Layer } from "effect"; +import { CounterLive } from "./actors/counter/live.ts"; + +const endpoint = process.env.RIVET_ENDPOINT ?? "http://127.0.0.1:6420"; + +const ActorsLayer = CounterLive.pipe(Layer.provide(Client.layer({ endpoint }))); + +const MainLayer = Registry.serve(ActorsLayer).pipe(Layer.provide(Registry.layer())); + +// Keeps the layer alive. Tears down on SIGINT/SIGTERM. +Layer.launch(MainLayer).pipe(NodeRuntime.runMain); +``` + +### Run The Server + +Set `RIVET_RUN_ENGINE=1` to spawn a local Rivet Engine alongside the server. The engine binary is downloaded and cached the first time you run, so there is nothing else to install: + +```sh +RIVET_RUN_ENGINE=1 npx tsx --watch src/main.ts +``` + +Your server now connects to the Rivet Engine on `http://localhost:6420`. Clients connect directly to the engine on this port. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +To point at a remote engine instead, set `RIVET_ENDPOINT=https://...` and omit `RIVET_RUN_ENGINE`. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend: + +### Effect + +The Effect client imports the same actor contract from your registry. `Counter.client` yields a typed accessor backed by the client layer: + +```ts src/client.ts @nocheck +import { NodeRuntime } from "@effect/platform-node"; +import { Client } from "@rivetkit/effect"; +import { Effect } from "effect"; +import { Counter } from "./actors/counter/api.ts"; + +const program = Effect.gen(function* () { + const counter = (yield* Counter.client).getOrCreate("my-counter"); + + const count = yield* counter.Increment({ amount: 3 }); + yield* Effect.log(`New count: ${count}`); + + const total = yield* counter.GetCount(); + yield* Effect.log(`Total: ${total}`); +}); + +const ClientLayer = Client.layer({ endpoint: "http://localhost:6420" }); + +program.pipe(Effect.provide(ClientLayer), NodeRuntime.runMain); +``` + +With the server still running, start the client in another terminal: + +```sh +npx tsx src/client.ts +``` + +See the [`chat-room-effect`](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room-effect) example for a larger project with typed errors and actor-to-actor calls. + +### TypeScript + +A plain RivetKit client can call your Effect actor by name through the same engine. Actor and action names are resolved at runtime, so the client is untyped here: + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient("http://localhost:6420"); + +const counter = client.Counter.getOrCreate(["my-counter"]); + +const count = await counter.Increment({ amount: 3 }); +console.log("New count:", count); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### Deploy + +## Feature Support + +The Effect SDK wraps the most common actor features with typed, schema-validated APIs. Everything else is still fully usable through the raw RivetKit context (see [Raw Escape Hatch](#raw-escape-hatch) below), so no feature is off limits, it just isn't typed yet. + +| Feature | Effect-native API | Access | +| --- | --- | --- | +| Actor contract & actions | `Actor.make`, `Action.make` | Typed | +| Persisted state | `State.get` / `set` / `update` / `updateAndGet` / `changes` | Typed | +| Typed client | `Actor.client`, `Client.layer` | Typed | +| Typed errors | `RivetError` | Typed | +| Logging | `RivetLogger` | Typed | +| Sleep request | `Actor.Sleep` | Typed | +| Actor address (`actorId` / `name` / `key`) | `Actor.CurrentAddress` | Typed | +| Registry serve / test / web handler | `Registry` | Typed | +| [Events & broadcast](/docs/actors/events) | Not yet wrapped | `rawRivetkitContext.broadcast(...)` | +| [Schedule](/docs/actors/schedule) | Not yet wrapped | `rawRivetkitContext.schedule.*` | +| [Embedded SQLite](/docs/actors/sqlite) | Not yet wrapped | `rawRivetkitContext.db.execute(...)` | +| [Destroy](/docs/actors/lifecycle) | Not yet wrapped | `rawRivetkitContext.destroy()` | +| Queues, connections, vars, alarms | Not yet wrapped | `rawRivetkitContext.*` | +| Lifecycle hooks (`onSleep` / `onDestroy`) | Not yet wrapped | `rawRivetkitContext.*` | +| Raw HTTP / WebSocket handlers | Not yet wrapped | `rawRivetkitContext.*` | + +### Raw Escape Hatch + +Every wake function receives `rawRivetkitContext`, the underlying RivetKit [actor context](/docs/actors). Reach for it to use any feature that does not have a typed wrapper yet. The typed `state` argument and the raw context point at the same actor, so you can mix both: + +```ts src/actors/counter/live.ts @nocheck +export const CounterLive = Counter.toLayer( + Effect.fnUntraced(function* ({ rawRivetkitContext, state }) { + return Counter.of({ + Increment: Effect.fnUntraced(function* ({ payload }) { + // Typed state wrapper + const next = yield* State.updateAndGet(state, (current) => ({ + count: current.count + payload.amount, + })).pipe(Effect.orDie); + + // Untyped features run through the raw context + rawRivetkitContext.broadcast("newCount", next.count); + rawRivetkitContext.schedule.after(1_000, "tick", {}); + + return next.count; + }), + }); + }), + { + state: { + schema: Schema.Struct({ count: Schema.Number }), + initialValue: () => ({ count: 0 }), + }, + name: "Counter", + }, +); +``` + +Calls through `rawRivetkitContext` are not validated by `effect/Schema` and their payloads are typed as they are in the base RivetKit API. + +## Next Steps + + +- [Actions](/docs/actors/actions) — Define the RPC surface clients call on your actor. + + +- [State](/docs/actors/state) — Persist and load actor state across sleeps and restarts. + + +- [Events](/docs/actors/events) — Broadcast realtime updates to connected clients. + +_Source doc path: /docs/actors/quickstart/effect_ diff --git a/.agents/skills/cron-jobs/reference/actors/quickstart/next-js.md b/.agents/skills/cron-jobs/reference/actors/quickstart/next-js.md new file mode 100644 index 0000000..f621606 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/quickstart/next-js.md @@ -0,0 +1,117 @@ +# Next.js Quickstart + +> Source: `src/content/docs/actors/quickstart/next-js.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/next-js +> Description: Get started with Rivet Actors in Next.js + +--- +### Add Rivet Skill to Coding Agent (Optional) + +If you're using an AI coding assistant (like Claude Code, Cursor, Windsurf, etc.), add Rivet skills for enhanced development assistance: + +```sh +npx skills add rivet-dev/skills +``` + +### Create a Next.js App + +```sh +npx create-next-app@latest my-app +cd my-app +``` + +### Install RivetKit + +### Create an Actor + +Create a file at `src/rivet/registry.ts` with a simple counter actor: + +### Setup Rivet API route + +Create a file at `src/app/api/rivet/[...all]/route.ts` to setup the API routes: + +```ts src/app/api/rivet/[...all]/route.ts @nocheck +import { toNextHandler } from "@rivetkit/next-js"; +import { registry } from "@/rivet/registry"; + +export const maxDuration = 300; + +export const { GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS } = toNextHandler(registry); +``` + +### Use the Actor in a component + +Create a Counter component and add it to your page: + +```tsx src/components/Counter.tsx @nocheck +"use client"; + +import { createRivetKit } from "@rivetkit/next-js/client"; +import type { registry } from "@/rivet/registry"; +import { useState } from "react"; + +export const { useActor } = createRivetKit({ + endpoint: + process.env.NEXT_PUBLIC_RIVET_ENDPOINT ?? "http://localhost:3000/api/rivet", + namespace: process.env.NEXT_PUBLIC_RIVET_NAMESPACE, + token: process.env.NEXT_PUBLIC_RIVET_TOKEN, +}); + +export function Counter() { + const [count, setCount] = useState(0); + + // Get or create a counter actor for the key "my-counter" + const counter = useActor({ + name: "counter", + key: ["my-counter"] + }); + + // Listen to realtime events + counter.useEvent("newCount", (x: number) => setCount(x)); + + const increment = async () => { + // Call actions + await counter.connection?.increment(1); + }; + + return ( +
+

Count: {count}

+ +
+ ); +} +``` + +```tsx src/app/page.tsx @nocheck +import { Counter } from "@/components/Counter"; + +export default function Home() { + return ( +
+

My App

+ +
+ ); +} +``` + +For information about the Next.js client API, see the [React Client API Reference](/docs/clients/react). + +### Run Locally + +Start the Next.js dev server. Rivet auto-starts a local engine alongside it: + +```sh +npm run dev +``` + +Open `http://localhost:3000` in your browser to use the app. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Deploy to Vercel + +See the [Vercel deployment guide](/docs/deploy/vercel) for detailed instructions on deploying your Rivet app to Vercel. + +_Source doc path: /docs/actors/quickstart/next-js_ diff --git a/.agents/skills/cron-jobs/reference/actors/quickstart/react.md b/.agents/skills/cron-jobs/reference/actors/quickstart/react.md new file mode 100644 index 0000000..8722fed --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/quickstart/react.md @@ -0,0 +1,82 @@ +# React Quickstart + +> Source: `src/content/docs/actors/quickstart/react.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/react +> Description: Build realtime React applications with Rivet Actors + +--- +## Steps + +### Add Rivet Skill to Coding Agent (Optional) + +If you're using an AI coding assistant (like Claude Code, Cursor, Windsurf, etc.), add Rivet skills for enhanced development assistance: + +```sh +npx skills add rivet-dev/skills +``` + +### Install Dependencies + +```sh +npm install rivetkit @rivetkit/react +``` + +### Create Backend Actor and Start Server + +Create your actor registry on the backend and start the server: + +### Create React Frontend + +Set up your React application: + +For detailed information about the React client API, see the [React Client API Reference](/docs/clients/react). + +### Setup Vite Configuration + +Configure Vite for development: + +```ts vite.config.ts @nocheck +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [react()], + server: { + port: 5173, + }, +}) +``` + +### Run Your Application + +Start both the backend and frontend: + +**Terminal 1**: Start the backend + +```sh Node.js +npx tsx --watch backend/index.ts +``` + +```sh Bun +bun --watch backend/index.ts +``` + +```sh Deno +deno run --allow-net --allow-read --allow-env --watch backend/index.ts +``` + +**Terminal 2**: Start the frontend + +```sh Frontend +npx vite +``` + +Open `http://localhost:5173` in your browser. Try opening multiple tabs to see realtime sync in action. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Deploy + +## Configuration Options + +_Source doc path: /docs/actors/quickstart/react_ diff --git a/.agents/skills/cron-jobs/reference/actors/quickstart/rust.md b/.agents/skills/cron-jobs/reference/actors/quickstart/rust.md new file mode 100644 index 0000000..1e55471 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/quickstart/rust.md @@ -0,0 +1,249 @@ +# Rust Quickstart (Beta) + +> Source: `src/content/docs/actors/quickstart/rust.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/rust +> Description: Build a Rivet Actor in Rust + +--- +Rust support is in beta. The supported public Rust API is `rivetkit` and `rivetkit-client`; lower-level crates are internal implementation details and do not carry a stability guarantee. See the full API reference on [docs.rs/rivetkit](https://docs.rs/rivetkit), or the runnable [`hello-world-rust`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-rust) example. + +## Steps + +### Add Rivet + +Add the `rivetkit` crate and its companions: + +```sh +cargo add rivetkit anyhow async-trait +cargo add serde --features derive +cargo add tokio --features full +``` + +### Define Your Actor + +Put the actor in `src/lib.rs` so both your server and your client can share the same types. An actor is a type that implements `Actor`, plus one `Handles` implementation for each action. Persisted state lives in `type State`; ephemeral runtime state is just fields on your actor struct. + +```rust src/lib.rs +use std::{future::Future, pin::Pin, sync::Arc}; + +use async_trait::async_trait; +use rivetkit::prelude::*; +use serde::{Deserialize, Serialize}; + +type BoxFuture = Pin> + Send>>; + +pub struct Counter; + +#[derive(Default, Serialize, Deserialize)] +pub struct CounterState { + pub count: i64, +} + +#[derive(Serialize, Deserialize)] +pub struct Increment { + pub amount: i64, +} + +impl Action for Increment { + type Output = i64; + + const NAME: &'static str = "increment"; +} + +#[derive(Serialize, Deserialize)] +pub struct NewCount { + pub count: i64, +} + +impl Event for NewCount { + const NAME: &'static str = "newCount"; +} + +#[async_trait] +impl Actor for Counter { + type State = CounterState; + type Input = (); + type Actions = (Increment,); + type Events = (NewCount,); + type Queue = (); + type ConnParams = (); + type ConnState = (); + type Action = action::Raw; + + async fn create_state(_ctx: &Ctx, _input: Self::Input) -> Result { + Ok(CounterState::default()) + } + + async fn create(_ctx: &Ctx) -> Result { + Ok(Self) + } +} + +impl Handles for Counter { + type Future = BoxFuture; + + fn handle(self: Arc, ctx: Ctx, action: Increment) -> Self::Future { + Box::pin(async move { + let count = { + let mut state = ctx.state_mut(); + state.count += action.amount; + state.count + }; + ctx.emit(NewCount { count })?; + Ok(count) + }) + } +} + +pub fn registry() -> Registry { + let mut registry = Registry::new(); + registry.register_actor::("counter"); + registry +} +``` + +### Serve The Registry + +Your `src/main.rs` just starts the registry from the library: + +```rust src/main.rs +#[tokio::main] +async fn main() -> anyhow::Result<()> { + counter::registry().start().await +} +``` + +Replace `counter` with your crate name (the package `name` in `Cargo.toml`, with dashes as underscores). + +### Run The Server + +The Rust runtime connects to the Rivet Engine. Setting `RIVETKIT_ENGINE_AUTO_DOWNLOAD=1` lets the runtime download and cache a matching engine binary the first time you run, so there is nothing else to install: + +```sh +RIVETKIT_ENGINE_AUTO_DOWNLOAD=1 cargo run +``` + +Your server now connects to the Rivet Engine on `http://localhost:6420`. Clients connect directly to the engine on this port. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +Already have an engine binary? Set `RIVET_ENGINE_BINARY_PATH=/path/to/rivet-engine` to point at it instead. If you are working inside the [Rivet monorepo](https://github.com/rivet-dev/rivet), a local `cargo build -p rivet-engine` is discovered automatically from `target/debug`. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend: + +### Rust + +Add a `src/bin/client.rs` that imports the same actor types from your library. There is no need to redefine the actor on the client. + +```rust src/bin/client.rs +use counter::{Counter, Increment, NewCount}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + let count = counter.send(Increment { amount: 3 }).await?; + println!("New count: {count}"); + + let connection = counter.connect(); + connection + .on::(|event| println!("Count changed: {}", event.count)) + .await; + connection.send(Increment { amount: 1 }).await?; + + Ok(()) +} +``` + +With the server still running, start the client in another terminal: + +```sh +cargo run --bin client +``` + +See the [`hello-world-rust`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-rust) example for a complete runnable counter. + +### TypeScript + +A TypeScript client can call your Rust actor by name through the same engine. Actor and action names are resolved at runtime, so the client is untyped here: + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient("http://localhost:6420"); + +const counter = client.counter.getOrCreate(["my-counter"]); + +const counterConnection = counter.connect(); +counterConnection.on("newCount", (event) => { + console.log("Event count:", event.count); +}); + +const count = await counterConnection.increment(3); +console.log("New count:", count); + +await counterConnection.increment(1); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### React + +```tsx Counter.tsx @nocheck +import { createRivetKit } from "@rivetkit/react"; +import { useState } from "react"; + +const { useActor } = createRivetKit("http://localhost:6420"); + +function Counter() { + const [count, setCount] = useState(0); + + const counter = useActor({ + name: "counter", + key: ["my-counter"], + }); + + const increment = async () => { + await counter.connection?.increment(1); + }; + + counter.useEvent("newCount", (event) => { + setCount(event.count); + }); + + return ( +
+

Count: {count}

+ +
+ ); +} +``` + +See the [React documentation](/docs/clients/react) for more information. + +### Deploy + +## Next Steps + + +- [API Reference](https://docs.rs/rivetkit) — Full `rivetkit` crate documentation on docs.rs. + + +- [Actions](/docs/actors/actions) — Define the RPC surface clients call on your actor. + + +- [State](/docs/actors/state) — Persist and load actor state across sleeps and restarts. + + +- [Events](/docs/actors/events) — Broadcast realtime updates to connected clients. + +_Source doc path: /docs/actors/quickstart/rust_ diff --git a/.agents/skills/cron-jobs/reference/actors/quickstart/supabase.md b/.agents/skills/cron-jobs/reference/actors/quickstart/supabase.md new file mode 100644 index 0000000..20b59d0 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/quickstart/supabase.md @@ -0,0 +1,109 @@ +# Supabase Functions Quickstart + +> Source: `src/content/docs/actors/quickstart/supabase.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/supabase +> Description: Set up a Rivet project locally targeting Supabase Edge Functions. + +--- +Set up a Rivet project locally that runs on Supabase Edge Functions. The `@rivetkit/supabase` package wires the WebAssembly runtime for you. + +Prefer to start from a complete project? See the runnable [`hello-world-supabase-functions`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-supabase-functions) example. + +## Steps + +### Prerequisites + +- [Node.js](https://nodejs.org/) +- [Supabase CLI](https://supabase.com/docs/guides/cli) +- Docker, for Supabase's local Edge Runtime + +The CLI runs the local Rivet engine as a bundled native binary, so Docker is only needed for Supabase itself. A Supabase project is only needed to deploy. + +### Create the Function + +```sh +npx supabase functions new rivet +``` + +Add the packages used by the function: + +```sh +npm install rivetkit @rivetkit/supabase +``` + +### Configure the Function + +Call `serve` from `@rivetkit/supabase`. It loads the WebAssembly runtime and serves the Rivet handler. + +```ts supabase/functions/rivet/index.ts @nocheck +import { actor } from "rivetkit"; +import { serve, setup } from "@rivetkit/supabase"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +// `setup` returns a typed registry, so a client can type itself with +// `typeof registry`. +export const registry = setup({ use: { counter } }); + +await serve(registry); +``` + +Add a `deno.json` next to the function so the deploy bundles only the WebAssembly runtime. It points `rivetkit` at the pre-bundled `@rivetkit/supabase`, keeping the deploy small. Without it, the deploy pulls Rivet's native engine and 413s. + +```json supabase/functions/rivet/deno.json +{ + "imports": { + "rivetkit": "npm:@rivetkit/supabase", + "@rivetkit/supabase": "npm:@rivetkit/supabase" + } +} +``` + +Your function code keeps importing from `rivetkit` as usual. The import map only changes how Deno resolves it at bundle time. + +### Run Locally + +Start Rivet. The CLI runs the local engine, spawns `supabase functions serve` for you, and populates the connection values: + +```sh +npx @rivetkit/cli dev --provider supabase +``` + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Call the Actor + +Connect to your actor from a client. This connects directly to the local engine on `http://localhost:6420`: + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./supabase/functions/rivet/index"; + +const client = createClient("http://localhost:6420"); + +const counter = client.counter.getOrCreate(["my-counter"]); +const count = await counter.increment(3); +console.log("New count:", count); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### Deploy + +Ready to ship? See [Deploying to Supabase Functions](/docs/deploy/supabase). + +## Related + +- [Quickstart](/docs/actors/quickstart) +- [Deploying to Supabase Functions](/docs/deploy/supabase) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/actors/quickstart/supabase_ diff --git a/.agents/skills/cron-jobs/reference/actors/request-handler.md b/.agents/skills/cron-jobs/reference/actors/request-handler.md new file mode 100644 index 0000000..0536b9c --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/request-handler.md @@ -0,0 +1,79 @@ +# Low-Level HTTP Request Handler + +> Source: `src/content/docs/actors/request-handler.mdx` +> Canonical URL: https://rivet.dev/docs/actors/request-handler +> Description: Actors can handle HTTP requests through the `onRequest` handler. + +--- +For most use cases, [actions](/docs/actors/actions) provide high-level API powered by HTTP that's easier to work with than low-level HTTP. However, low-level handlers are required when implementing custom use cases or integrating external libraries that need direct access to the underlying HTTP `Request`/`Response` objects or WebSocket connections. + +## Handling HTTP Requests + +The `onRequest` handler processes HTTP requests sent to your actor. It receives the actor context and a standard `Request` object and returns a `Response` object. + +### Raw HTTP + +### Hono + +See also the [raw fetch handler example](https://github.com/rivet-dev/rivet/tree/main/examples/raw-fetch-handler). + +## Sending Requests To Actors + +### Via RivetKit Client + +Use the `.fetch()` method on an actor handle to send HTTP requests to the actor's `onRequest` handler. This can be executed from either your frontend or backend. + +### Via getGatewayUrl + +Use `.getGatewayUrl()` to get the raw gateway URL for the actor. This is useful when you need to use the URL with external tools or custom HTTP clients. + +### Via HTTP API + +This handler can be accessed with raw HTTP using `https://api.rivet.dev/gateway/{actorId}/request/{...path}`. + +For example, to call `POST /increment` on the counter actor above: + +```bash +curl -X POST "https://api.rivet.dev/gateway/{actorId}/request/increment" \ + -H "x-rivet-token: {token}" +``` + +The request is routed to the actor's `onRequest` handler where: + +- `request.method` is `"POST"` +- `request.url` ends with `/increment` (the path after `/request/`) +- Headers, body, and other request properties are passed through unchanged + +See the [HTTP API reference](/docs/actors/http-api) for more information on HTTP routing and authentication. + +### Via Proxying Requests + +You can proxy HTTP requests from your own server to actor handlers using the RivetKit client. This is useful when you need to add custom authentication, rate limiting, or request transformation before forwarding to actors. + +## Connection & Lifecycle Hooks + +`onRequest` will trigger the `onBeforeConnect`, `onConnect`, and `onDisconnect` hooks. Read more about [lifecycle hooks](/docs/actors/lifecycle). + +Requests in flight will be listed in `c.conns`. Read more about [connections](/docs/actors/connections). + +## WinterTC Compliance + +The `onRequest` handler is WinterTC compliant and will work with existing libraries using the standard `Request` and `Response` types. + +## Limitations + +- Does not support streaming responses & server-sent events at the moment. See the [tracking issue](https://github.com/rivet-dev/rivet/issues/3529). +- `OPTIONS` requests currently are handled by Rivet and are not passed to `onRequest` + +## Advanced + +### Skip Ready Wait + +Requests are normally held at the gateway until the actor is ready. Pass `skipReadyWait: true` on `handle.fetch()` to deliver immediately, including while the actor is still starting or in the [sleep grace period](/docs/actors/lifecycle#shutdown-sequence). See [Skip Ready Wait](/docs/clients/javascript#skip-ready-wait) for details. + +## API Reference + +- [`RequestContext`](/typedoc/interfaces/rivetkit.mod.RequestContext.html) - Context for HTTP request handlers +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining request handlers + +_Source doc path: /docs/actors/request-handler_ diff --git a/.agents/skills/cron-jobs/reference/actors/scaling.md b/.agents/skills/cron-jobs/reference/actors/scaling.md new file mode 100644 index 0000000..b597115 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/scaling.md @@ -0,0 +1,10 @@ +# Scaling & Concurrency + +> Source: `src/content/docs/actors/scaling.mdx` +> Canonical URL: https://rivet.dev/docs/actors/scaling +> Description: This page has moved to [design patterns](/docs/actors/design-patterns). + +--- + + +_Source doc path: /docs/actors/scaling_ diff --git a/.agents/skills/cron-jobs/reference/actors/schedule.md b/.agents/skills/cron-jobs/reference/actors/schedule.md new file mode 100644 index 0000000..8dfdb1f --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/schedule.md @@ -0,0 +1,40 @@ +# Actor Scheduling + +> Source: `src/content/docs/actors/schedule.mdx` +> Canonical URL: https://rivet.dev/docs/actors/schedule +> Description: Schedule actor actions in the future with persistent timers that survive restarts and upgrades. + +--- +Scheduling is used to trigger events in the future. The actor scheduler is like `setTimeout`, except the timeout will persist even if the actor restarts, upgrades, or crashes. + +For a pattern guide to durable recurring jobs, see the cookbook: [Cron Jobs and Scheduled Tasks](/cookbook/cron-jobs/). + +## Use Cases + +Scheduling is helpful for long-running timeouts like month-long billing periods or account trials. + +## Scheduling + +### `c.schedule.after(duration, actionName, ...args)` + +Schedules a function to be executed after a specified duration. This function persists across actor restarts, upgrades, or crashes. + +Parameters: + +- `duration` (number): The delay in milliseconds. +- `actionName` (string): The name of the action to be executed. +- `...args` (unknown[]): Additional arguments to pass to the function. + +### `c.schedule.at(timestamp, actionName, ...args)` + +Schedules a function to be executed at a specific timestamp. This function persists across actor restarts, upgrades, or crashes. + +Parameters: + +- `timestamp` (number): The exact time in milliseconds since the Unix epoch when the function should be executed. +- `actionName` (string): The name of the action to be executed. +- `...args` (unknown[]): Additional arguments to pass to the function. + +## Full Example + +_Source doc path: /docs/actors/schedule_ diff --git a/.agents/skills/cron-jobs/reference/actors/sharing-and-joining-state.md b/.agents/skills/cron-jobs/reference/actors/sharing-and-joining-state.md new file mode 100644 index 0000000..1fe0683 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/sharing-and-joining-state.md @@ -0,0 +1,10 @@ +# Sharing and Joining State + +> Source: `src/content/docs/actors/sharing-and-joining-state.mdx` +> Canonical URL: https://rivet.dev/docs/actors/sharing-and-joining-state +> Description: This page has moved to [design patterns](/docs/actors/design-patterns). + +--- + + +_Source doc path: /docs/actors/sharing-and-joining-state_ diff --git a/.agents/skills/cron-jobs/reference/actors/sqlite-drizzle.md b/.agents/skills/cron-jobs/reference/actors/sqlite-drizzle.md new file mode 100644 index 0000000..f0184d9 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/sqlite-drizzle.md @@ -0,0 +1,248 @@ +# SQLite + Drizzle + +> Source: `src/content/docs/actors/sqlite-drizzle.mdx` +> Canonical URL: https://rivet.dev/docs/actors/sqlite-drizzle +> Description: Use Drizzle ORM with embedded SQLite in Rivet Actors. + +--- +Use Drizzle when you want typed schema, typed queries, and generated migrations on top of actor-local SQLite. + +For a high-level overview of where to store actor data, see [State & Storage](/docs/actors/state). For a worked multi-tenant pattern, see the cookbook: [Database per Tenant](/cookbook/per-tenant-database/). + +## What is Drizzle good for? + +- **Typed schema**: define tables in TypeScript and get typed query results. +- **Typed query builder**: write SQL-like queries with autocompletion. +- **Migration workflow**: generate SQL migration files from schema changes. +- **Raw SQL escape hatch**: use `c.db.execute(...)` for direct SQLite when needed. + +## Project structure + +Use one folder per actor database: + +```txt +src/ + actors/ + todo-list/ + index.ts + schema.ts + drizzle.config.ts + drizzle/ + 0000_init.sql + migrations.js + migrations.d.ts + meta/ + _journal.json +``` + +- `index.ts` is the actor implementation. +- `drizzle/` holds the SQL migrations (`*.sql`) and `meta/_journal.json` generated by `drizzle-kit`. +- `migrations.js` is a small RivetKit glue file you maintain by hand. It imports the journal and each `*.sql` file and exports a `{ journal, migrations }` object keyed by migration (for example `m0000`). Add a new entry here whenever `db:generate` produces a new migration. +- Commit the generated migration files and `migrations.js` to source control. + +## Basic setup + +```json package.json +{ + "scripts": { + "db:generate": "find src/actors -name drizzle.config.ts -exec drizzle-kit generate --config {} \\;" + }, + "dependencies": { + "rivetkit": "*", + "drizzle-orm": "^0.44.2" + }, + "devDependencies": { + "drizzle-kit": "^0.31.2" + } +} +``` + +```ts vite.config.ts @nocheck +import { defineConfig, type Plugin } from "vite"; +import { readFileSync } from "node:fs"; + +function sqlRawPlugin(): Plugin { + return { + name: "sql-raw", + transform(_code, id) { + if (id.endsWith(".sql")) { + const content = readFileSync(id, "utf-8"); + return { code: `export default ${JSON.stringify(content)};` }; + } + }, + }; +} + +export default defineConfig({ + plugins: [sqlRawPlugin()], +}); +``` + +```ts drizzle.config.ts @nocheck +import { defineConfig } from "rivetkit/db/drizzle"; + +export default defineConfig({ + schema: "./src/actors/todo-list/schema.ts", + out: "./src/actors/todo-list/drizzle", +}); +``` + +```sql 0000_init.sql +CREATE TABLE `todos` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `title` text NOT NULL, + `created_at` integer NOT NULL +); +``` + +```json _journal.json +{ + "version": "7", + "dialect": "sqlite", + "entries": [ + { + "idx": 0, + "version": "7", + "when": 1735689600000, + "tag": "0000_init", + "breakpoints": true + } + ] +} +``` + +```ts migrations.js @nocheck +import journal from "./meta/_journal.json"; +import m0000 from "./0000_init.sql"; + +export default { + journal, + migrations: { + m0000, + }, +}; +``` + +```ts index.ts @nocheck +import { actor } from "rivetkit"; +import { db } from "rivetkit/db/drizzle"; +import migrations from "./drizzle/migrations.js"; +import { schema, todos } from "./schema.ts"; + +export const todoList = actor({ + db: db({ schema, migrations }), + actions: { + addTodo: async (c, title: string) => { + const rows = await c.db + .insert(todos) + .values({ title, createdAt: Date.now() }) + .returning(); + return rows[0]; + }, + getTodos: async (c) => { + return await c.db.select().from(todos).orderBy(todos.id); + }, + getTodoCount: async (c) => { + const rows = (await c.db.execute( + "SELECT COUNT(*) AS count FROM todos", + )) as { count: number }[]; + return rows[0]?.count ?? 0; + }, + }, +}); +``` + +```ts index.ts @nocheck +import { setup } from "rivetkit"; +import { todoList } from "./todo-list/index.ts"; + +export const registry = setup({ use: { todoList } }); +registry.start(); +``` + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const todoList = client.todoList.getOrCreate(["main"]); + +await todoList.addTodo("Write Drizzle docs"); + +const todos = await todoList.getTodos(); +const count = await todoList.getTodoCount(); + +console.log(todos, count); +``` + +## Queries + +### Query builder + +Use Drizzle's typed query APIs for most reads and writes. + +```ts @nocheck +import { eq } from "drizzle-orm"; + +await c.db.insert(todos).values({ title, createdAt: Date.now() }); + +const rows = await c.db + .select() + .from(todos) + .where(eq(todos.title, title)); +``` + +### Raw SQL + +`rivetkit/db/drizzle` also exposes raw SQLite access through `c.db.execute(...)`. + +```ts @nocheck +await c.db.execute( + "CREATE INDEX IF NOT EXISTS idx_todos_created_at ON todos(created_at)", +); +``` + +## Queues + +Use queues for ordered mutations and keep actions read-only. Import `queue` alongside `actor` from `rivetkit`. + +```ts @nocheck +import { actor, queue } from "rivetkit"; + +// ... + +queues: { + addTodo: queue<{ title: string }>(), +}, +run: async (c) => { + for await (const message of c.queue.iter()) { + if (message.name === "addTodo") { + await c.db.insert(todos).values({ + title: message.body.title, + createdAt: Date.now(), + }); + } + } +}, +actions: { + getTodos: async (c) => await c.db.select().from(todos), +}, +``` + +## Recommendations + +- Prefer Drizzle query APIs for app code and use raw SQL for advanced SQLite features. +- Keep one `drizzle.config.ts` per actor folder. +- Re-run `db:generate` after schema changes and commit generated migration files. +- Use queues for writes and actions for reads. +- Keep related writes in one action or queue message to reduce interleaved query risk. + +## Read more + +- [Drizzle SQLite quickstart](https://orm.drizzle.team/docs/get-started-sqlite) +- [Drizzle `drizzle-kit generate`](https://orm.drizzle.team/docs/drizzle-kit-generate) +- [Drizzle + Cloudflare D1](https://orm.drizzle.team/docs/deploy-cloudflare-d1) +- [Drizzle + Cloudflare Durable Objects](https://orm.drizzle.team/docs/deploy-cloudflare-do) +- [Cloudflare Durable Objects SQLite storage](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/) + +_Source doc path: /docs/actors/sqlite-drizzle_ diff --git a/.agents/skills/cron-jobs/reference/actors/sqlite.md b/.agents/skills/cron-jobs/reference/actors/sqlite.md new file mode 100644 index 0000000..fb55998 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/sqlite.md @@ -0,0 +1,127 @@ +# SQLite + +> Source: `src/content/docs/actors/sqlite.mdx` +> Canonical URL: https://rivet.dev/docs/actors/sqlite +> Description: Use embedded SQLite in Rivet Actors with raw SQL queries. + +--- +For a high-level overview of where to store actor data, including when to use `c.state` versus SQLite, see [State & Storage](/docs/actors/state). For a worked multi-tenant pattern, see the cookbook: [Database per Tenant](/cookbook/per-tenant-database/). + +## What is SQLite? + +- **Database per actor**: each actor instance has its own SQLite database, scoped to that actor. +- **High performance**: Rivet Actors keep compute and storage together, so queries avoid network round trips to an external database. +- **Larger-than-memory storage**: SQLite stores data on disk, so you can work with datasets that do not fit in actor memory. +- **Embedded relational database**: use tables, indexes, and SQL queries directly inside actor logic. + +### SQLite features + +- **Indexes**: speed up lookups on frequently queried fields. +- **Search and filtering**: use `WHERE`, `LIKE`, and `ORDER BY` instead of manual in-memory loops. +- **Relationships**: use multiple tables and `JOIN` queries for connected data. +- **Constraints**: use primary keys, unique constraints, and foreign keys for data integrity. +- **Transactions**: apply multiple writes atomically when changes must stay consistent. + +## Raw SQL vs ORM (Drizzle) + +Rivet supports both raw SQL and [Drizzle](https://orm.drizzle.team/) for actor-local SQLite. + +Use **raw SQL** when you want direct query control and minimal abstraction. + +```ts @nocheck +await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); +const rows = await c.db.execute("SELECT id, title FROM todos ORDER BY id DESC"); +``` + +Use **Drizzle** when you want typed schema and typed query APIs. + +```ts @nocheck +await c.vars.drizzle.insert(todos).values({ title }); +const rows = await c.vars.drizzle.select().from(todos).orderBy(desc(todos.id)); +``` + +You can mix both in the same actor. + +For Drizzle setup, see [SQLite + Drizzle](/docs/actors/sqlite-drizzle). + +## Basic setup + +Define `db: db({ onMigrate })` on your actor, create your schema in `onMigrate`, and execute SQL with `c.db.execute(...)`. + +RivetKit wraps `onMigrate` in a SQLite savepoint, so migration steps are atomic. If `onMigrate` throws, all SQL run by that hook is rolled back before the actor starts. + +## Queries + +`c.db.execute(...)` returns an array of row objects for `SELECT` queries. + +```ts @nocheck +const rows = await c.db.execute( + "SELECT id, title FROM todos WHERE title LIKE ?", + `%${query}%`, +); +``` + +### Parameterized queries + +Use `?` placeholders for dynamic values and pass parameters in order after the SQL string. + +```ts @nocheck +await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); +``` + +You can also use named SQLite bindings by passing a single properties object. + +```ts @nocheck +const rows = await c.db.execute( + "SELECT id, title FROM todos WHERE title = :title", + { title: "Write SQLite docs" }, +); +``` + +### Transactions + +Use transactions when multiple writes must succeed or fail together. + +```ts @nocheck +await c.db.transaction(async (tx) => { + await tx.execute("INSERT INTO todos (title) VALUES (?)", title); + await tx.execute( + "INSERT INTO comments (todo_id, body) VALUES (last_insert_rowid(), ?)", + body, + ); +}); +``` + +RivetKit commits when the callback resolves and rolls back when it throws. Other transactions and ordinary actor SQL queue in FIFO order until the callback finishes. Transactions have a 60-second safety timeout by default; increase it for legitimately long work with `{ timeout: 120_000 }`. + +Always use the callback's `tx` value inside the transaction. Starting another transaction or using the outer `c.db` from the callback waits behind the active transaction and eventually reaches the safety timeout; the resulting error points to this possible deadlock. + +Manual `BEGIN`/`COMMIT` calls remain supported for compatibility, but cannot protect against interleaving callers. RivetKit logs a warning recommending `db.transaction()`. Set `warnOnManualTransactions: false` in `db(...)` to disable the warning; the warning itself mentions this flag. + +## Queues + +It's recommended to use queues for mutations and actions for read-only queries. This is the same code structure as the basic setup, but mutation writes are routed through queues. + +## Debugging + +- `GET /inspector/summary` includes `isDatabaseEnabled` so you can confirm SQLite is configured. +- `GET /inspector/database/schema` returns the tables and views discovered in the actor's SQLite database. +- `GET /inspector/database/rows?table=...&limit=100&offset=0` returns paged rows for a specific table or view. +- `POST /inspector/database/execute` lets you run ad-hoc SQL for debugging and data fixes with positional `args` or named `properties`. +- Keep a small read-only action for quick query verification while debugging. +- In non-dev mode, inspector endpoints require authorization. + +## Recommendations + +- Keep schema creation and migration steps in `onMigrate`; RivetKit runs them atomically inside a SQLite savepoint. +- Use `?` placeholders for dynamic values. +- Prefer queue-driven writes for ordered or background work. +- Use transactions for related multi-step mutations when atomicity matters. + +## Read more + +- [SQLite + Drizzle in Rivet Actors](/docs/actors/sqlite-drizzle) +- [SQLite docs](https://sqlite.org/docs.html) +- [SQLite SQL language reference](https://sqlite.org/lang.html) + +_Source doc path: /docs/actors/sqlite_ diff --git a/.agents/skills/cron-jobs/reference/actors/state.md b/.agents/skills/cron-jobs/reference/actors/state.md new file mode 100644 index 0000000..559b49c --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/state.md @@ -0,0 +1,270 @@ +# In-Memory State + +> Source: `src/content/docs/actors/state.mdx` +> Canonical URL: https://rivet.dev/docs/actors/state +> Description: Actors store state in memory for instant reads and writes. State can be persisted automatically or kept ephemeral. + +--- +## Types of State + +There are three ways to store data in an actor, depending on what it looks like and whether it needs to survive restarts. + +### Durable + +Simple, serializable data on `c.state` that is automatically persisted and restored across restarts. The default starting point. + +### Ephemeral + +Live objects on `c.vars` like database connections, API clients, and event emitters, or data loaded from an external source. Never persisted. + +```typescript @nocheck External database +import { actor } from "rivetkit"; +import { Pool } from "pg"; + +// One shared pool for the whole process, created once and reused by every actor +const pool = new Pool({ connectionString: process.env.DATABASE_URL }); + +const userActor = actor({ + state: { profile: null as Record | null }, + + // Load this actor's row from the shared pool on each start + createVars: async (c) => { + const { rows } = await pool.query("SELECT * FROM users WHERE id = $1", [c.key[0]]); + return { profile: rows[0] }; + }, + + actions: { + updateEmail: async (c, email: string) => { + await pool.query("UPDATE users SET email = $1 WHERE id = $2", [email, c.key[0]]); + } + } +}); +``` + +### SQLite + +Rivet also provides an embedded SQLite database (`c.db`) for when your data needs to be queried, requires safe schema migrations, or grows too large to hold in memory. See [SQLite](/docs/actors/sqlite). + +```typescript @nocheck Basic +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +const todoList = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL + ); + `); + }, + }), + + actions: { + add: async (c, title: string) => { + await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); + }, + + list: async (c) => { + return (await c.db.execute( + "SELECT id, title FROM todos ORDER BY id DESC", + )) as { id: number; title: string }[]; + }, + }, +}); +``` + +```typescript @nocheck Load into memory +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +const counter = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS counter ( + id INTEGER PRIMARY KEY CHECK (id = 1), + count INTEGER NOT NULL + ); + `); + await db.execute("INSERT OR IGNORE INTO counter (id, count) VALUES (1, 0)"); + }, + }), + + // Load the count from SQLite into memory on every start + createVars: async (c) => { + const rows = (await c.db.execute( + "SELECT count FROM counter WHERE id = 1", + )) as { count: number }[]; + return { count: rows[0].count }; + }, + + actions: { + get: (c) => c.vars.count, + + increment: async (c) => { + // Update the in-memory value and write it back to SQLite + c.vars.count += 1; + await c.db.execute("UPDATE counter SET count = ? WHERE id = 1", c.vars.count); + return c.vars.count; + }, + }, +}); +``` + +## State Isolation + +Each actor's state is fully isolated. Other actors and clients can't touch it directly; all reads and writes go through the actor's own [Actions](/docs/actors/actions). To share state across actors, see [sharing and joining state](/docs/actors/sharing-and-joining-state). + +## Durable State + +`c.state` lives in memory and is persisted automatically, so reads and writes have no added latency while the data still survives sleeps, restarts, upgrades, and crashes. Use it for small, simple values like counters, flags, and small maps. + +`createState` runs once when the actor is first created. On later starts, state is loaded from storage instead of recreated. See [Lifecycle](/docs/actors/lifecycle). + +### When state saves + +Mutating `c.state` schedules a save automatically. Rapid mutations are batched into a single write on a throttle (`stateSaveInterval`, default 1 second). Reads never trigger a save, saves aren't tied to action or handler boundaries, and state is also flushed when the actor sleeps or shuts down. + +To force a save mid-action, call `c.saveState()`: + +- `c.saveState({ immediate: true })` writes immediately and resolves once the write completes. +- `c.saveState()` schedules a throttled save and returns right away, without waiting for the write. + +Force an immediate save before a risky side effect so a crash can't lose progress: + +### Supported types + +State must be serializable. + +- `null`, `undefined`, `boolean`, `string`, `number`, `BigInt` +- `Date`, `RegExp`, `Error` +- `ArrayBuffer` and typed arrays (`Uint8Array`, `Int8Array`, `Float32Array`, etc.) +- `Map`, `Set`, `Array` +- Plain objects + +When data grows large or needs querying, store it in [Embedded SQLite](#embedded-sqlite) instead. + +## Ephemeral State + +`c.vars` holds data that exists only while the actor runs and is never saved. Use it for live objects that can't be serialized (connections, clients, emitters) or for data loaded from an external source. Most actors use both: `state` for durable data, `vars` for live objects. + +`createVars` runs on every actor start, unlike `createState` which runs once. That makes it the place to open connections and load data each time the actor wakes. + +### Runtime objects + +Build non-serializable objects in `createVars` and use them from actions: + +### Loading from external sources + +Create the connection pool once at module scope and share it across all actors, then use `createVars` (which can be `async`) to load this actor's data from it on each start: + +```typescript @nocheck +import { actor } from "rivetkit"; +import { Pool } from "pg"; + +// One shared pool for the whole process, not one per actor +const pool = new Pool({ connectionString: process.env.DATABASE_URL }); + +const profile = actor({ + state: { cachedName: "" }, + + createVars: async (c) => { + const { rows } = await pool.query("SELECT * FROM users WHERE id = $1", [c.key[0]]); + return { user: rows[0] }; + }, + + actions: { + updateEmail: async (c, email: string) => { + await pool.query("UPDATE users SET email = $1 WHERE id = $2", [email, c.key[0]]); + } + } +}); +``` + +When the actor owns its data, prefer [durable state](#durable-state) or [SQLite](#embedded-sqlite), which need no external infrastructure. + +### Cleanup + +`vars` is dropped when the actor stops, but per-actor resources like timers, subscriptions, and dedicated connections aren't cleaned up for you. Release them in `onSleep` and `onDestroy`. A shared pool stays open for the whole process, so don't close it per actor. + +```typescript @nocheck +const poller = actor({ + state: { ticks: 0 }, + + // Per-actor timer started on each wake + createVars: (c) => ({ timer: setInterval(() => c.state.ticks++, 5000) }), + + // Clear it before the actor sleeps or is destroyed + onSleep: (c) => clearInterval(c.vars.timer), + onDestroy: (c) => clearInterval(c.vars.timer), + + actions: { /* ... */ } +}); +``` + +## Embedded SQLite + +`c.db` is a SQLite database scoped to each actor and stored on disk. Use it for queryable, relational, or larger-than-memory data. Because compute and storage live together, queries run locally with no network round trips. + +A common pattern is to treat SQLite as the source of truth and keep a working copy in `c.vars`: load rows in `createVars`, serve reads from memory, and write changes back to `c.db`. + +```typescript @nocheck +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +const leaderboard = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS scores ( + player TEXT PRIMARY KEY, + score INTEGER NOT NULL + ); + `); + }, + }), + + // Load the table into memory once per start + createVars: async (c) => { + const rows = (await c.db.execute("SELECT player, score FROM scores")) as { + player: string; + score: number; + }[]; + return { scores: new Map(rows.map((r) => [r.player, r.score])) }; + }, + + actions: { + top: (c) => [...c.vars.scores].sort((a, b) => b[1] - a[1]).slice(0, 10), + + record: async (c, player: string, score: number) => { + c.vars.scores.set(player, score); + // Write through to SQLite + await c.db.execute( + "INSERT INTO scores (player, score) VALUES (?, ?) ON CONFLICT(player) DO UPDATE SET score = ?", + player, score, score, + ); + }, + }, +}); +``` + +For the full query API, schema migrations, transactions, and the Drizzle ORM, see: + +- [SQLite](/docs/actors/sqlite): raw SQL against the embedded per-actor database. +- [SQLite + Drizzle](/docs/actors/sqlite-drizzle): typed schema and query APIs. + +## Debugging + +- `GET /inspector/state` returns the actor's current state and `isStateEnabled`. +- `PATCH /inspector/state` lets you set state directly while debugging. +- In non-dev mode, inspector endpoints require authorization. + +## API Reference + +- [`CreateContext`](/typedoc/types/rivetkit.mod.CreateContext.html) - Context available during actor state creation +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - Context available throughout actor lifecycle +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining actors with state + +_Source doc path: /docs/actors/state_ diff --git a/.agents/skills/cron-jobs/reference/actors/statuses.md b/.agents/skills/cron-jobs/reference/actors/statuses.md new file mode 100644 index 0000000..cccf52a --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/statuses.md @@ -0,0 +1,36 @@ +# Actor Statuses + +> Source: `src/content/docs/actors/statuses.mdx` +> Canonical URL: https://rivet.dev/docs/actors/statuses +> Description: Understand the lifecycle statuses of Rivet Actors, what they mean, how they appear in the API, and how to troubleshoot common issues. + +--- +## Statuses + +These are the statuses you can see in the dashboard for each actor. + +| Status | Description | +|---|---| +| **Starting** | The actor has been created but has not yet become connectable. | +| **Running** | The actor is live and accepting connections. | +| **Destroyed** | The actor has been gracefully destroyed. | +| **Crashed** | The actor failed to start or encountered a fatal error. See [Troubleshooting](/docs/actors/troubleshooting#actor-status-is-crashed) for common failure reasons. | +| **Sleeping** | The actor has been put to sleep from inactivity. It will be woken up automatically when a new request arrives. | +| **Pending** | The actor is waiting to be allocated to a runner. This happens when no runner is available to handle the actor. See [Troubleshooting](/docs/actors/troubleshooting#actor-status-is-pending) for common causes. | +| **Crash Loop Backoff** | The actor failed to allocate and is waiting to retry with a backoff. This typically means repeated allocation failures. The backoff prevents overloading your infrastructure in the case of a widespread misconfiguration in your backend. See [Troubleshooting](/docs/actors/troubleshooting#actor-status-is-crashed) for common failure reasons. | + +## API Representation + +The actor object returned by the full engine API (used by the dashboard) includes the following timestamp fields used to derive status: + +| Field | Description | +|---|---| +| `createTs` | When the actor was first created. Always present. | +| `connectableTs` | When the actor became connectable. Null if not yet running. | +| `destroyTs` | When the actor was destroyed. | +| `sleepTs` | When the actor entered a sleeping state. | +| `pendingAllocationTs` | When the actor started waiting for an allocation. | +| `rescheduleTs` | When the actor will retry allocation after a failure. | +| `error` | Error details if the actor failed. | + +_Source doc path: /docs/actors/statuses_ diff --git a/.agents/skills/cron-jobs/reference/actors/testing.md b/.agents/skills/cron-jobs/reference/actors/testing.md new file mode 100644 index 0000000..5afe658 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/testing.md @@ -0,0 +1,51 @@ +# Testing + +> Source: `src/content/docs/actors/testing.mdx` +> Canonical URL: https://rivet.dev/docs/actors/testing +> Description: Rivet provides a straightforward testing framework to build reliable and maintainable applications. This guide covers how to write effective tests for your actor-based services. + +--- +## Setup + +To set up testing with Rivet: + +```bash +# Install Vitest +npm install -D vitest + +# Run tests +npm test +``` + +## Basic Testing Setup + +Rivet includes a test helper called `setupTest` that starts your registry in test mode and returns a client connected to it. This allows for fast, isolated tests without external dependencies. + +## Testing Actor State + +State persists within each test, allowing you to verify that your actor correctly maintains state between operations. + +## Testing Events + +For actors that emit events, you can verify events are correctly triggered by subscribing to them: + +## Testing Schedules + +Rivet's schedule functionality can be tested by scheduling work and waiting for it to run: + +Use a short real-time delay to wait for scheduled work to run. `setupTest` does not install fake timers, so if you want to use `vi.useFakeTimers()` you must enable it yourself and confirm it works with your selected runtime. + +## Best Practices + +1. **Isolate tests**: Each test should run independently, avoiding shared state. +2. **Test edge cases**: Verify how your actor handles invalid inputs, concurrent operations, and error conditions. +3. **Test scheduled operations**: Use short real-time delays to wait for scheduled work to run. +4. **Use realistic data**: Test with data that resembles production scenarios. + +`setupTest` starts the registry and disposes the returned client when the test finishes, so you can focus on writing effective tests for your business logic. + +## API Reference + +- [`setupTest`](/typedoc/functions/rivetkit.test_mod.setupTest.html) - Test setup helper function + +_Source doc path: /docs/actors/testing_ diff --git a/.agents/skills/cron-jobs/reference/actors/troubleshooting.md b/.agents/skills/cron-jobs/reference/actors/troubleshooting.md new file mode 100644 index 0000000..65b234d --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/troubleshooting.md @@ -0,0 +1,154 @@ +# Troubleshooting + +> Source: `src/content/docs/actors/troubleshooting.mdx` +> Canonical URL: https://rivet.dev/docs/actors/troubleshooting +> Description: Common issues with Rivet Actors and how to resolve them. + +--- +## Common Steps + +Before diving into specific errors, try these general troubleshooting steps: + +- Check your server logs for `level=ERROR` or `level=WARN` messages. +- Check if any of your backend processes have crashed or restarted unexpectedly. +- If you need more diagnostics, set `RIVET_LOG_LEVEL=DEBUG` for verbose logging. See [Logging](/docs/general/logging) for more options. + +## Reporting Issues + +If you're stuck, reach out on [Discord](https://rivet.dev/discord) or file an issue on [GitHub](https://github.com/rivet-dev/rivet/issues). + +When reporting, please include: + +- **Symptoms** + - Whether this is happening in local dev, deployed, or both + - The error you're seeing (screenshot or error message) + - Relevant source code related to the issue +- **What you've tried to solve it** +- **Environment** + - RivetKit version + - Runtime (Node, Bun, etc.) including version + - If applicable, provider in use (e.g. Vercel, Railway, Cloudflare) + - If applicable, HTTP router in use (e.g. Hono, Express, Elysia) + +## Actor status is crashed + +See [Actor Statuses](/docs/actors/statuses) for more about this status. + +The dashboard will show the specific failure reason. Common errors include: + +### `crashed` + +The actor's `run` handler threw an unhandled exception or exited unexpectedly. Check your actor logs for the error message and stack trace. + +### `no_capacity` + +No server was available to run your actor. The cause depends on your [runtime mode](/docs/general/runtime-modes): + +**Serverless**: + +- Your provider configuration does not have the region enabled that the actor is trying to run in. This is uncommon and usually only happens if an actor was created and then the provider config was updated to remove the region. +- There is an issue connecting to your backend. If the engine is hitting `/api/rivet/start` and failing, check your backend logs for errors. + +**Runners**: + +- You don't have enough runners online. Check your runner list in the dashboard to verify runners are visible and connected. +- Your runners are full. Each runner has a limited number of actor slots (configured via `RIVET_TOTAL_SLOTS`, default: 100,000). Check the dashboard to see if your runners have available capacity and scale up if needed. + +### `runner_no_response` + +The server running your actor did not respond in time. This can happen if your server is overloaded or experienced a network issue. Try restarting your server or checking its health. + +### `runner_connection_lost` + +The server running your actor lost its connection to Rivet. This is usually caused by a network interruption or your server restarting. + +### `runner_draining_timeout` + +Your server is shutting down and the actor did not finish in time. Consider handling graceful shutdown in your actor or increasing your shutdown timeout. + +### `concurrent_actor_limit_reached` + +The actor could not be allocated because the concurrent actor limit was reached. Reduce the number of concurrently running actors or increase your limit. + +### `no_envoys` + +No server was available to run your actor. This is equivalent to `no_capacity` on the current allocation path. See the `no_capacity` section above for the causes and fixes for your [runtime mode](/docs/general/runtime-modes). + +### `envoy_no_response` + +The server running your actor did not respond in time. This can happen if your server is overloaded or experienced a network issue. Try restarting your server or checking its health. + +### `envoy_connection_lost` + +The server running your actor lost its connection to Rivet. This is usually caused by a network interruption or your server restarting. + +### `serverless_http_error` + +Your serverless endpoint returned an HTTP error. Common causes: + +- Your backend is returning an error before the actor can start. Check your server logs. +- Your endpoint is behind authentication or a firewall that is blocking Rivet's requests. +- Your serverless function crashed during startup. Check your platform's function logs (e.g. Vercel, Cloudflare). + +### `serverless_connection_error` + +Rivet was unable to connect to your serverless endpoint. Check that: + +- Your backend is deployed and the endpoint URL is correct. +- Your server is publicly reachable from the internet. +- There are no DNS or firewall issues blocking the connection. + +### `serverless_stream_ended_early` + +The connection to your serverless endpoint was terminated before the actor finished. This usually means your serverless function hit its execution time limit. Ensure that your Rivet provider's request lifespan is configured to match the max duration of your serverless platform. + +### `serverless_invalid_sse_payload` + +Rivet received an unexpected response from your serverless endpoint. This typically means something is intercepting or modifying the request before it reaches your RivetKit handler. Check that: + +- Your server routes requests to `registry.start()`, `registry.serve()`, or `registry.handler()` correctly. +- No middleware is modifying the request or response body. + +### `internal_error` + +An unexpected error occurred within Rivet. If this persists, please [contact support](https://rivet.dev/docs). + +## Actors crashing immediately on startup + +If your actors are being created and then immediately destroyed or crashing, there is likely an error being thrown in your `createState` or `onCreate` lifecycle hooks. These hooks run during actor initialization before the actor is marked as ready. + +Check your server logs for the error message and stack trace. Common causes include: + +- An exception thrown in `createState` (e.g. invalid input, failed validation, or a runtime error when computing initial state) +- An exception thrown in `onCreate` (e.g. a failing external API call, missing configuration, or invalid setup logic) + +Fix the error in the relevant lifecycle hook and redeploy. + +## Actors not upgrading to new code + +If your actors are still running old code after deploying a new version, your [versioning](/docs/actors/versions) is likely not configured correctly. + +Without versioning, Rivet has no way to distinguish old deployments from new ones. The behavior depends on your [runtime mode](/docs/general/runtime-modes): + +- **Serverless**: Old requests may still be open from the previous deployment, so actors continue running on the old version's connection until those requests close. +- **Runners**: The old runner container is still running and will continue accepting new actors. New actors may be scheduled on the old runner instead of the new one. + +To fix this, configure a version number in your [registry configuration](/docs/general/registry-configuration). When a new version is deployed, Rivet will allocate new actors to the latest version and optionally drain old actors to migrate them. + +## Actor status is pending + +See [Actor Statuses](/docs/actors/statuses) for more about this status. + +An actor stays in "pending" status when Rivet is waiting for a server to accept it. The cause depends on your [runtime mode](/docs/general/runtime-modes): + +**Serverless**: + +- A region may have been removed from your provider configuration while an existing actor still lives in that region. The actor has no available server to start on because no provider serves that region anymore. Re-add the region to your provider config or destroy the affected actors. +- Check your backend logs for errors on the `/api/rivet/start` endpoint. + +**Runners**: + +- You don't have enough runners online. Check the dashboard to verify your runners are connected. +- Your runners may be at capacity. Check the dashboard to see if runners have available actor slots and scale up if needed. + +_Source doc path: /docs/actors/troubleshooting_ diff --git a/.agents/skills/cron-jobs/reference/actors/types.md b/.agents/skills/cron-jobs/reference/actors/types.md new file mode 100644 index 0000000..3e8f9b0 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/types.md @@ -0,0 +1,46 @@ +# Types + +> Source: `src/content/docs/actors/types.mdx` +> Canonical URL: https://rivet.dev/docs/actors/types +> Description: TypeScript types for working with Rivet Actors. This page covers context types used in lifecycle hooks and actions, as well as helper types for extracting types from actor definitions. + +--- +## Context Types + +Context types define what properties and methods are available in different parts of the actor lifecycle. + +### Extracting Context Types + +When writing helper functions that work with actor contexts, use context extractor types like `CreateContextOf` or `ActionContextOf` to extract the appropriate context type from your actor definition. + +### All Context Types + +Each lifecycle hook and handler has a corresponding `*ContextOf` type, exported from `"rivetkit"`. Pass `typeof myActor` as the type parameter. + +| Hook / Handler | Context Type | +|---|---| +| `createState` | `CreateContextOf` | +| `onCreate` | `CreateContextOf` | +| `createVars` | `CreateVarsContextOf` | +| `createConnState` | `CreateConnStateContextOf` | +| `onBeforeConnect` | `BeforeConnectContextOf` | +| `onConnect` | `ConnectContextOf` | +| `onDisconnect` | `DisconnectContextOf` | +| `onDestroy` | `DestroyContextOf` | +| `onMigrate` | `MigrateContextOf` | +| `onWake` | `WakeContextOf` | +| `onSleep` | `SleepContextOf` | +| `onStateChange` | `StateChangeContextOf` | +| `onBeforeActionResponse` | `BeforeActionResponseContextOf` | +| `actions.*` | `ActionContextOf` | +| `run` | `RunContextOf` | +| `workflow` orchestration helpers (root, `loop`, `try`, `race`, `join` branches) | `WorkflowContextOf` | +| `workflow` `step` / `tryStep` run + rollback helpers | `WorkflowStepContextOf` | +| `onRequest` | `RequestContextOf` | +| `onWebSocket` | `WebSocketContextOf` | + +`ActorContextOf`, `ConnContextOf`, and `ConnInitContextOf` are general-purpose base context types useful for helper functions that don't correspond to a specific hook. + +Workflow context extractors are exported from both `"rivetkit"` and `"rivetkit/workflow"`. + +_Source doc path: /docs/actors/types_ diff --git a/.agents/skills/cron-jobs/reference/actors/versions.md b/.agents/skills/cron-jobs/reference/actors/versions.md new file mode 100644 index 0000000..1b45129 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/versions.md @@ -0,0 +1,241 @@ +# Versions & Upgrades + +> Source: `src/content/docs/actors/versions.mdx` +> Canonical URL: https://rivet.dev/docs/actors/versions +> Description: When you deploy new code, Rivet ensures actors are upgraded seamlessly without downtime. + +--- +## How Versions Work + +Each runner has a **version number**. When you deploy new code with a new version, Rivet handles the transition automatically: + +- **New actors go to the newest version**: When allocating actors, Rivet always prefers runners with the highest version number +- **Multiple versions can coexist**: Old actors continue running on old versions while new actors are created on the new version +- **Drain old actors**: When enabled, a runner connecting with a newer version number will gracefully stop old actors to be rescheduled to the new version + +Versions are not configured by default. See [Registry Configuration](/docs/general/registry-configuration) to learn how to configure the runner version. + +`RIVET_ENVOY_VERSION` is only needed when self-hosting or using a custom runner. Rivet Compute handles versioning automatically. + +### Example Scenario + +### Drain Enabled + +When a new version is deployed, existing actors are gracefully stopped on the old runner and rescheduled onto the new version. + +```mermaid +sequenceDiagram + participant R1 as Runner v1 + participant R2 as Runner v2 + + Note over R1: Currently running + Note over R2: Deployed + R2->>R1: Drain old actors + R1->>R2: Reschedule actors + Note over R1: Shut down when all actors stopped +``` + +### Drain Disabled + +When a new version is deployed, both versions coexist. New actors are created on the new version while existing actors continue running on the old version until. + +```mermaid +sequenceDiagram + participant R1 as Runner v1 + participant R2 as Runner v2 + + Note over R1: Currently running + Note over R2: Deployed + Note over R1: Actor 1 sleeps from inactivity + Note over R2: Actor 1 wakes up when prompted +``` + +## Configuration + +### Setting the Version + +Configure the runner version using an environment variable or programmatically: + +```bash {{"title": "Environment Variable"}} +RIVET_ENVOY_VERSION=2 +``` + +The version **must** be set at build time, not at runtime. Do not use `Date.now()` or similar runtime values in your registry setup code. This would assign a different version every time the server starts, causing actors to be drained and rescheduled on every restart instead of only on new deployments. + +### Example Configurations + +We recommend injecting a build-time value that increments with every deployment. Here are concrete examples for common setups: + +### Dockerfile + +Generate the version at build time and bake it into the image as an environment variable: + +```bash @nocheck +docker build --build-arg RIVET_ENVOY_VERSION=$(date +%s) . +``` + +```dockerfile @nocheck +FROM node:20-slim +ARG RIVET_ENVOY_VERSION +ENV RIVET_ENVOY_VERSION=$RIVET_ENVOY_VERSION +WORKDIR /app +COPY . . +RUN npm install && npm run build +CMD ["node", "dist/server.js"] +``` + +All containers from this image will share the same version. + +### Next.js + +Set the version in `next.config.ts`. Next.js evaluates this file once at build time and inlines the value into the bundle: + +```typescript @nocheck +import type { NextConfig } from "next"; + +const nextConfig: NextConfig = { + env: { + RIVET_ENVOY_VERSION: String(Math.floor(Date.now() / 1000)), + }, +}; + +export default nextConfig; +``` + +### Vite + +Use `define` in your Vite config. This is evaluated once at build time and inlined into the bundle: + +```typescript @nocheck +import { defineConfig } from "vite"; + +export default defineConfig({ + define: { + "process.env.RIVET_ENVOY_VERSION": JSON.stringify( + String(Math.floor(Date.now() / 1000)) + ), + }, +}); +``` + +### CI/CD + +Set the version from your CI pipeline: + +```yaml @nocheck +# GitHub Actions +env: + RIVET_ENVOY_VERSION: ${{ github.run_number }} +``` + +```bash @nocheck +# Railway / Render / generic CI +export RIVET_ENVOY_VERSION=$(date +%s) +``` + +```bash @nocheck +# Git commit count +export RIVET_ENVOY_VERSION=$(git rev-list --count HEAD) +``` + +### Build Script + +Generate a version file during your build step and import it: + +```json @nocheck +{ + "scripts": { + "build": "echo \"export const BUILD_VERSION = $(date +%s);\" > src/build-version.ts && tsc" + } +} +``` + +```typescript @nocheck +import { actor, setup } from "rivetkit"; +import { BUILD_VERSION } from "./build-version"; + +const myActor = actor({ state: {}, actions: {} }); + +const registry = setup({ + use: { myActor }, + envoy: { + version: BUILD_VERSION, + }, +}); +``` + +### Drain on Version Upgrade + +The `drainOnVersionUpgrade` option controls whether old actors are stopped when a new version is deployed. This is configured in the Rivet dashboard under your runner configuration. See [Pool Configuration](/docs/general/pool-configuration) for the full set of pool options, including how to rate-limit actor eviction during the drain. + +| Value | Behavior | +|-------|----------| +| `false` | Old actors continue running. New actors go to new version. Versions coexist. | +| `true` (default) | Old actors receive stop signal and have 30m to finish gracefully. | + +## Upgrading Actor State + +When you deploy a new version, existing actors may need to handle schema changes in their persisted data. + +### SQLite (recommended for complex schemas) + +**Drizzle (recommended)** + +Use [Drizzle](/docs/actors/sqlite-drizzle) for typed schemas with generated migrations. Drizzle generates versioned `.sql` migration files from your TypeScript schema and applies them in order automatically. This is the recommended approach when your schema evolves frequently. + +**Raw SQL** + +For actors using [raw SQLite](/docs/actors/sqlite), migrations run automatically via the `onMigrate` hook on every actor start. RivetKit wraps the hook in a SQLite savepoint, so the migration is fully atomic. Use SQLite's `user_version` pragma to track which migrations have run: + +### In-memory state (`c.state`) + +If you use `c.state` for persistence, you are responsible for handling schema changes yourself. If you add, remove, or rename fields between versions, your code must handle the old shape gracefully. + +**Manual defaults in `onWake`** + +Apply defaults for missing fields: + +**Zod schema coercion** + +Use [Zod](https://zod.dev/) to parse persisted state on wake. Zod's `.default()` fills in missing fields automatically, so old actor state is coerced to the current schema: + +For anything beyond simple defaults, consider moving to [SQLite](/docs/actors/sqlite) where you get proper migration tooling. + +## Advanced + +### How Version Upgrade Detection Works + +When `drainOnVersionUpgrade` is enabled, Rivet uses two mechanisms to detect version changes: + +- **New runner connection**: When a runner connects with a newer version number, the engine immediately drains all older runners with the same name. This is the primary mechanism for [runner mode](/docs/general/runtime-modes) deployments. +- **Metadata polling** (serverless only): In [serverless mode](/docs/general/runtime-modes), runners periodically poll the engine to check for newer versions and self-drain if one is found. This ensures old runners drain even if no new requests trigger a runner connection. + +### SIGTERM Handling + +When a runner process receives SIGTERM, it gracefully stops all actors before exiting: + +- Each actor's `onSleep` hook is called, giving it time to save state +- Actors are rescheduled to other available runners +- The runner waits up to **30 minutes** for all actors to finish stopping +- If the process is force-killed before actors finish (e.g. SIGKILL), actors are rescheduled with a crash backoff penalty instead of a clean handoff + +Actors have a maximum of 30 minutes to clean up during shutdown. Ensure your platform's drain grace period is at most 30 minutes. + +### Shutdown Timeouts + +Several timeouts control how long each part of the shutdown process can take: + +| Timeout | Default | Description | Configuration | +|---------|---------|-------------|---------------| +| `actor_stop_threshold` | 30m | Engine-side limit on how long each actor has to stop before being marked lost | [Engine config](/docs/self-hosting/configuration) (`pegboard.actor_stop_threshold`) | +| `sleepGracePeriod` | 15s | Total graceful sleep budget for `onSleep`, `waitUntil`, `keepAwake`, and async raw WebSocket handlers | [Actor options](/docs/actors/lifecycle#options) | +| `runner_lost_threshold` | 15s | Fallback detection if the runner dies without graceful shutdown | [Engine config](/docs/self-hosting/configuration) (`pegboard.runner_lost_threshold`) | + +Rivet has a max shutdown grace period of 30 minutes that cannot be configured. + +## Related + +- [Runtime Modes](/docs/general/runtime-modes): Serverless vs runner deployment modes +- [Lifecycle](/docs/actors/lifecycle): Actor lifecycle hooks including `onSleep` + +_Source doc path: /docs/actors/versions_ diff --git a/.agents/skills/cron-jobs/reference/actors/websocket-handler.md b/.agents/skills/cron-jobs/reference/actors/websocket-handler.md new file mode 100644 index 0000000..f94499d --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/websocket-handler.md @@ -0,0 +1,201 @@ +# Low-Level WebSocket Handler + +> Source: `src/content/docs/actors/websocket-handler.mdx` +> Canonical URL: https://rivet.dev/docs/actors/websocket-handler +> Description: Actors can handle WebSocket connections through the `onWebSocket` handler. + +--- +For most use cases, [actions](/docs/actors/actions) and [events](/docs/actors/events) provide high-level connection handling powered by WebSockets that's easier to work with than low-level WebSockets. However, low-level handlers are required when implementing custom use cases. + +## Handling WebSocket Connections + +The `onWebSocket` handler manages low-level WebSocket connections. It receives the actor context and a `WebSocket` object. + +See also the [raw WebSocket handler example](https://github.com/rivet-dev/rivet/tree/main/examples/raw-websocket-handler). + +## Connecting To Actors + +### Via RivetKit Client + +Use the `.webSocket()` method on an actor handle to open a WebSocket connection to the actor's `onWebSocket` handler. This can be executed from either your frontend or backend. + +```typescript index.ts @hide @nocheck +import { actor, setup } from "rivetkit"; + +export const chat = actor({ + state: { messages: [] as string[] }, + onWebSocket: (c, websocket) => { + websocket.addEventListener("message", (event) => { + c.state.messages.push(event.data as string); + }); + }, + actions: {} +}); + +export const registry = setup({ use: { chat } }); +registry.start(); +``` + +```typescript client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +const actor = client.chat.getOrCreate(["my-chat"]); + +// Open WebSocket connection +const ws = await actor.webSocket("/"); + +// Listen for messages +ws.addEventListener("message", (event) => { + const message = JSON.parse(event.data as string); + console.log("Received:", message); +}); + +// Send messages +ws.send(JSON.stringify({ type: "chat", text: "Hello!" })); +``` + +The `.webSocket()` method returns a standard WebSocket. + +### Via getGatewayUrl + +Use `.getGatewayUrl()` to get the raw gateway URL for the actor. This is useful when you need to use the URL with external tools or custom WebSocket clients. + +```typescript index.ts @hide @nocheck +import { actor, setup } from "rivetkit"; + +export const chat = actor({ + state: { messages: [] as string[] }, + onWebSocket: (c, websocket) => { + websocket.addEventListener("message", (event) => { + c.state.messages.push(event.data as string); + }); + }, + actions: {} +}); + +export const registry = setup({ use: { chat } }); +registry.start(); +``` + +```typescript client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +const actor = client.chat.getOrCreate(["my-chat"]); + +// Get the raw gateway URL +const gatewayUrl = await actor.getGatewayUrl(); +// gatewayUrl = "https://...rivet.dev/..." + +// Convert to WebSocket URL and connect +const wsUrl = gatewayUrl.replace("http://", "ws://").replace("https://", "wss://"); +const ws = new WebSocket(`${wsUrl}/websocket/`); + +ws.addEventListener("message", (event) => { + const message = JSON.parse(event.data as string); + console.log("Received:", message); +}); + +ws.addEventListener("open", () => { + ws.send(JSON.stringify({ type: "chat", text: "Hello!" })); +}); +``` + +### Via HTTP API + +This handler can be accessed with raw WebSockets using `wss://api.rivet.dev/gateway/{actorId}@{token}/websocket/{...path}`. + +For example, to connect to the chat actor above: + +```typescript +// Replace with your actor ID and token +const actorId = "your-actor-id"; +const token = "your-token"; + +const ws = new WebSocket( + `wss://api.rivet.dev/gateway/${actorId}@${token}/websocket/` +); + +ws.addEventListener("message", (event) => { + const message = JSON.parse(event.data as string); + console.log("Received:", message); +}); + +ws.addEventListener("open", () => { + ws.send(JSON.stringify({ type: "chat", text: "Hello!" })); +}); +``` + +```bash +wscat -c "wss://api.rivet.dev/gateway/{actorId}@{token}/websocket/" +``` + +The path after `/websocket/` is passed to your `onWebSocket` handler and can be used to route to different functionality within your actor. For example, to connect with a custom path `/admin`: + +```typescript +// Replace with your actor ID and token +const actorId = "your-actor-id"; +const token = "your-token"; + +const ws = new WebSocket( + `wss://api.rivet.dev/gateway/${actorId}@${token}/websocket/admin` +); +``` + +```bash +wscat -c "wss://api.rivet.dev/gateway/{actorId}@{token}/websocket/admin" +``` + +See the [HTTP API reference](/docs/actors/http-api) for more information on WebSocket routing and authentication. + +### Via Proxying Connections + +You can proxy WebSocket connections from your own server to actor handlers using the RivetKit client. This is useful when you need to add custom authentication or connection management before forwarding to actors. + +See also the [raw WebSocket handler with proxy example](https://github.com/rivet-dev/rivet/tree/main/examples/raw-websocket-handler-proxy). + +## Connection & Lifecycle Hooks + +`onWebSocket` will trigger the `onBeforeConnect`, `onConnect`, and `onDisconnect` hooks. Read more about [lifecycle hooks](/docs/actors/lifecycle). + +Open WebSockets will be listed in `c.conns`. `conn.send` and `c.broadcast` have no effect on low-level WebSocket connections. Read more about [connections](/docs/actors/connections). + +## WinterTC Compliance + +The `onWebSocket` handler uses standard WebSocket APIs and will work with existing libraries expecting WinterTC-compliant WebSocket objects. + +## Advanced + +## WebSocket Hibernation + +WebSocket hibernation allows actors to go to sleep while keeping WebSocket connections alive. Actors automatically wake up when a message is received or the connection closes. + +Enable hibernation by setting `canHibernateWebSocket: true`. You can also pass a function `(request) => boolean` for conditional control. + +Since `open` only fires once when the client first connects, use `c.conn.state` to store per-connection data that persists across sleep cycles. See [connections](/docs/actors/connections) for more details. + +### Accessing the Request + +The underlying HTTP request is available via `c.request`. This is useful for accessing the path or query parameters. + +### Skip Ready Wait + +Connections are normally held at the gateway until the actor is ready. Pass `skipReadyWait: true` on `handle.webSocket()` to connect immediately, including while the actor is still starting or in the [sleep grace period](/docs/actors/lifecycle#shutdown-sequence). See [Skip Ready Wait](/docs/clients/javascript#skip-ready-wait) for details. + +### Async Handlers + +The `onWebSocket` handler can be async, allowing you to perform async code before setting up event listeners: + +## API Reference + +- [`WebSocketContext`](/typedoc/interfaces/rivetkit.mod.WebSocketContext.html) - Context for WebSocket handlers +- [`UniversalWebSocket`](/typedoc/interfaces/rivetkit.mod.UniversalWebSocket.html) - Universal WebSocket interface +- [`handleRawWebSocketHandler`](/typedoc/functions/rivetkit.mod.handleRawWebSocketHandler.html) - Function to handle raw WebSocket +- [`UpgradeWebSocketArgs`](/typedoc/interfaces/rivetkit.mod.UpgradeWebSocketArgs.html) - Arguments for WebSocket upgrade + +_Source doc path: /docs/actors/websocket-handler_ diff --git a/.agents/skills/cron-jobs/reference/actors/workflows.md b/.agents/skills/cron-jobs/reference/actors/workflows.md new file mode 100644 index 0000000..9c59975 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/actors/workflows.md @@ -0,0 +1,228 @@ +# Workflows + +> Source: `src/content/docs/actors/workflows.mdx` +> Canonical URL: https://rivet.dev/docs/actors/workflows +> Description: Build durable, replayable run loops in Rivet Actors with steps, queue waits, timers, and rollback. + +--- +Use workflows for durable, multi-step execution with replay safety. + +## What are workflows? + +A workflow is a durable, replayable run handler for a Rivet Actor. + +- Survives restarts: workflow progress is saved automatically. +- Re-runs safely: replay follows the same recorded steps. +- Event-driven: workflows can pause for queue messages, then continue. + +## Getting started + +### Simple workflow + +Use this when you need a short multi-step sequence. + +### Loops + +This is the recommended workflow shape for most actor workloads. + +- Use a queue wait inside the loop to receive the next unit of work. +- Keep actor state changes in a single workflow loop. +- This gives you one durable workflow that manages all actor progress. + +### Setup & teardown + +Use this when the workflow should initialize resources, process queued commands, then clean up. + +## Features + +### Queue + +Use this for fire-and-forget commands where the client does not need a reply. + +Use the `Loops` example above as the baseline pattern. + +### Request/response (using queue) + +Use this when the caller needs a response from queued processing. + +### Timers + +Use queue messages as the trigger source, then sleep durably inside the workflow. + +### Join + +Use `join` when several independent tasks can run in parallel. + +### Race + +Use `race` when you need first-winner behavior. + +### Timeouts + +Use step timeouts and retries for slow or flaky dependencies. + +Step timeouts are critical by default and fail immediately. Set `retryOnTimeout: true` if a timeout should retry like any other error using `maxRetries`. + +Workflows use roll-forward semantics everywhere. When a step throws, any `state` or `vars` mutations it made before failing are never rolled back, whether the step retries or the failure is caught by `tryStep` or `try`. The next attempt observes whatever the failed attempt already wrote, so write steps idempotently: check before you increment, or move the mutation after the fallible work. + +### Handling terminal failures as data + +Use `tryStep` when a step failure should produce data instead of failing the whole workflow. + +Use `try` when you want to recover from terminal `step`, `join`, or `race` failures inside a named block. + +```ts +async function runPaymentFlow(ctx: any) { + return await ctx.try("payment-flow", async (blockCtx: any) => { + const auth = await blockCtx.step("authorize", async (blockCtx) => + authorizeOrder("order-123"), + ); + const capture = await blockCtx.step("capture", async (blockCtx) => + captureOrder("order-123"), + ); + return { auth, capture }; + }); +} + +async function authorizeOrder(orderId: string): Promise { + return `auth-${orderId}`; +} + +async function captureOrder(orderId: string): Promise { + return `capture-${orderId}`; +} +``` + +- `tryStep` and `try` only catch terminal failures. Retry backoff, sleeps, queue waits, eviction, and history divergence still rethrow. +- Catching a failure does not undo it. `state` and `vars` mutations made before the failure remain visible after `tryStep` or `try` returns, so use explicit compensating steps when a caught failure needs cleanup. +- `RollbackError` is not caught by default. Pass `catch: ["rollback"]` when you want rollback failures returned as data. + +### Error hooks + +Use `onError` when you want a best-effort notification for workflow failures. + +- Step failures include the attempt number, retry counts, whether the step will retry, and the next retry delay. +- Workflow failures also include terminal errors outside steps, such as rollback failures or code/history mismatches. +- The hook is observational. It is not part of workflow replay, so use it for logging, metrics, or updating non-critical actor state. +- This is also a good place to forward workflow failures to Sentry or another error reporting pipeline. + +### Rollback + +Use rollback checkpoints before steps that have compensating actions. + +## Patterns + +### Store workflow progress in state + broadcast + +Store progress in `state` so replay and recovery always restore it. Broadcast state changes so clients can render progress in realtime. + +### Cron (queue-driven) + +Rivet scheduling triggers actions. For cron-like workflows, use a small scheduled action as a bridge that enqueues work, then process that work in the workflow loop. + +These are common workflow shapes used in production systems. + +### Queue-driven worker + +Use this when external systems enqueue work and the actor should process each item durably. + +### Setup & teardown + +Use this when you need one-time initialization before a long-lived loop, plus cleanup when the actor stops sleeping or is destroyed. + +### Human approval gate + +Use this when an operation must pause for a user or system decision before continuing. + +### Fan-out / fan-in (join) + +Use this when independent work items can run in parallel and you need a single merged result. + +### Batch drainer + +Use this when throughput matters and handling one message at a time is too expensive. + +### Coordinator -> worker RPC + +Use this when one actor orchestrates work by calling actions on other actors. + +### Request/response over queue (async RPC) + +Use this when you want decoupled actor-to-actor communication with durable waits and explicit completion. + +### Scatter-gather across actors + +Use this when multiple actors can process independent parts of a request in parallel, then return a merged response. + +### Timeout + fallback actor + +Use this when a primary actor call might be slow or unavailable and you need a deterministic fallback path. + +### Cross-actor saga (compensating actions) + +Use this when a workflow spans multiple actors and each side effect may need compensation. + +### Signal-driven control loop + +Use this when workflow progress should be triggered by commands/events instead of fixed polling intervals. + +### Poll + backoff loop + +Use this when an external dependency has variable availability and retries should slow down after failures. + +### Child worker orchestration + +Use this when one workflow coordinates many child workers (actors or worker workflows) and manages their lifecycle. + +### Bounded drain + concurrency cap + +Use this when inbound work can spike and you need predictable per-iteration limits. + +### Versioned workflow evolution + +Use this when workflow structure changes across deployments and old histories must still replay. + +### Version gates with `getVersion` + +Use `ctx.getVersion(name, latest)` to branch behavior when you change a workflow's logic while old instances are still in flight. It returns the version this instance is pinned to at that point: + +- A fresh instance resolves to `latest`. +- An instance that already executed past this point under older code resolves to `1` (the implicit floor). + +The resolved version is recorded in history, so replays are deterministic and each instance stays on the branch it started on. Inside a loop, every iteration resolves independently, so in-flight iterations finish on the old branch while new iterations pick up `latest`. + +`latest` must be an integer `>= 1`, and the gate name must be unique within its scope like any other entry. Once every old instance has drained, retire the gate by replacing the call with `ctx.removed(name, "version_check")`. + +### Checkpoint-friendly loop design + +Use this when you need reliable replay and resume semantics across crashes and restarts. + +## Migrations + +- Keep workflow entry names stable once deployed. +- If an old entry was removed or renamed, call `ctx.removed(name, originalType)`. +- To change behavior at a point while old instances are still running, gate it with `ctx.getVersion(name, latest)` (see [Version gates](#version-gates-with-getversion)). +- This keeps replay compatible across deployments. + +## Step-only access to actor APIs + +`state`, `vars`, `db`, `client()`, and connection/event APIs are only valid inside `ctx.step(...)` callbacks. + +Use non-step workflow code for orchestration only: queue waits, sleeps, loops, joins, races, and rollback boundaries. Keep actor-local side effects in steps. + +## Debugging + +- `GET /inspector/workflow-history` returns workflow history status for an actor. +- Response includes `isWorkflowEnabled` and `history`. +- In non-dev mode, inspector endpoints require authorization. + +## Recommendations + +- Prefer queue-driven loops for long-lived workflows. +- Structure long-lived workflows with setup and teardown around the main loop. +- Keep actor state changes and side effects inside steps. +- Store workflow progress in `state` and broadcast updates as progress changes. +- Use timeouts and rollback for external side effects. +- Write step bodies idempotently. `state` and `vars` mutations from a failed attempt are never rolled back, whether the step retries or `tryStep`/`try` catches the failure. + +_Source doc path: /docs/actors/workflows_ diff --git a/.agents/skills/cron-jobs/reference/cli.md b/.agents/skills/cron-jobs/reference/cli.md new file mode 100644 index 0000000..34880ea --- /dev/null +++ b/.agents/skills/cron-jobs/reference/cli.md @@ -0,0 +1,103 @@ +# CLI + +> Source: `src/content/docs/cli.mdx` +> Canonical URL: https://rivet.dev/docs/cli +> Description: Reference for the optional rivet CLI: deploy to Rivet Compute and run local dev for serverless platforms. + +--- +The `rivet` CLI (`@rivetkit/cli`) is optional. You only need it for: + +| Use case | Command | +| --- | --- | +| Deploy to Rivet Compute | `rivet deploy` | +| Local dev for serverless platforms (Cloudflare, Supabase) | `rivet dev --provider ` | + +Run it with your package runner: + +```bash +npx @rivetkit/cli +``` + +| Command | Description | +| --- | --- | +| `rivet dev` | Run a local engine and your handler's dev server. | +| `rivet deploy` | Build and deploy the project to Rivet Cloud. | +| `rivet engine` | Run the bundled `rivet-engine` binary directly. | +| `rivet setup-ci` | Install the GitHub Actions deploy workflow. | + +## `rivet dev` + +Starts a local engine, spawns your dev server, and registers the serverless runner pointing at it. The engine keeps running across restarts; Ctrl-C stops only the dev server. + +```bash +rivet dev [--provider ] [--port N] [--fn-name NAME] [--url URL] [-- ...] +``` + +`--provider` selects how the dev server is launched. Anything after `--` is appended to the preset command (or is the command to run when no provider is set). + +| `--provider` | Spawns | Port | +| --- | --- | --- | +| _(omitted)_ | your `-- ` (needs `--port`) | from `--port` | +| `serverless` | your `-- ` (gets `PORT`) | auto | +| `cloudflare` | `wrangler dev` | `8787` | +| `supabase` | `supabase functions serve` | `54321` | +| `none` | nothing (engine only) | — | + +For `cloudflare`, the CLI also passes the engine endpoint as `--var RIVET_ENDPOINT:...`, so the Worker connects back with no `wrangler.toml` config. + +| Flag | Description | +| --- | --- | +| `--port` | Handler port. Required without a provider unless `--url` is set. | +| `--fn-name` | Supabase function name (default `rivet`). | +| `--url` | Explicit handler URL, overriding port and path. | +| `--engine-binary` | Path to a `rivet-engine` binary. | + +## `rivet deploy` + +Builds and pushes your project's Docker image and upserts the managed pool, printing the dashboard URL. See [Deploying to Rivet Compute](/docs/deploy/rivet-compute). + +```bash +rivet deploy --token cloud_api_xxxxx +``` + +The token is saved to `~/.rivet/credentials` (also read from `RIVET_CLOUD_TOKEN`), so later deploys can omit it. + +| Flag | Default | Description | +| --- | --- | --- | +| `--token` | env / credentials | Rivet Cloud API token. | +| `--namespace` | `production` | Cloud namespace. | +| `--project` / `--org` | from token | Override project/org. | +| `--dockerfile` | `Dockerfile` | Dockerfile to build. | +| `--build-context` | `.` | Docker build context. | +| `--env KEY=VAL` | — | Environment override, repeatable. | +| `--image` | project slug | Image repository name. | +| `--tag` | git short SHA | Image tag. | + +## `rivet engine` + +Runs the bundled `rivet-engine` binary directly, against the same local database and ports as `rivet dev`. Arguments are forwarded verbatim. + +```bash +rivet engine nuke # wipe local engine state +rivet engine wf list # inspect workflows +``` + +## `rivet setup-ci` + +Installs `.github/workflows/rivet-deploy.yml`, which deploys to Rivet Cloud on push and pull request. Add `--force` to overwrite. Then set the token secret: + +```bash +gh secret set RIVET_CLOUD_TOKEN +``` + +## Engine binary resolution + +`rivet dev` and `rivet engine` resolve the `rivet-engine` binary from, in order: `--engine-binary`, `RIVET_ENGINE_BINARY_PATH`, a binary bundled next to the CLI, a local `target/{debug,release}` build, then an auto-downloaded release. Set `RIVETKIT_ENGINE_AUTO_DOWNLOAD=0` to require a local binary. + +## Related + +- [Deploying to Rivet Compute](/docs/deploy/rivet-compute) +- [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) +- [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) + +_Source doc path: /docs/cli_ diff --git a/.agents/skills/cron-jobs/reference/clients/javascript.md b/.agents/skills/cron-jobs/reference/clients/javascript.md new file mode 100644 index 0000000..689d79b --- /dev/null +++ b/.agents/skills/cron-jobs/reference/clients/javascript.md @@ -0,0 +1,120 @@ +# Node.js & Bun + +> Source: `src/content/docs/clients/javascript.mdx` +> Canonical URL: https://rivet.dev/docs/clients/javascript +> Description: Connect JavaScript apps to Rivet Actors. + +--- +## Getting Started + +See the [backend quickstart guide](/docs/actors/quickstart/backend) for getting started. + +## Minimal Client + +## Stateless vs Stateful + +## Getting Actors + +## Connection Parameters + +Use `params` for static connection parameters. Use `getParams` when the value can change between connection attempts, such as refreshing a JWT before each `.connect()` or reconnect. + +## Subscribing to Events + +## Connection Lifecycle + +## Low-Level HTTP & WebSocket + +For actors that implement `onRequest` or `onWebSocket`, call them directly: + +```ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("history"); +const history = await response.json(); + +const ws = await handle.webSocket("stream"); +ws.addEventListener("message", (event) => { + console.log("message:", event.data); +}); +ws.send("hello"); +``` + +## Calling from Backend + +## Error Handling + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`createClient()` automatically reads: + +- `RIVET_ENDPOINT` (endpoint) +- `RIVET_NAMESPACE` +- `RIVET_TOKEN` +- `RIVET_RUNNER` + +Defaults to `http://localhost:6420` when unset. RivetKit runs on port 6420 by default. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, use your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## Advanced + +### Skip Ready Wait + +Requests are normally held at the gateway until the actor is ready to accept traffic. An actor is not ready while it's still starting (before `onWake` finishes) or while it's in the [sleep grace period](/docs/actors/lifecycle#shutdown-sequence) (running `onSleep`, `waitUntil`, and pending disconnects). + +Pass `skipReadyWait: true` on the [low-level HTTP and WebSocket APIs](#low-level-http--websocket) to deliver immediately and reach the actor's `onRequest` / `onWebSocket` handler in either window: + +```ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("/healthz", { + skipReadyWait: true, +}); + +const ws = await handle.webSocket("probe", undefined, { + skipReadyWait: true, +}); +``` + +Requests can still return transient lifecycle or gateway errors. Retry once the actor is available again. + +- `actor.stopping`: the actor has fully stopped, i.e. the sleep grace period has ended but it has not yet restarted. +- `guard.actor_stopped_while_waiting`: the request reached the actor tunnel, but the actor stopped before the gateway received a response. +- `guard.tunnel_request_aborted`: the actor tunnel aborted the request before a response started. +- `guard.tunnel_message_timeout`: the gateway dropped the in-flight tunnel request after its tunnel message timeout. +- `guard.tunnel_response_closed`: the actor tunnel closed before sending a response. +- `guard.gateway_response_start_timeout`: the gateway timed out waiting for the actor response to start. + +## API Reference + +**Package:** [rivetkit](https://www.npmjs.com/package/rivetkit) + +See the [RivetKit client overview](/docs/clients). + +- [`createClient`](/typedoc/functions/rivetkit.client_mod.createClient.html) - Create a client +- [`Client`](/typedoc/types/rivetkit.mod.Client.html) - Client type + +_Source doc path: /docs/clients/javascript_ diff --git a/.agents/skills/cron-jobs/reference/clients/react.md b/.agents/skills/cron-jobs/reference/clients/react.md new file mode 100644 index 0000000..9b976e2 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/clients/react.md @@ -0,0 +1,88 @@ +# React + +> Source: `src/content/docs/clients/react.mdx` +> Canonical URL: https://rivet.dev/docs/clients/react +> Description: Connect React apps to Rivet Actors. + +--- +## Getting Started + +See the [React quickstart guide](/docs/actors/quickstart/react) for getting started. + +## Install + +## Minimal Client + +## Stateless vs Stateful + +## Getting Actors + +## Connection Parameters + +## Subscribing to Events + +## Connection Lifecycle + +## Low-Level HTTP & WebSocket + +Use the JavaScript client for raw HTTP and WebSocket access: + +```tsx @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("history"); +const history = await response.json(); + +const ws = await handle.webSocket("stream"); +ws.addEventListener("message", (event) => { + console.log("message:", event.data); +}); +ws.send("hello"); +``` + +## Calling from Backend + +Use the JavaScript client on your backend (Node.js/Bun). See the [JavaScript client docs](/docs/clients/javascript). + +## Error Handling + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`createRivetKit()` (and the underlying `createClient()` instance) automatically read: + +- `RIVET_ENDPOINT` +- `RIVET_NAMESPACE` +- `RIVET_TOKEN` +- `RIVET_RUNNER` + +Defaults to `http://localhost:6420` when unset. RivetKit runs on port 6420 by default. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, use your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## API Reference + +**Package:** [@rivetkit/react](https://www.npmjs.com/package/@rivetkit/react) + +- [`createRivetKit`](/docs/clients/react) - Create hooks for React +- [`useActor`](/docs/clients/react) - Hook for actor instances + +_Source doc path: /docs/clients/react_ diff --git a/.agents/skills/cron-jobs/reference/clients/rust.md b/.agents/skills/cron-jobs/reference/clients/rust.md new file mode 100644 index 0000000..32bebfc --- /dev/null +++ b/.agents/skills/cron-jobs/reference/clients/rust.md @@ -0,0 +1,367 @@ +# Rust (Beta) + +> Source: `src/content/docs/clients/rust.mdx` +> Canonical URL: https://rivet.dev/docs/clients/rust +> Description: Connect Rust apps to Rivet Actors. + +--- +Rust support is in beta. The supported public Rust API is `rivetkit` and `rivetkit::client`; lower-level crates are internal implementation details and do not carry a stability guarantee. See the full API reference on [docs.rs/rivetkit](https://docs.rs/rivetkit), or the runnable [`hello-world-rust`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-rust) example. + +## Getting Started + +See the [Rust quickstart guide](/docs/actors/quickstart/rust) for getting started. + +## Install + +Add the `rivetkit` crate and its companions: + +```sh +cargo add rivetkit anyhow async-trait +cargo add serde --features derive +cargo add tokio --features full +``` + +The Rust client is strongly typed. It shares the same action and event types as your actor, so define your actor in `src/lib.rs` and import those types from both your server and your client. There is no need to redefine the actor on the client. See [Define Your Actor](/docs/actors/quickstart/rust#define-your-actor) in the quickstart for the actor definition this page builds on. + +## Minimal Client + +```rust @nocheck +use counter::{Counter, Increment}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + let count = counter.send(Increment { amount: 1 }).await?; + println!("New count: {count}"); + + Ok(()) +} +``` + +`counter` here is your crate name (the package `name` in `Cargo.toml`, with dashes as underscores). `Counter` and `Increment` are the types you defined alongside your actor. + +## Stateless vs Stateful + +```rust @nocheck +use counter::{Counter, Increment, NewCount}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + + // Stateless: each call is independent + counter.send(Increment { amount: 1 }).await?; + + // Stateful: keep a connection open for realtime events + let connection = counter.connect(); + connection + .on::(|event| println!("count: {}", event.count)) + .await; + connection.send(Increment { amount: 1 }).await?; + + connection.disconnect().await; + Ok(()) +} +``` + +A stateless call on the handle opens a short-lived request per action. A connection keeps a WebSocket open so you can receive events and reuse it across calls. + +## Getting Actors + +```rust @nocheck +use counter::Counter; +use rivetkit::{ + client::{Client, ClientConfig, GetOrCreateOptions}, + prelude::*, + TypedClientExt, +}; +use serde_json::json; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + // Get or create an actor + let room = client.get_or_create_typed_default::("counter", ["room-42"])?; + + // Get an existing actor handle (fails when used if the actor does not exist) + let existing = client.get_typed_default::("counter", ["room-42"])?; + + // Create a new actor with input + let created = client.get_or_create_typed::( + "counter", + ["game-1"], + GetOrCreateOptions { + create_with_input: Some(json!({ "mode": "ranked" })), + ..Default::default() + }, + )?; + + // Get an actor handle by ID + let by_id = client.get_for_id("counter", "actor-id", Default::default())?; + + // Resolve the actor ID + let resolved_id = room.inner().resolve().await?; + println!("Resolved ID: {resolved_id}"); + + Ok(()) +} +``` + +`get_typed_default` / `get_or_create_typed_default` use default options. The non-default variants (`get_typed` / `get_or_create_typed`) take `GetOptions` / `GetOrCreateOptions` for connection parameters, input, and region. + +## Connection Parameters + +Pass connection parameters through the handle options. They are delivered to the actor's `create_conn_state` callback: + +```rust @nocheck +use counter::Counter; +use rivetkit::{ + client::{Client, ClientConfig, GetOrCreateOptions}, + prelude::*, + TypedClientExt, +}; +use serde_json::json; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + let chat = client.get_or_create_typed::( + "counter", + ["general"], + GetOrCreateOptions { + params: Some(json!({ "authToken": "jwt-token-here" })), + ..Default::default() + }, + )?; + + let connection = chat.connect(); + connection.disconnect().await; + Ok(()) +} +``` + +## Subscribing to Events + +`on` registers a typed callback for an event and returns once the subscription is registered: + +```rust @nocheck +use counter::{Counter, NewCount}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let connection = client + .get_or_create_typed_default::("counter", ["general"])? + .connect(); + + connection + .on::(|event| println!("count changed: {}", event.count)) + .await; + + Ok(()) +} +``` + +Event callbacks are synchronous and run for every matching event. The actor's emitted event type (here `NewCount`) is decoded into the typed value for you. + +## Connection Lifecycle + +The lower-level connection exposes lifecycle callbacks and the current status. Reach it with `connection.inner()`: + +```rust @nocheck +use counter::Counter; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let connection = client + .get_or_create_typed_default::("counter", ["general"])? + .connect(); + let inner = connection.inner().clone(); + + inner.on_open(|| println!("connected")).await; + inner.on_close(|| println!("disconnected")).await; + inner.on_error(|message| eprintln!("error: {message}")).await; + inner + .on_status_change(|status| println!("status: {status:?}")) + .await; + + println!("current status: {:?}", inner.conn_status()); + + connection.disconnect().await; + Ok(()) +} +``` + +`ConnectionStatus` is one of `Idle`, `Connecting`, `Connected`, or `Disconnected`. Connections reconnect automatically with backoff until you call `disconnect`. + +## Low-Level HTTP & WebSocket + +For actors that implement `on_request` or `on_websocket`, call them directly on the untyped handle (`handle.inner()`). `fetch` returns a `reqwest::Response`, and `web_socket` returns a `tokio_tungstenite` stream. This example also needs a few extra crates: + +```sh +cargo add futures-util tokio-tungstenite +cargo add reqwest --features json +``` + +```rust @nocheck +use counter::Counter; +use futures_util::{SinkExt, StreamExt}; +use reqwest::{header::HeaderMap, Method}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; +use tokio_tungstenite::tungstenite::Message; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let handle = client.get_or_create_typed_default::("counter", ["general"])?; + + // Raw HTTP request + let response = handle + .inner() + .fetch("history", Method::GET, HeaderMap::new(), None) + .await?; + let history: Vec = response.json().await?; + println!("history: {history:?}"); + + // Raw WebSocket connection + let mut ws = handle.inner().web_socket("stream", None).await?; + ws.send(Message::text("hello")).await?; + if let Some(message) = ws.next().await { + println!("received: {:?}", message?); + } + + Ok(()) +} +``` + +## Calling from Backend + +The client is a normal Tokio type, so you can hold it in your backend (Axum, Actix, etc.) and call actors from request handlers. The client is `Clone` and cheap to share: + +```rust @nocheck +use counter::{Counter, Increment}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +async fn increment(client: Client) -> Result { + let counter = client.get_or_create_typed_default::("counter", ["server-counter"])?; + let count = counter.send(Increment { amount: 1 }).await?; + Ok(count) +} +``` + +## Error Handling + +Action and connection calls return `anyhow::Result`. Actor-side errors surface as an `anyhow::Error` carrying the error group, code, message, and metadata: + +```rust @nocheck +use counter::{Counter, Increment}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + + match counter.send(Increment { amount: 1 }).await { + Ok(count) => println!("count: {count}"), + Err(error) => eprintln!("action failed: {error:#}"), + } + + Ok(()) +} +``` + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```rust @nocheck +use counter::Counter; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + // Compound key: [org, room] + let room = client.get_or_create_typed_default::("counter", ["org-acme", "general"])?; + let actor_id = room.inner().resolve().await?; + println!("Actor ID: {actor_id}"); + + Ok(()) +} +``` + +Keys accept arrays of `&str` or `String` (`["org-acme", "general"]`). Don't build keys with string interpolation like `format!("org:{user_id}")` when `user_id` contains user data. Use arrays instead to prevent key injection attacks. + +### Configuration + +`ClientConfig::new(endpoint)` is a builder. The endpoint is always required; there is no default. Common options: + +```rust @nocheck +use rivetkit::client::ClientConfig; + +let config = ClientConfig::new("http://localhost:6420") + .namespace("default") + .token("pk_...") + .pool_name("my-pool") + .header("x-custom", "value"); +``` + +- `namespace` - target namespace (defaults to the engine's configured namespace). +- `token` - authentication token for the engine. +- `pool_name` - runner pool to target. +- `header` / `headers` - extra HTTP headers sent with each request. +- `max_input_size` - cap on encoded action input size. + +For serverless deployments, set the endpoint to your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints) for details. + +## API Reference + +See the full client API documentation on [docs.rs/rivetkit-client](https://docs.rs/rivetkit-client/latest/rivetkit_client/). + +_Source doc path: /docs/clients/rust_ diff --git a/.agents/skills/cron-jobs/reference/clients/swift.md b/.agents/skills/cron-jobs/reference/clients/swift.md new file mode 100644 index 0000000..c760645 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/clients/swift.md @@ -0,0 +1,454 @@ +# Swift + +> Source: `src/content/docs/clients/swift.mdx` +> Canonical URL: https://rivet.dev/docs/clients/swift +> Description: Connect Swift apps to Rivet Actors. + +--- +## Install + +Add the Swift package dependency and import `RivetKitClient`: + +```swift +// Package.swift +dependencies: [ + .package(url: "https://github.com/rivet-dev/rivetkit-swift", from: "2.0.0") +] + +targets: [ + .target( + name: "MyApp", + dependencies: [ + .product(name: "RivetKitClient", package: "rivetkit-swift") + ] + ) +] +``` + +## Minimal Client + +### Endpoint URL + +```swift +import RivetKitClient + +let config = try ClientConfig( + endpoint: "https://my-namespace:pk_...@api.rivet.dev" +) +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["my-counter"]) +let count: Int = try await handle.action("increment", 1, as: Int.self) +``` + +### Explicit Fields + +```swift +import RivetKitClient + +let config = try ClientConfig( + endpoint: "https://api.rivet.dev", + namespace: "my-namespace", + token: "pk_..." +) +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["my-counter"]) +let count: Int = try await handle.action("increment", 1, as: Int.self) +``` + +## Stateless vs Stateful + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["my-counter"]) + +// Stateless: each call is independent +let current: Int = try await handle.action("getCount", as: Int.self) +print("Current count: \(current)") + +// Stateful: keep a connection open for realtime events +let conn = handle.connect() + +// Subscribe to events using AsyncStream +let eventTask = Task { + for await count in await conn.events("count", as: Int.self) { + print("Event: \(count)") + } +} + +_ = try await conn.action("increment", 1, as: Int.self) + +eventTask.cancel() +await conn.dispose() +await client.dispose() +``` + +## Getting Actors + +```swift +import RivetKitClient + +struct GameInput: Encodable { + let mode: String +} + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +// Get or create an actor +let room = client.getOrCreate("chatRoom", ["room-42"]) + +// Get an existing actor (fails if not found) +let existing = client.get("chatRoom", ["room-42"]) + +// Create a new actor with input +let created = try await client.create( + "game", + ["game-1"], + options: CreateOptions(input: GameInput(mode: "ranked")) +) + +// Get actor by ID +let byId = client.getForId("chatRoom", "actor-id") + +// Resolve actor ID +let resolvedId = try await room.resolve() +print("Resolved ID: \(resolvedId)") + +await client.dispose() +``` + +Actions support positional overloads for 0–5 args: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("counter", ["my-counter"]) + +let count: Int = try await handle.action("getCount") +let updated: String = try await handle.action("rename", "new-name") +let ok: Bool = try await handle.action("setScore", "user-1", 42) + +print("Count: \(count), Updated: \(updated), OK: \(ok)") +await client.dispose() +``` + +If you need more than 5 arguments, use the raw JSON fallback: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("counter", ["my-counter"]) + +let args: [JSONValue] = [ + .string("user-1"), + .number(.int(42)), + .string("extra"), + .string("more"), + .string("args"), + .string("here") +] +let ok: Bool = try await handle.action("setScore", args: args, as: Bool.self) +print("OK: \(ok)") + +await client.dispose() +``` + +## Connection Parameters + +```swift +import RivetKitClient + +struct ConnParams: Encodable { + let authToken: String +} + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +let chat = client.getOrCreate( + "chatRoom", + ["general"], + options: GetOrCreateOptions(params: ConnParams(authToken: "jwt-token-here")) +) + +let conn = chat.connect() + +// Use the connection... +for await status in await conn.statusChanges() { + print("Status: \(status.rawValue)") + if status == .connected { + break + } +} + +await conn.dispose() +await client.dispose() +``` + +## Subscribing to Events + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let conn = client.getOrCreate("chatRoom", ["general"]).connect() + +// Subscribe to events using AsyncStream +let messageTask = Task { + for await (from, body) in await conn.events("message", as: (String, String).self) { + print("\(from): \(body)") + } +} + +// For one-time events, break after receiving +let gameOverTask = Task { + for await _ in await conn.events("gameOver", as: Void.self) { + print("done") + break + } +} + +// Let it run for a bit +try await Task.sleep(for: .seconds(5)) + +// Cancel when done +messageTask.cancel() +gameOverTask.cancel() +await conn.dispose() +await client.dispose() +``` + +Event streams support 0–5 typed arguments. If you need raw values or more than 5 arguments, use `JSONValue`: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let conn = client.getOrCreate("chatRoom", ["general"]).connect() + +let rawTask = Task { + for await args in await conn.events("message") { + print(args) + } +} + +try await Task.sleep(for: .seconds(5)) +rawTask.cancel() +await conn.dispose() +await client.dispose() +``` + +## Connection Lifecycle + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let conn = client.getOrCreate("chatRoom", ["general"]).connect() + +// Monitor status changes (immediately yields current status) +let statusTask = Task { + for await status in await conn.statusChanges() { + print("status: \(status.rawValue)") + } +} + +// Monitor errors +let errorTask = Task { + for await error in await conn.errors() { + print("error: \(error.group).\(error.code)") + } +} + +// Monitor open/close events +let openTask = Task { + for await _ in await conn.opens() { + print("connected") + } +} + +let closeTask = Task { + for await _ in await conn.closes() { + print("disconnected") + } +} + +// Check current status +let current = await conn.currentStatus +print("Current status: \(current.rawValue)") + +// Let it run for a bit +try await Task.sleep(for: .seconds(5)) + +// Cleanup +statusTask.cancel() +errorTask.cancel() +openTask.cancel() +closeTask.cancel() +await conn.dispose() +await client.dispose() +``` + +## Low-Level HTTP & WebSocket + +For actors that implement `onRequest` or `onWebSocket`, you can call them directly: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("chatRoom", ["general"]) + +// Raw HTTP request +let response = try await handle.fetch("history") +let history: [String] = try response.json([String].self) +print("History: \(history)") + +// Raw WebSocket connection +let websocket = try await handle.websocket(path: "stream") +try await websocket.send(text: "hello") +let message = try await websocket.receive() +print("Received: \(message)") + +await client.dispose() +``` + +## Calling from Backend + +Use the same client in server-side Swift (Vapor, Hummingbird, etc.): + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["server-counter"]) +let count: Int = try await handle.action("increment", 1, as: Int.self) +print("Count: \(count)") + +await client.dispose() +``` + +## Error Handling + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +do { + _ = try await client.getOrCreate("user", ["user-123"]) + .action("updateUsername", "ab", as: String.self) +} catch let error as ActorError { + print("Error code: \(error.code)") + print("Metadata: \(String(describing: error.metadata))") +} + +await client.dispose() +``` + +If you need an untyped response, you can decode to `JSONValue`: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("data", ["raw"]) + +let value: JSONValue = try await handle.action("getRawPayload") +print("Raw value: \(value)") + +await client.dispose() +``` + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +// Use compound keys for hierarchical addressing +let room = client.getOrCreate("chatRoom", ["org-acme", "general"]) +let actorId = try await room.resolve() +print("Actor ID: \(actorId)") + +await client.dispose() +``` + +Don't build keys with string interpolation like `"org:\(userId)"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`ClientConfig` reads optional values from environment variables: + +- `RIVET_NAMESPACE` - Namespace (can also be in endpoint URL) +- `RIVET_TOKEN` - Authentication token (can also be in endpoint URL) +- `RIVET_RUNNER` - Runner name (defaults to `"default"`) + +The `endpoint` parameter is always required. There is no default endpoint. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, set the endpoint to your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## API Reference + +### Client +- `RivetKitClient(config:)` - Create a client with a config +- `ClientConfig` - Configure endpoint, namespace, and token +- `client.get()` / `getOrCreate()` / `getForId()` / `create()` - Get actor handles +- `client.dispose()` - Dispose the client and all connections + +### ActorHandle +- `handle.action(name, args..., as:)` - Stateless action call +- `handle.connect()` - Create a stateful connection +- `handle.resolve()` - Get the actor ID +- `handle.getGatewayUrl()` - Get the raw gateway URL +- `handle.fetch(path, request:)` - Raw HTTP request +- `handle.websocket(path:)` - Raw WebSocket connection + +### ActorConnection +- `conn.action(name, args..., as:)` - Action call over WebSocket +- `conn.events(name, as:)` - AsyncStream of typed events +- `conn.statusChanges()` - AsyncStream of status changes +- `conn.errors()` - AsyncStream of connection errors +- `conn.opens()` - AsyncStream that yields on connection open +- `conn.closes()` - AsyncStream that yields on connection close +- `conn.currentStatus` - Current connection status +- `conn.dispose()` - Close the connection + +### Types +- `ActorConnStatus` - Connection status enum (`.idle`, `.connecting`, `.connected`, `.disconnected`, `.disposed`) +- `ActorError` - Typed actor errors with `group`, `code`, `message`, `metadata` +- `JSONValue` - Raw JSON value for untyped responses + +_Source doc path: /docs/clients/swift_ diff --git a/.agents/skills/cron-jobs/reference/clients/swiftui.md b/.agents/skills/cron-jobs/reference/clients/swiftui.md new file mode 100644 index 0000000..4ae65d8 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/clients/swiftui.md @@ -0,0 +1,359 @@ +# SwiftUI + +> Source: `src/content/docs/clients/swiftui.mdx` +> Canonical URL: https://rivet.dev/docs/clients/swiftui +> Description: Build SwiftUI apps with Rivet Actors. + +--- +## Install + +Add the Swift package dependency and import `RivetKitSwiftUI`: + +```swift +// Package.swift +dependencies: [ + .package(url: "https://github.com/rivet-dev/rivetkit-swift", from: "2.0.0") +] + +targets: [ + .target( + name: "MyApp", + dependencies: [ + .product(name: "RivetKitSwiftUI", package: "rivetkit-swift") + ] + ) +] +``` + +`RivetKitSwiftUI` re-exports `RivetKitClient` and `SwiftUI`, so a single import covers both. + +## Minimal Client + +```swift HelloWorldApp.swift +import RivetKitSwiftUI +import SwiftUI + +@main +struct HelloWorldApp: App { + var body: some Scene { + WindowGroup { + ContentView() + .rivetKit(endpoint: "https://my-namespace:pk_...@api.rivet.dev") + } + } +} +``` + +```swift ContentView.swift +import RivetKitSwiftUI +import SwiftUI + +struct ContentView: View { + @Actor("counter", key: ["my-counter"]) private var counter + @State private var count = 0 + + var body: some View { + VStack(spacing: 16) { + Text("\(count)") + .font(.system(size: 64, weight: .bold, design: .rounded)) + + Button("Increment") { + counter.send("increment", 1) + } + .disabled(!counter.isConnected) + } + .task { + count = (try? await counter.action("getCount")) ?? 0 + } + .onActorEvent(counter, "newCount") { (newCount: Int) in + count = newCount + } + } +} +``` + +## Actor Options + +The `@Actor` property wrapper always uses get-or-create semantics and accepts: + +- `name` (required) +- `key` as `String` or `[String]` (required) +- `params` (optional connection parameters) +- `createWithInput` (optional creation input) +- `createInRegion` (optional creation hint) +- `enabled` (toggle connection lifecycle) + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct ConnParams: Encodable { + let authToken: String +} + +struct ChatView: View { + @Actor( + "chatRoom", + key: ["general"], + params: ConnParams(authToken: "jwt-token"), + enabled: true + ) private var chat + + var body: some View { + Text("Chat: \(chat.connStatus.rawValue)") + } +} +``` + +## Actions + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct CounterView: View { + @Actor("counter", key: ["my-counter"]) private var counter + @State private var count = 0 + @State private var name = "" + + var body: some View { + VStack { + Text("Count: \(count)") + Text("Name: \(name)") + + Button("Fetch") { + Task { + count = try await counter.action("getCount") + name = try await counter.action("rename", "new-name") + } + } + + Button("Increment") { + counter.send("increment", 1) + } + } + } +} +``` + +## Subscribing to Events + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct GameView: View { + @Actor("game", key: ["game-1"]) private var game + @State private var count = 0 + @State private var isGameOver = false + + var body: some View { + VStack { + Text("Count: \(count)") + if isGameOver { + Text("Game Over!") + } + } + .onActorEvent(game, "newCount") { (newCount: Int) in + count = newCount + } + .onActorEvent(game, "gameOver") { + isGameOver = true + } + } +} +``` + +## Async Event Streams + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct ChatView: View { + @Actor("chatRoom", key: ["general"]) private var chat + @State private var messages: [String] = [] + + var body: some View { + List(messages, id: \.self) { message in + Text(message) + } + .task { + for await message in chat.events("message", as: String.self) { + messages.append(message) + } + } + } +} +``` + +## Connection Status + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct StatusView: View { + @Actor("counter", key: ["my-counter"]) private var counter + @State private var count = 0 + + var body: some View { + VStack { + Text("Status: \(counter.connStatus.rawValue)") + + if counter.connStatus == .connected { + Text("Connected!") + .foregroundStyle(.green) + } + + Button("Fetch via Handle") { + Task { + if let handle = counter.handle { + count = try await handle.action("getCount", as: Int.self) + } + } + } + .disabled(!counter.isConnected) + } + } +} +``` + +## Error Handling + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct UserView: View { + @Actor("user", key: ["user-123"]) private var user + @State private var errorMessage: String? + @State private var username = "" + + var body: some View { + VStack { + TextField("Username", text: $username) + + Button("Update Username") { + Task { + do { + let _: String = try await user.action("updateUsername", username) + } catch let error as ActorError { + errorMessage = "\(error.code): \(String(describing: error.metadata))" + } + } + } + + if let errorMessage { + Text(errorMessage) + .foregroundStyle(.red) + } + } + .onActorError(user) { error in + errorMessage = "\(error.group).\(error.code): \(error.message)" + } + } +} +``` + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct OrgChatView: View { + @Actor("chatRoom", key: ["org-acme", "general"]) private var room + + var body: some View { + Text("Room: \(room.connStatus.rawValue)") + } +} +``` + +Don't build keys with string interpolation like `"org:\(userId)"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Configuration + +Call `.rivetKit(endpoint:)` or `.rivetKit(client:)` once at the root of your view tree: + +```swift +// With endpoint string (recommended for most apps) +@main +struct MyApp: App { + var body: some Scene { + WindowGroup { + ContentView() + .rivetKit(endpoint: "https://my-namespace:pk_...@api.rivet.dev") + } + } +} + +// With custom client (for advanced configuration) +@main +struct MyApp: App { + private let client = RivetKitClient( + config: try! ClientConfig(endpoint: "https://api.rivet.dev", token: "pk_...") + ) + + var body: some Scene { + WindowGroup { + ContentView() + .rivetKit(client: client) + } + } +} +``` + +When using `.rivetKit(endpoint:)`, the client is created once and cached per endpoint. When using `.rivetKit(client:)`, store the client as a property on `App` (not inside `body`) since SwiftUI can call `body` multiple times. + +### Environment Variables + +`ClientConfig` reads optional values from environment variables: + +- `RIVET_NAMESPACE` - Namespace (can also be in endpoint URL) +- `RIVET_TOKEN` - Authentication token (can also be in endpoint URL) +- `RIVET_RUNNER` - Runner name (defaults to `"default"`) + +The endpoint is always required. There is no default endpoint. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, set the endpoint to your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## API Reference + +### Property Wrapper +- `@Actor(name, key:, params:, createWithInput:, createInRegion:, enabled:)` - SwiftUI property wrapper for actor connections + +### View Modifiers +- `.rivetKit(endpoint:)` - Configure client with an endpoint URL (creates cached client) +- `.rivetKit(client:)` - Configure client with a custom instance +- `.onActorEvent(actor, event) { ... }` - Subscribe to actor events (supports 0–5 typed args) +- `.onActorError(actor) { error in ... }` - Handle actor errors + +### ActorObservable +- `actor.action(name, args..., as:)` - Async action call +- `actor.send(name, args...)` - Fire-and-forget action +- `actor.events(name, as:)` - AsyncStream of typed events +- `actor.connStatus` - Current connection status +- `actor.isConnected` - Whether connected +- `actor.handle` - Underlying `ActorHandle` (optional) +- `actor.connection` - Underlying `ActorConnection` (optional) +- `actor.error` - Most recent error (optional) + +### Types +- `ActorConnStatus` - Connection status enum (`.idle`, `.connecting`, `.connected`, `.disconnected`, `.disposed`) +- `ActorError` - Typed actor errors with `group`, `code`, `message`, `metadata` + +_Source doc path: /docs/clients/swiftui_ diff --git a/.agents/skills/cron-jobs/reference/cookbook/ai-agent.md b/.agents/skills/cron-jobs/reference/cookbook/ai-agent.md new file mode 100644 index 0000000..1adb285 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/cookbook/ai-agent.md @@ -0,0 +1,127 @@ +# AI Agent + +> Source: `src/content/cookbook/ai-agent.mdx` +> Canonical URL: https://rivet.dev/cookbook/ai-agent +> Description: Build an AI agent backend with persistent memory: one Rivet Actor per conversation, queued message handling, and streaming LLM responses as realtime events. + +--- +Patterns for building AI agent backends with RivetKit, where each conversation is one Rivet Actor that owns its memory, its message queue, and its streaming output. + +## Starter Code + +Start with one of the working examples on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/ai-agent) and adapt it. The sections below describe the flagship `ai-agent` example unless a variant is called out explicitly. + +| Variant | Starter Code | Use When | +| --- | --- | --- | +| Queue-driven AI SDK agent | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/ai-agent) | You want a streaming chat agent where each conversation keeps its own persistent memory and processes one message at a time. | +| Sandbox coding agent | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/sandbox-coding-agent) | The agent should run a coding agent (Codex by default) inside an isolated [sandbox](/docs/actors/sandbox) via Docker, Daytona, or E2B. | +| Durable streams agent (experimental) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/experimental-durable-streams-ai-agent) | You want replayable, restart-safe prompt and response delivery through durable streams instead of actor state and events. | + +## Conversation Memory + +Use one actor per conversation, keyed by a conversation or agent id (see [Actor Keys](/docs/actors/keys)). The agent actor's persistent [state](/docs/actors/state) is the conversation memory: in the `ai-agent` example, `messages` and `status` live in JSON actor state and survive sleep and restarts with no external database. Every model call rebuilds the prompt from `c.state.messages` plus a system prompt, so memory and inference input are the same data. + +| Variant | Where Memory Lives | Persisted State Fields | +| --- | --- | --- | +| `ai-agent` | JSON actor state | `messages`, `status` | +| `sandbox-coding-agent` | JSON actor state plus the sandbox ACP session | `messages`, `status`, `sessionId` | +| `experimental-durable-streams-ai-agent` | Durable streams; the actor stores only its conversation id and a read cursor | `conversationId`, `promptStreamOffset` | + +## Message Handling + +In the `ai-agent` example, the client pushes user input onto the agent's `message` [queue](/docs/actors/queues) with `agent.connection.send("message", { text, sender })`. This is a queue push, not an action call. The actor's `run` hook (see [Lifecycle](/docs/actors/lifecycle)) consumes the queue serially with `for await (const queued of c.queue.iter())`. + +Serial queue consumption is the per-conversation concurrency guarantee: at most one in-flight model call per actor, with no extra locking. The `status` field (`thinking` while a model call is in flight) is UI signal only; the run loop is the actual lock. The loop also checks `c.aborted` inside the token stream so shutdown exits gracefully. + +| Variant | Message Ingress | Serialization Guarantee | +| --- | --- | --- | +| `ai-agent` | `message` queue pushed via `connection.send` | `run` hook pops one queued message at a time with `c.queue.iter()`. | +| `sandbox-coding-agent` | `sendMessage` [action](/docs/actors/actions), no queue | Each call awaits the sandbox round trip before broadcasting the result. | +| `experimental-durable-streams-ai-agent` | Durable prompt stream long-polled from `onWake` | `promptStreamOffset` is persisted per chunk, so restarts resume without reprocessing prompts. | + +## Streaming Responses + +The `ai-agent` actor broadcasts a `response` [event](/docs/actors/events) for every model text delta. The payload carries `messageId`, the per-token `delta`, the cumulative `content`, and a `done` flag (plus `error` on failure), so clients can either append deltas or idempotently replace the message by `messageId` using `content`. The example frontend replaces by `messageId`, which tolerates dropped events. The terminal broadcast has an empty `delta`, the full `content`, and `done: true`. + +Because the assistant message object lives in `c.state.messages` and is mutated in place during streaming, partial content persists if the actor restarts mid-stream. The example broadcasts once per AI SDK delta with no throttling; batching or throttling deltas is a recommended extension for high-traffic deployments, not something the example implements. + +Variant differences: `sandbox-coding-agent` sends a single `response` broadcast with `done: true` after the sandbox finishes (no incremental streaming), and `experimental-durable-streams-ai-agent` appends per-token chunks to a durable response stream, then broadcasts `responseComplete` or `responseError`. + +## Architecture + +| Topic | Summary | +| --- | --- | +| Topology | `agentManager["primary"]` singleton directory plus one `agent[agentId]` actor per conversation. | +| Ingress | Client pushes `AgentQueueMessage` payloads onto the agent's `message` queue with `connection.send`. | +| Streaming | One `response` broadcast per model delta, terminal broadcast with `done: true`. | +| Memory | Full transcript and status in JSON actor state; no external database. | + +The manager creates `AgentInfo` records and warms each agent through [actor-to-actor communication](/docs/actors/communicating-between-actors): `createAgent` calls `c.client()`, then `client.agent.getOrCreate([info.id])` and awaits `getStatus()` so the conversation actor exists before the client connects. The sandbox variant extends this topology with a `codingSandbox` actor that shares the agent's key (`codingSandbox.getOrCreate([c.key[0]])`), so the agent-to-sandbox mapping is implicit in the key space. + +**Actors** + +- **Key**: `agentManager["primary"]` +- **Responsibility**: Directory actor. Creates `AgentInfo` records, lists agents, and warms each agent actor via `c.client()`. +- **Actions** + - `createAgent` + - `listAgents` +- **Queues** + - None +- **State** + - JSON + - `agents` + +- **Key**: `agent[agentId]` +- **Responsibility**: One actor per conversation. Holds the full message history and status, consumes queued user messages in its `run` loop, calls the model via the AI SDK, and broadcasts streaming deltas. +- **Actions** + - `getHistory` + - `getStatus` +- **Queues** + - `message` +- **Events** + - `messageAdded` + - `status` + - `response` +- **State** + - JSON + - `messages` + - `status` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant AM as agentManager + participant A as agent + participant LLM as Model API + + C->>AM: createAgent(name) + AM->>A: getOrCreate([info.id]) + getStatus() + AM-->>C: AgentInfo + C->>A: connection.send("message", {text, sender}) + Note over A: run loop pops queue via c.queue.iter() + A-->>C: messageAdded (user message) + A-->>C: messageAdded (assistant placeholder) + A-->>C: status (thinking) + A->>LLM: streamText(system prompt + history) + loop each text delta + LLM-->>A: delta + A-->>C: response {messageId, delta, content, done: false} + end + A-->>C: response {delta: "", content, done: true} + A-->>C: status (idle) +``` + +## Security Checklist + +The examples ship without auth so they stay minimal. Apply this baseline before exposing an agent backend. + +- **API keys stay server-side**: `OPENAI_API_KEY` (or `ANTHROPIC_API_KEY`) is read by the AI SDK inside the actor process. The key never reaches the browser; clients only talk to the actor over RivetKit. The sandbox variant forwards keys into the sandbox env, never to the client. +- **Add authentication**: The examples have no auth, so anyone who reaches the server can create agents, list them, and message any agent whose key they can guess. Add `onBeforeConnect` or `createConnState` checks with scoped tokens as a recommended extension. See [Authentication](/docs/actors/authentication). +- **Validate and rate-limit queue payloads**: The example only skips bodies without a string `text`. Enforce payload size limits, schema validation, and per-connection rate limits as a recommended extension. +- **Derive sender identity server-side**: The example trusts the client-supplied `sender` field verbatim. Bind sender identity to the authenticated connection instead. +- **Cap or trim message history**: The example sends the full transcript on every model call with no cap. Trim or summarize old messages as a recommended extension so prompts and state stay bounded. +- **Set cost ceilings per conversation**: Add per-agent token budgets and quotas as a recommended extension. The sandbox variant runs real compute, so also enforce per-user sandbox quotas and restrict sandbox network egress. + +_Source doc path: /cookbook/ai-agent_ diff --git a/.agents/skills/cron-jobs/reference/cookbook/chat-room.md b/.agents/skills/cron-jobs/reference/cookbook/chat-room.md new file mode 100644 index 0000000..cb8dbe4 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/cookbook/chat-room.md @@ -0,0 +1,114 @@ +# Chat Room + +> Source: `src/content/cookbook/chat-room.mdx` +> Canonical URL: https://rivet.dev/cookbook/chat-room +> Description: Build a realtime chat room backend with Rivet Actors: one actor per room, SQLite-backed message history, and WebSocket broadcast to every connected client. + +--- +Patterns for building a chat room backend with RivetKit: room-scoped actors, persistent message history, and realtime delivery over WebSocket connections. + +## Starter Code + +Start with the working example on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room) and adapt it. The backend is a single `chatRoom` actor; the frontend is a React app using `@rivetkit/react` (see the [React quickstart](/docs/actors/quickstart/react)). + +| Topic | Summary | +| --- | --- | +| Room model | One `chatRoom` actor per room key. The frontend defaults the key to `general`; typing a different room name connects to a different actor. | +| History | SQLite `messages` table created in `db({ onMigrate })`, read back with `ORDER BY id ASC`. | +| Delivery | `sendMessage` inserts the row, then broadcasts a typed `newMessage` event to every connected client. | +| Identity | None in the example. `sender` is a plain action argument; production should bind identity to the connection. | + +## Room-Per-Actor Model + +Each room is one Rivet Actor instance, addressed by [key](/docs/actors/keys). The client calls `useActor({ name: "chatRoom", key: [roomId] })`, which gets-or-creates the actor for that room. This gives you: + +- **Isolation**: each room's history and connections are fully scoped to its key. Switching the room input re-keys the hook and connects to a different actor with separate history. +- **A single serialized writer**: all `sendMessage` calls for one room run through one actor, so message ordering is consistent without locks. The SQLite `AUTOINCREMENT` id is the canonical order, which is why `getHistory` sorts by `id` rather than by timestamp. +- **Natural scaling**: rooms spread across the cluster independently. A hot room does not slow down other rooms. + +## Message History Storage + +This example stores history in the actor's SQLite database, not in JSON state. Pick based on history size and query needs: + +| Approach | Use When | Implementation Guidance | +| --- | --- | --- | +| [SQLite](/docs/actors/sqlite) (what this example uses) | Large or long-lived history that needs ordering, caps, pagination, or search | Create the `messages` table in `db({ onMigrate })`, insert with parameterized queries (`c.db.execute("INSERT ... VALUES (?, ?, ?)", ...)`), and read with `ORDER BY id ASC`. History survives actor sleep and scales past what you want in memory. | +| [JSON state](/docs/actors/state) | Small recent history, for example the last 50 to 100 messages | Push onto a `messages` array in actor state and trim to a cap on every send. Simplest option, but the whole history lives in memory and there is no query layer, so it only fits bounded recent-history use cases. | + +## Broadcast Delivery + +New messages reach connected clients through a typed [event](/docs/actors/events): + +- The actor declares `events: { newMessage: event() }`, where `Message` is `{ sender, text, timestamp }`. +- The `sendMessage` [action](/docs/actors/actions) builds the message with a server-side `Date.now()` timestamp, inserts it into the `messages` table, then calls `c.broadcast("newMessage", message)` and returns the message to the caller. +- Each client subscribes with `useEvent("newMessage", ...)` and appends to its local list. The sender renders its own message through the same broadcast path as everyone else, so all clients stay on one code path. +- History load is connection-gated: once the connection is ready, the client calls `getHistory()` once to render the backlog, then relies on events for everything after. + +Use `c.broadcast(...)` for room-wide messages. For private or per-recipient payloads (such as DMs inside a room), send on the individual connection instead, which is a recommended extension beyond this example. + +## Typing Indicators And Presence (Extension) + +The example does not implement typing indicators, presence, or join/leave handling of any kind. There is no `createConnState`, `onConnect`, or `onDisconnect` in the code. If you need them, add them as ephemeral [connection](/docs/actors/connections) behavior: + +- **Keep it ephemeral**: store the username and typing flag in per-connection state, never in SQLite or persisted actor state. Presence is derived from live connections and should disappear with them. +- **Broadcast on change only**: emit a typing event when a user starts or stops typing, and a presence event from `onConnect` / `onDisconnect`, rather than polling or ticking. +- **Expire on the client**: clear a typing indicator after a short client-side timeout so a dropped connection never leaves a stuck "is typing" row. + +## Per-User Inbox (Extension) + +For offline delivery, DMs, unread counts, or notification fanout, add a `userInbox[userId]` actor per user. This is an extension beyond the example: + +- The room actor forwards each message to the inbox actor of every member via [actor-to-actor calls](/docs/actors/communicating-between-actors), so users who are not connected to the room still accumulate messages. +- The inbox actor owns per-user unread state and serves it when the user comes online, independent of which rooms they are in. +- DMs become a degenerate room: either a `chatRoom` keyed by the sorted pair of user ids, or direct inbox-to-inbox delivery if you do not need shared history semantics. + +## Actors + +- **Key**: `chatRoom[roomId]` +- **Responsibility**: Owns one chat room. Persists the room's message history in its SQLite database and broadcasts each new message to every connected client. +- **Actions** + - `sendMessage` + - `getHistory` +- **Queues** + - None +- **Events** + - `newMessage` +- **State** + - SQLite + - `messages` table: `id` (autoincrement primary key), `sender`, `text`, `timestamp` + +## Lifecycle + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant R as chatRoom + + A->>R: connect with key [roomId] + Note over R: every start runs onMigrate (CREATE TABLE IF NOT EXISTS messages) + A->>R: getHistory() + R-->>A: Message[] ordered by id + B->>R: connect with key [roomId] + B->>R: getHistory() + R-->>B: Message[] ordered by id + A->>R: sendMessage(sender, text) + Note over R: INSERT row with server timestamp + R-->>A: newMessage (broadcast) + R-->>B: newMessage (broadcast) + A->>R: disconnect + Note over R: history stays in SQLite for the next connection +``` + +## Security Checklist + +The example is intentionally minimal and skips all of the following. Add them before production: + +- **Auth before join**: any client can join any room by knowing its name, and `sender` is arbitrary client input on every call. Validate a token during [connection auth](/docs/actors/authentication), bind identity to [connection state](/docs/actors/connections), and check room membership before serving history. Never trust a sender name passed as an action argument. +- **Message length clamps**: the example accepts empty messages and has no length limit. Trim server-side, reject empty text, and clamp to a maximum length. +- **Per-connection rate limiting**: rate limit `sendMessage` per connection to stop spam and broadcast amplification. +- **Server-side timestamps and ids**: the example already does this correctly. `timestamp` comes from `Date.now()` inside the action and `id` from SQLite `AUTOINCREMENT`. Keep it that way; never accept client-supplied timestamps or ids. +- **History caps**: `getHistory` returns every row with no limit. Add a `LIMIT` plus pagination, and prune or archive old rows so a long-lived room cannot grow unbounded. +- **Parameterized queries**: the example already inserts with `?` placeholders. Keep all user-supplied text out of SQL string interpolation. + +_Source doc path: /cookbook/chat-room_ diff --git a/.agents/skills/cron-jobs/reference/cookbook/collaborative-text-editor.md b/.agents/skills/cron-jobs/reference/cookbook/collaborative-text-editor.md new file mode 100644 index 0000000..cacbc1f --- /dev/null +++ b/.agents/skills/cron-jobs/reference/cookbook/collaborative-text-editor.md @@ -0,0 +1,157 @@ +# Collaborative Text Editor + +> Source: `src/content/cookbook/collaborative-text-editor.mdx` +> Canonical URL: https://rivet.dev/cookbook/collaborative-text-editor +> Description: Build a collaborative text editor backend with Yjs CRDTs and Rivet Actors: per-document actors relay sync and awareness updates and persist snapshots. + +--- +Patterns for building a Yjs server on RivetKit: CRDT document sync, presence and cursors, and snapshot persistence, with one Rivet Actor per document acting as a relay. + +## Starter Code + +Start with the working example on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/collaborative-document) and adapt it to your editor. It ships a React frontend with a plain textarea, remote cursor overlays, and a workspace document index. + +| Use Case | Starter Code | Common Examples | +| --- | --- | --- | +| Shared document editing | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/collaborative-document) | Notion-style docs, shared notes, pair-writing tools, form co-editing | + +## CRDT vs OT + +Two families of algorithms solve concurrent text editing. The choice decides what your server has to do. + +| Dimension | CRDT (Yjs) | Operational Transformation | +| --- | --- | --- | +| Conflict resolution model | Commutative merges. Updates apply in any order on any peer and converge to the same result. | Server transforms each operation against every concurrent operation. Correctness depends on a central sequencer. | +| Offline support | Strong. Clients keep editing locally and merge buffered updates on reconnect. | Weak. Long-lived divergence makes transformation chains complex and fragile. | +| Server role | Relay plus persistence. The server applies opaque updates and rebroadcasts them. It never needs to understand document semantics. | Authoritative transformer. The server must implement transformation logic for every operation type. | +| Library maturity | Yjs is mature and widely deployed, with bindings for ProseMirror, CodeMirror, Monaco, and others. | Production-grade implementations are mostly proprietary (Google Docs) or aging (ShareDB). | + +The example uses Yjs because CRDTs let the server stay a relay-style Rivet Actor. The actor applies each incoming update to a server-side `Y.Doc` so it can persist the merged state and serve late joiners, but it never transforms operations or arbitrates conflicts. Ordering does not matter because Yjs merges are commutative. + +## Document Actor Model + +| Topic | Summary | +| --- | --- | +| Topology | One `document[workspaceId, documentId]` actor per document plus one `documentList[workspaceId]` coordinator per workspace. | +| Sync model | Each client holds a local `Y.Doc`. The document actor relays incremental Yjs updates as broadcast [events](/docs/actors/events) and keeps a server-side merged copy in vars. | +| Persistence | Full merged Yjs snapshot overwritten in one binary [actor KV](/docs/actors/kv) key (`yjs:doc`) on every sync update. Document metadata lives in JSON [state](/docs/actors/state). | +| Queues | None. The example is purely [actions](/docs/actors/actions) plus broadcast events. | +| Presence | Yjs Awareness relayed through the same `applyUpdate` action. Per-connection `connState` tracks asserted awareness clientIds for disconnect cleanup. | + +The two-actor split follows the coordinator pattern from [Design Patterns](/docs/actors/design-patterns): the coordinator owns discovery and creation, and each document actor owns one document's realtime state. Multi-part [keys](/docs/actors/keys) scope both actors to a workspace. + +**Actors** + +- **Key**: `document[workspaceId, documentId]` +- **Responsibility**: Applies incoming sync and awareness updates to a server-side `Y.Doc` and `Awareness`, persists the merged Yjs snapshot to actor KV, and broadcasts updates to all connected collaborators. +- **Actions** + - `getContent` + - `applyUpdate` + - `getAwareness` +- **Queues** + - None +- **State** + - JSON metadata only: `title`, `createdAt`, `updatedAt` + - Binary KV key `yjs:doc` holding the full merged Yjs snapshot + - Ephemeral vars: the live `Y.Doc` and `Awareness`, created in `createVars` and rehydrated from KV on actor start + - Per-connection `connState`: `clientIds` of awareness clients asserted by that connection + +- **Key**: `documentList[workspaceId]` +- **Responsibility**: Coordinator for one workspace. Creates document actors through the actor-to-actor client and maintains the index of document summaries. +- **Actions** + - `createDocument` + - `listDocuments` + - `deleteDocument` +- **Queues** + - None +- **State** + - JSON + - `documents` array of `DocumentSummary` entries (`id`, `title`, `createdAt`, `updatedAt`) + +The coordinator's `createDocument` generates a UUID, then explicitly creates the document actor with `c.client()` and passes `{ title, createdAt }` as creation [input](/docs/actors/input), which the document actor's `createState` consumes. See [Communicating Between Actors](/docs/actors/communicating-between-actors) for the actor-to-actor client. + +## Update Relay + +A single `applyUpdate(update, kind, clientId?)` action handles both update kinds. Updates cross the action boundary as `number[]` byte arrays and are converted back to `Uint8Array` on each side. + +| Kind | Server Applies To | Persists | Broadcasts | +| --- | --- | --- | --- | +| `"sync"` | `c.vars.doc` via `Y.applyUpdate` with origin `"client"` | Full merged snapshot to KV key `yjs:doc`, then bumps `updatedAt` | `sync` event carrying the incremental update | +| `"awareness"` | `c.vars.awareness` via `applyAwarenessUpdate` with origin `"client"` | Nothing. Presence is ephemeral. | `awareness` event carrying the update | + +Note the asymmetry on the sync branch: the broadcast carries only the small incremental update, while the KV write stores the full merged document re-encoded with `Y.encodeStateAsUpdate`. + +Yjs origin tags are the echo guards that keep the relay loop-free: + +| Origin Tag | Set Where | Effect | +| --- | --- | --- | +| `"local"` | Client edits inside `doc.transact(..., "local")` | The client's update listener fires and sends `applyUpdate` to the actor. | +| `"client"` | Server applying an incoming update to its `Y.Doc` or `Awareness` | Marks the change as client-originated on the server copy. | +| `"remote"` | Client applying broadcast events or initial sync data | Update listeners early-return on `"remote"`, so a client never re-sends its own echo. | + +On connect or reconnect, the client calls `getContent` and `getAwareness`, then applies both results to its local `Y.Doc` and `Awareness` with origin `"remote"`. After that, every change flows through `applyUpdate` and the broadcast events. + +## Awareness And Presence + +Presence (user names, colors, cursor positions) rides on the Yjs Awareness protocol instead of actor state: + +- Clients set presence with `awareness.setLocalStateField` for the `user` and `cursor` fields. The awareness update listener encodes the change and sends `applyUpdate(update, "awareness", awareness.clientID)`. +- The actor records each asserted `clientId` in that connection's `connState.clientIds`, applies the update to the server-side `Awareness`, and broadcasts the `awareness` event to all peers. See [Connections](/docs/actors/connections) for per-connection state. +- `onDisconnect` reads the connection's `clientIds`, calls `removeAwarenessStates` on the server-side `Awareness`, and broadcasts the encoded removal so every remaining client drops the departed user's cursor. See [Lifecycle](/docs/actors/lifecycle) for the hook. + +Because the actor tracks which awareness clientIds belong to which connection, presence cleanup is automatic on disconnect with no client cooperation required. + +## Persistence And Compaction + +The example persists with a full-snapshot overwrite: on every `"sync"` update, the actor re-encodes the entire merged document with `Y.encodeStateAsUpdate` and overwrites the single binary KV key `yjs:doc`. There is no append-only update log and no separate compaction job. Compaction is implicit because `Y.encodeStateAsUpdate` emits one compact merged representation of the document, so Yjs merge semantics keep the stored blob compact on their own. + +| Property | Full-Snapshot Overwrite (the example) | +| --- | --- | +| Write cost | One full-document KV write per sync update, so every keystroke rewrites the whole blob. | +| Read cost | One binary KV read in `createVars` rehydrates the document on actor start. | +| Crash safety | The last completed `applyUpdate` is durable. No log replay needed. | +| Sweet spot | Small to medium documents where simplicity beats write amplification. | + +**Recommended extension (not in the example)**: for large documents or very high edit rates, switch to appending incremental updates to a KV update log and writing a merged snapshot only periodically (for example every N updates). Boot becomes snapshot plus log replay, and the snapshot write becomes the explicit compaction step that truncates the log. Adopt this only when full-snapshot writes become the measured bottleneck or the blob approaches KV value size limits. + +## Lifecycle + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant DL as documentList + participant D as document + + A->>DL: listDocuments() + A->>DL: createDocument(title) + DL->>D: create([workspaceId, documentId], input) + DL-->>A: DocumentSummary + A->>D: connect + B->>D: connect + Note over D: createVars rehydrates Y.Doc from KV "yjs:doc" + A->>D: getContent() + getAwareness() + D-->>A: encoded doc + awareness state + Note over A: local edit with origin "local" + A->>D: applyUpdate(update, "sync") + Note over D: apply with origin "client", overwrite KV snapshot + D-->>B: sync event (incremental update) + Note over B: apply with origin "remote", no echo + A->>D: applyUpdate(update, "awareness", clientId) + D-->>B: awareness event + B-->>D: disconnect + Note over D: onDisconnect removes B's awareness clientIds + D-->>A: awareness event (removal) +``` + +## Security Checklist + +The example ships with no authentication or authorization. Harden it with this baseline before production. None of these are implemented in the example. + +- **Authenticate before connect**: Anyone who knows or guesses a workspace ID can connect, and because `useActor` implicitly getOrCreates, connecting with a nonexistent workspace ID silently creates a blank `documentList` coordinator. Add connection auth so unauthenticated clients never reach an actor. See [Authentication](/docs/actors/authentication). +- **Per-document access control**: Validate that the authenticated user is allowed to access the specific `[workspaceId, documentId]` key, not just any document. +- **Cap and rate limit `applyUpdate`**: Update payloads are unvalidated `number[]` arrays with no size limit, and the example client sends one action per keystroke and per cursor move with zero throttling. Enforce payload size caps and per-connection rate limits on the server, and debounce on the client. +- **Do not trust client-asserted awareness clientIds**: The `clientId` argument to `applyUpdate` is client-supplied and trusted as-is. Derive or verify presence identity from connection-scoped server state instead. +- **Destroy actors and KV on delete**: `deleteDocument` only filters the entry out of the coordinator's index. The document actor and its KV snapshot are orphaned. On delete, also destroy the document actor and its storage, with a permission check on who may delete. + +_Source doc path: /cookbook/collaborative-text-editor_ diff --git a/.agents/skills/cron-jobs/reference/cookbook/cron-jobs.md b/.agents/skills/cron-jobs/reference/cookbook/cron-jobs.md new file mode 100644 index 0000000..12f7119 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/cookbook/cron-jobs.md @@ -0,0 +1,123 @@ +# Cron Jobs and Scheduled Tasks + +> Source: `src/content/cookbook/cron-jobs.mdx` +> Canonical URL: https://rivet.dev/cookbook/cron-jobs +> Description: Durable cron jobs with Rivet Actors: schedule.after and schedule.at timers survive restarts and crashes, plus re-arming recurring jobs and idempotent handlers. + +--- +Patterns for running durable cron jobs and scheduled tasks on Rivet Actors. Actor schedules are persistent timers owned by the engine, so a job keeps its deadline through actor sleep, restarts, upgrades, deploys, and crashes. + +## Starter Code + +Start from the working [Scheduling example on GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/scheduling). It implements a reminder service with one-shot timers, a React frontend, and live trigger events. + +## The Scheduling API + +The full API is documented in [Scheduling](/docs/actors/schedule). There are two methods, both available on the actor context: + +| Method | Behavior | +| --- | --- | +| `c.schedule.after(duration, actionName, ...args)` | Runs the named action after `duration` milliseconds. | +| `c.schedule.at(timestamp, actionName, ...args)` | Runs the named action at an exact epoch timestamp in milliseconds. | + +Key properties: + +- **Durable**: The schedule is persisted by the engine and the timer survives actor sleep, restart, upgrade, and crash. If the actor is asleep at the deadline, the engine wakes it to run the action. See [Lifecycle](/docs/actors/lifecycle). +- **Plain actions as callbacks**: The scheduled callback is an ordinary [action](/docs/actors/actions) on the same actor, invoked by name. Arguments after the action name are forwarded positionally, for example `c.schedule.after(delayMs, "triggerReminder", reminder.id)`. +- **No cancellation API**: Rivet does not currently support canceling a scheduled action. The pattern is a tombstone guard: remove the entry from [state](/docs/actors/state) and have the scheduled action no-op when it cannot find its entry. The example's `cancelReminder` and `triggerReminder` actions implement exactly this. + +## Recurring Jobs Via Re-Arm + +`c.schedule` is one-shot, so recurring jobs are built by having the scheduled action re-arm itself at the end of each run: + +Arm the first run from `onCreate` or a setup action; after that, the action keeps the chain alive by rescheduling itself. + +Re-arming with `after` measures the next run from the end of the current one, so the cadence drifts later by the job's runtime on every cycle. If runs must stay aligned to a fixed cadence, re-arm with `c.schedule.at(c.state.lastRunAt + DAY_MS, "runReport")` instead. + +The Scheduling example itself only uses one-shot reminders. A real re-arm implementation lives in the [idle world actor](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/idle/), where the `collectProduction` action credits production, updates `lastCollectedAt`, and calls a `scheduleCollection` helper that re-arms with `c.schedule.after(delayMs, "collectProduction", { buildingId })`. It also shows catch-up handling: if the action runs late, it computes how many whole intervals elapsed since the last run and credits them in one batch before re-arming. + +For multi-step jobs that need retries and progress tracking inside a single run, consider [Workflows](/docs/actors/workflows) instead of chaining schedules. + +## Durability Comparison + +| Approach | Timer Durability | Horizontal Scaling | Deploys And Restarts | +| --- | --- | --- | --- | +| `setTimeout` / `setInterval` | In-process memory only | Every replica arms its own timer, so jobs run once per instance | All pending timers are lost on restart or crash | +| `node-cron` and similar libraries | In-process memory only | Every instance runs the job unless you add external locking | Schedule resets on deploy; runs missed during downtime are skipped | +| External cron service | Lives outside your app | Needs a public HTTP endpoint plus its own dedupe and retry state | Survives your deploys but is separate infrastructure to operate | +| Rivet Actor scheduling | Persisted by the engine as a durable timer | Exactly one actor per key, so the timer is armed once rather than once per replica | Survives actor sleep, restart, upgrade, and crash | + +## Idempotency + +A scheduled action can fire more than you expect: a crash between doing the work and re-arming can cause the action to run again, and because schedules cannot be cancelled, an action can fire for an entry that was already removed. Design handlers so a duplicate firing is harmless: + +- **Store a run marker in state**: Keep a `lastRunAt` timestamp or a sequence number in actor state and update it inside the action. On each firing, compute elapsed time since the marker and skip or batch accordingly. The idle world actor's `collectProduction` does this with `lastCollectedAt` and whole-interval batching. +- **Tombstone guard for cancelled entries**: The example's `triggerReminder` looks the reminder up in `c.state.reminders` first and returns with a warning if it is gone, so a fire-after-cancel is a safe no-op. +- **Keep work and marker updates in the same action**: Actor state writes are persisted with the action, so updating the marker in the same handler that does the work keeps the two consistent. + +## Topology + +| Topology | Use When | Example Key | +| --- | --- | --- | +| Singleton job actor | One global job such as a nightly report or cleanup pass | `job["daily-report"]` | +| Actor per scheduled entity | Per-user or per-resource timers such as reminders, trials, or billing periods | `reminder[userId]` | + +The Scheduling example uses a single shared `reminderActor["main"]` key for demo simplicity. For production reminder systems, prefer one actor per user so timers, state, and load are isolated per entity. See [Keys](/docs/actors/keys). + +## Reminder Service Example + +| Topic | Summary | +| --- | --- | +| Scheduling | One-shot timers armed with `c.schedule.after(delayMs, "triggerReminder", reminder.id)` or `c.schedule.at(timestamp, "triggerReminder", reminder.id)`. | +| State | JSON state holding `reminders` and `completedCount`; the scheduled action mutates state when it fires. | +| Events | `triggerReminder` broadcasts a `reminderTriggered` event to all connected clients. See [Events](/docs/actors/events). | +| Cancellation | `cancelReminder` only removes the reminder from state; the scheduled action may still fire and no-ops via a state lookup guard. | + +**Actors** + +- **Key**: `reminderActor["main"]` +- **Responsibility**: Stores reminders in persistent state, arms a future self-action per reminder via `c.schedule`, marks reminders completed when the scheduled action fires, and broadcasts `reminderTriggered` to connected clients. +- **Actions** + - `scheduleReminder` + - `scheduleReminderAt` + - `triggerReminder` + - `getReminders` + - `cancelReminder` + - `getStats` +- **Queues** + - None +- **State** + - JSON + - `reminders` + - `completedCount` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant R as reminderActor + participant E as Engine + + C->>R: scheduleReminder(message, delayMs) + R->>E: schedule.after(delayMs, triggerReminder, id) + Note over E: schedule persisted + alarm armed + R-->>C: reminder + Note over R: actor sleeps + E->>R: alarm fires, actor wakes + Note over R: triggerReminder(id) runs + R-->>C: reminderTriggered event + Note over R: recurring jobs re-arm here with schedule.after +``` + +## Security Checklist + +The example is intentionally open: any client can connect to the shared `["main"]` key and schedule or cancel anything. Treat all of the following as required extensions for production: + +- **Validate schedule inputs**: Clamp `delayMs` and `timestamp` from clients. Reject negative delays, timestamps in the past, and absurdly far-future deadlines, and bound message or payload sizes. +- **Never schedule client-chosen actions**: Expose specific actions like `scheduleReminder` that internally arm a fixed callback. Do not pass a client-supplied action name or unchecked args into `c.schedule`. +- **Authenticate and scope keys**: Add connection [authentication](/docs/actors/authentication) and use per-user actor keys instead of one global key, so users cannot read or cancel each other's schedules. +- **Prune completed entries**: The example's `reminders` array grows without bound. Remove or archive completed entries so state stays small. +- **Use stable IDs**: Generate entry IDs with `crypto.randomUUID()` rather than timestamp-plus-random strings. + +_Source doc path: /cookbook/cron-jobs_ diff --git a/.agents/skills/cron-jobs/reference/cookbook/live-cursors.md b/.agents/skills/cron-jobs/reference/cookbook/live-cursors.md new file mode 100644 index 0000000..71c94ab --- /dev/null +++ b/.agents/skills/cron-jobs/reference/cookbook/live-cursors.md @@ -0,0 +1,152 @@ +# Live Cursors and Presence + +> Source: `src/content/cookbook/live-cursors.mdx` +> Canonical URL: https://rivet.dev/cookbook/live-cursors +> Description: Live cursors and multiplayer presence with Rivet Actors: per-connection cursor state, realtime updates over events or raw WebSockets, and throttling. + +--- +Patterns for building live cursors, multiplayer presence, and realtime cursor sharing with RivetKit. One room actor fans cursor positions out to every connected client, keyed per room with [actor keys](/docs/actors/keys). + +## Starter Code + +Start with one of the two working variants on GitHub. Both implement the same collaborative cursor canvas with persistent text labels; they differ only in transport. + +| Variant | Starter Code | Transport | Presence Storage | +| --- | --- | --- | --- | +| `cursors` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/cursors) | Typed [actions](/docs/actors/actions) and [events](/docs/actors/events) over the RivetKit connection | `connState` per connection | +| `cursors-raw-websocket` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/cursors-raw-websocket) | Raw [`onWebSocket` handler](/docs/actors/websocket-handler) with a custom JSON message protocol | Socket map in `createVars` | + +Use `cursors` by default: typed actions, typed events, and automatic connection tracking cover most apps with less code. Use `cursors-raw-websocket` when you need full control of the wire format, for example a custom JSON or binary protocol, or clients that do not use the RivetKit client library. + +## Connection State vs Persistent State + +Presence is ephemeral by definition. A cursor position is only meaningful while its connection is alive, so it belongs in per-connection storage, not in persistent actor state. Persistent state is reserved for data that must survive disconnects and actor restarts. + +| Data | Where It Lives | Why | +| --- | --- | --- | +| Cursor position | `connState` (`cursors`) or the `createVars` socket map (`cursors-raw-websocket`) | Scoped to one connection and discarded with it. Stale presence cannot accumulate in storage. | +| Text labels (`textLabels`) | Persistent actor `state` in both variants | Canvas content must survive disconnects and actor restarts. | + +In the `cursors` variant, `updateCursor` writes `c.conn.state.cursor` and `getRoomState` rebuilds the presence snapshot by iterating `c.conns.values()`, so the cursor map is always derived from live connections rather than stored. See [Connections](/docs/actors/connections) for `connState` and [State](/docs/actors/state) for persistence semantics. + +## Presence Lifecycle + +- **Join**: The `cursors-raw-websocket` variant pushes an `init` message with the current `{ cursors, textLabels }` snapshot as soon as a socket connects. The `cursors` variant has no explicit join broadcast; the client calls the `getRoomState` action once after connecting to seed its local maps, and peers first see a new user on that user's first `cursorMoved` broadcast. +- **Move**: Every `updateCursor` call writes the connection's presence entry, then broadcasts `cursorMoved` to all connections, including the sender. +- **Leave**: The `cursors` variant handles leave in `onDisconnect`, broadcasting `cursorRemoved` with the connection's last cursor. The raw variant does the same from the socket `close` listener, then deletes the session from the `vars.websockets` map. Clients delete that user from their local cursor map, so stale cursors disappear the moment a tab closes. + +See [Lifecycle](/docs/actors/lifecycle) for `onDisconnect` and `createVars`. + +## Update Throttling + +Neither example throttles. Both frontends send a cursor update on every raw `mousemove` event with no debounce or interval cap. That is fine for a demo, but a fast mouse on a high-refresh display can emit hundreds of events per second per user. The patterns below are recommended production hardening on top of the starter code, not something the examples implement. + +| Layer | Pattern | Guidance | +| --- | --- | --- | +| Client (smoothness) | Throttle to 20-30Hz | Sample the latest pointer position every 33-50ms and send only that. Drop intermediate moves, but always flush the final position so cursors settle at the true location. Interpolate between received positions on the rendering side. | +| Server (enforcement) | Per-connection rate limit | Track the last accepted update timestamp per connection and drop or coalesce updates arriving faster than your cap. Client throttles are cooperative; the actor is the enforcement boundary. | + +## Actors + +- **Key**: `cursorRoom[roomId]` (the frontend defaults `roomId` to `"general"`) +- **Responsibility**: Holds per-connection cursor presence in `connState`, persists shared text labels in actor state, and broadcasts cursor and text updates to all connections. +- **Actions** + - `updateCursor` + - `updateText` + - `removeText` + - `getRoomState` +- **Events** + - `cursorMoved` + - `cursorRemoved` + - `textUpdated` + - `textRemoved` +- **Queues** + - None +- **State** + - JSON + - `textLabels` (persistent) + - `connState.cursor` per connection (ephemeral) + +- **Key**: `cursorRoom[roomId]` (resolved via `client.cursorRoom.getOrCreate(roomId)`) +- **Responsibility**: Exposes a raw WebSocket endpoint, tracks live sockets and their cursors in a `createVars` map keyed by a `sessionId` query parameter, persists text labels, and manually fans JSON frames out to every socket. +- **Actions** + - `getOrCreate` (stub returning `{ status: "ok" }`; the frontend resolves the actor ID with the client handle's `getOrCreate(roomId).resolve()`, which creates the actor without dispatching this action) + - `getRoomState` +- **Queues** + - None +- **State** + - JSON + - `textLabels` (persistent) + - `vars.websockets` map of `sessionId` to socket and cursor (in-memory, lost on restart) + +The raw variant defines no RivetKit events. Its message names are `type` fields on raw JSON frames: + +| Direction | Message `type` | Payload | +| --- | --- | --- | +| Client to server | `updateCursor` | `{ userId, x, y }` | +| Client to server | `updateText` | `{ id, userId, text, x, y }` | +| Client to server | `removeText` | `{ id }` | +| Server to client | `init` | `{ cursors, textLabels }` snapshot on connect | +| Server to client | `cursorMoved`, `textUpdated`, `textRemoved`, `cursorRemoved` | The corresponding cursor, label, or ID payload | + +## Lifecycle + +### cursors (Actions + Events) + +```mermaid +sequenceDiagram + participant A as Client A + participant R as cursorRoom + participant B as Other Clients + + A->>R: connect via useActor (cursorRoom[roomId]) + A->>R: getRoomState() + R-->>A: {cursors, textLabels} + loop every mouse move + A->>R: updateCursor(userId, x, y) + Note over R: write c.conn.state.cursor + R-->>B: cursorMoved (broadcast) + end + A->>R: updateText(id, userId, text, x, y) + Note over R: upsert persistent state.textLabels + R-->>B: textUpdated (broadcast) + Note over A: tab closes + Note over R: onDisconnect reads conn.state.cursor + R-->>B: cursorRemoved (broadcast) +``` + +### cursors-raw-websocket + +```mermaid +sequenceDiagram + participant A as Client A + participant R as cursorRoom + participant B as Other Clients + + A->>R: getOrCreate(roomId).resolve() + R-->>A: actorId + A->>R: open WebSocket /gateway/{actorId}/websocket?sessionId=... + Note over R: close 1008 if sessionId is missing + Note over R: store socket in vars.websockets + R-->>A: init {cursors, textLabels} + loop every mouse move + A->>R: {type: "updateCursor"} frame + Note over R: update session cursor in vars + R-->>B: cursorMoved frame + end + Note over A: socket closes + R-->>B: cursorRemoved frame + Note over R: delete session from vars.websockets +``` + +## Security Checklist + +Both examples ship without authentication so the presence pattern stays readable. Everything below is recommended hardening for production, not behavior the examples implement. + +- **Identity**: Bind presence identity to the connection (`c.conn.id` in the actions variant, a server-generated session ID in the raw variant). Never trust a client-supplied `userId`; in the examples it is a random client-generated string, so any client can impersonate or remove any cursor. +- **Authorization**: Authorize label mutations by owner. In the examples, `updateText` accepts arbitrary `id` and `userId` arguments and `removeText` accepts an arbitrary `id`, so any client can edit or delete any label. +- **Input validation**: Clamp `x` and `y` to canvas bounds, cap text label length, and cap the total `textLabels` count so persistent state cannot grow unbounded. +- **Rate limiting**: Enforce a per-connection cap on `updateCursor` (for example 30Hz) and on label writes, as described in [Update Throttling](#update-throttling). +- **Protocol strictness (raw variant)**: Validate message shape before use and close the socket on malformed JSON instead of logging and continuing. Reject duplicate `sessionId` values rather than silently overwriting another session's socket entry. + +_Source doc path: /cookbook/live-cursors_ diff --git a/.agents/skills/cron-jobs/reference/cookbook/multiplayer-game.md b/.agents/skills/cron-jobs/reference/cookbook/multiplayer-game.md new file mode 100644 index 0000000..425b113 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/cookbook/multiplayer-game.md @@ -0,0 +1,713 @@ +# Multiplayer Game + +> Source: `src/content/cookbook/multiplayer-game.mdx` +> Canonical URL: https://rivet.dev/cookbook/multiplayer-game +> Description: Pragmatic patterns for building multiplayer games: matchmaking, tick loops, realtime state, interest management, and validation. + +--- +Patterns for building multiplayer games with RivetKit, intended as a practical checklist you can adapt per genre. + +## Starter Code + +Start with one of the working examples on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/) and adapt it to your game. Do not start from scratch for matchmaking and lifecycle flows. + +| Game Classification | Starter Code | Common Examples | +| --- | --- | --- | +| Battle Royale | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/battle-royale/) | Fortnite, Apex Legends, PUBG, Warzone | +| Arena | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/arena/) | Call of Duty TDM/FFA, Halo Slayer, Counter-Strike casual, VALORANT unrated, Overwatch Quick Play, Rocket League | +| IO Style | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/io-style/) | Agar.io, Slither.io, surviv.io | +| Open World | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/open-world/) | Minecraft survival servers, Rust-like worlds, MMO zone/chunk worlds | +| Party | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/party/) | Fall Guys private lobbies, custom game rooms, social party sessions | +| Physics 2D | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-2d/) | Top-down physics brawlers, 2D arena games, platform fighters | +| Physics 3D | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-3d/) | Physics sandbox sessions, 3D arena games, movement playgrounds | +| Ranked | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/ranked/) | Chess ladders, competitive card games, duel arena ranked queues | +| Turn-Based | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/turn-based/) | Chess correspondence, Words With Friends, async board games | +| Idle | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/idle/) | Cookie Clicker, Idle Miner Tycoon, Adventure Capitalist | + +## Server Simulation + +### Game Loop And Tick Rates + +| Pattern | Use When | Implementation Guidance | +| --- | --- | --- | +| Fixed realtime loop | Battle Royale, Arena, IO Style, Open World, Ranked | Run in `run` with `sleep(tickMs)` and exit on `c.aborted`. | +| Action-driven updates | Party, Turn-Based | Mutate and broadcast only on actions/events rather than scheduled ticks. | +| Coarse offline progression | Any mode with idle progression | Use `c.schedule.after(...)` with coarse windows (for example 5 to 15 minutes) and apply catch-up from elapsed wall clock time. | + +### Physics + +Start with custom kinematic logic for simple games. Switch to a full physics engine when you need joints, stacked bodies, high collision density, or complex shapes (rotated polygons, capsules, convex hulls, triangle meshes). + +Pick one engine per simulation. Keep frontend-only libs out of backend simulation paths and treat server state as authoritative. + +| Dimension | Primary Engine | Fallback Engines | Example Code | +| --- | --- | --- | --- | +| 2D | `@dimforge/rapier2d` | `planck-js`, `matter-js` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-2d/) | +| 3D | `@dimforge/rapier3d` | `cannon-es`, `ammo.js` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-3d/) | + +### Spatial Indexing + +For non-physics spatial queries, use a dedicated index instead of naive `O(n^2)` checks: + +| Index Type | Recommendation | +| --- | --- | +| AABB index | For AOI, visibility, and non-collider entities, use `rbush` for dynamic sets or `flatbush` for static-ish sets. | +| Point index | For nearest-neighbor or within-radius queries, use `d3-quadtree`. | + +## Networking & State Sync + +### Netcode + +| Model | When To Use | Implementation | +| --- | --- | --- | +| Hybrid (client movement, server combat) | Shooters, action sports, ranked duels | Client owns movement and sends capped-rate position updates. Server validates for anti-cheat. Combat (projectiles, hits, damage) is fully server-authoritative. | +| Server-authoritative with interpolation | IO Style, persistent worlds | Client sends input commands. Server simulates on fixed ticks and publishes authoritative snapshots. Client interpolates between snapshots. | +| Server-authoritative (basic logic) | Turn-based, event-driven | Server validates and applies discrete actions (turns, phase transitions, votes). Client displays confirmed state. | + +### Realtime Data Model + +- **Snapshots and diffs**: Publish state as events. Send a full snapshot on join/resync, then per-tick diffs for regular updates. +- **Batch per tick**: Keep events small and typed. Batch high-frequency updates per tick. +- **Avoid UI framework state for game updates**: Use `requestAnimationFrame` or a Canvas/Three.js loop for simulation, not React state. Reserve UI framework state for menus, HUD, and forms. +- **Broadcast vs per-connection**: Use `c.broadcast(...)` for shared updates and `conn.send(...)` for private/per-player data. + +### Shared Simulation Logic + +Shared simulation logic runs on both the client and the server. For example, an `applyInput(state, input, dt)` function that integrates velocity and clamps to world bounds can run on the client for prediction and on the server for validation. + +- **Hybrid modes**: Client runs shared movement as primary authority, server runs it for anti-cheat validation. +- **Server-authoritative modes**: Client uses shared logic for interpolation and prediction only. +- **Keep it pure**: Movement integration, input transforms, collision helpers, and constants only. +- **Put shared code in `src/shared/`**: Keep deterministic helpers in `src/shared/sim/*` with no side effects. + +### Interest Management + +Control what each client receives to reduce bandwidth and prevent information leaks. + +#### Per-Player Replication Filters + +- **Filter by relevance**: Send each client only state relevant to that player (proximity, line-of-sight, team, or game phase). +- **Shooters and action games**: Limit replication by proximity and optional field-of-view checks. +- **Server-side only**: Clients should never receive data they should not see. + +#### Sharded Worlds + +- **Partition large worlds**: Use chunk actors keyed by `worldId:chunkX:chunkY`. +- **Subscribe to nearby chunks**: Clients connect only to nearby partitions (for example a 3x3 chunk window). +- **Use sparingly**: Only when the world is large and state-heavy (sandbox builders, MMOs), not as a default for small matches. + +## Backend Infrastructure + +### Persistence + +- **In-memory state**: Best for realtime game state that changes every tick (player positions, inputs, match phase, scores). +- **SQLite (`rivetkit/db`)**: Better for large or table-like state that needs queries, indexes, or long-term persistence (tiles, inventory, matchmaking pools). Serialize DB work through a queue since multiple actions can hit the same actor concurrently. + +### Matchmaking Patterns + +Common building blocks used across the architecture patterns below. + +#### Actor Topology + +| Primitive | Use When | Typical Ownership | +| --- | --- | --- | +| `matchmaker["main"]` + `match[matchId]` | Session-based multiplayer (battle royale, arena, ranked, party, turn-based) | Matchmaker owns discovery/assignment. Match owns lifecycle and gameplay state. | +| `chunk[worldId,chunkX,chunkY]` | Large continuous worlds that need sharding | Each chunk owns local players, chunk state, and local simulation. | +| `world[playerId]` | Per-player progression loops (idle/solo world state) | Per-player resources, buildings, timers, and progression. | +| `player[username]` | Canonical profile/rating reused across matches | Durable player stats (for example rating and win/loss). | +| `leaderboard["main"]` | Shared rankings across many matches/players | Global ordered score rows and top lists. | + +#### Queueing Strategy + +- Multiple players can hit the matchmaker at the same time, so actions like find/create, queue/unqueue, and close need to be serialized through actor queues to avoid races. +- Match-local actions (gameplay, scoring) do not need queueing unless they write back to the matchmaker. + +## Security And Anti-Cheat + +Start with this baseline, then harden further for competitive or high-risk environments. + +### Baseline Checklist + +- **Identity**: Use `c.conn.id` as the authoritative transport identity. Treat `playerId`/`username` in params as untrusted input and bind through server-issued assignment/join tickets. +- **Authorization**: Validate the caller is allowed to mutate the target entity (room membership, turn ownership, host-only actions). +- **Input validation**: Clamp sizes/lengths, validate enums, and validate usernames (length, allowed chars, avoid unbounded Unicode). +- **Rate limiting**: Per-connection rate limits for spammy actions (chat, join/leave, fire, movement updates). +- **State integrity**: Server recomputes derived state (scores, win conditions, placements). Never allow client-authoritative changes to inventory/currency/leaderboard totals. + +### Movement Validation + +For any mode with client-authoritative movement (hybrid flows), clients may send position/rotation updates for smoothness, but the server must: + +- Enforce max delta per update (speed cap) based on elapsed time. +- Reject or clamp teleports. +- Enforce world bounds (and basic collision if applicable). +- Rate limit update frequency (for example 20Hz max). + +## Architecture Patterns + +Each game type below starts with a quick summary table, then details actors and lifecycle. + +### Battle Royale + +| Topic | Summary | +| --- | --- | +| Matchmaking | Immediate routing to the fullest non-started lobby (oldest tie-break); players wait in lobby until capacity, then the match starts. | +| Netcode | Hybrid. Client owns movement, camera, and local prediction. Server owns zone state, projectiles, hit resolution, eliminations, loot, and final placement. | +| Tick Rate | 10 ticks/sec (`100ms`) with a fixed loop for zone progression and lifecycle checks. | +| Physics | Client owns movement with server anti-cheat validation; projectiles, hits, and damage are server-authoritative. Use `@dimforge/rapier3d` for 3D or `@dimforge/rapier2d` for top-down 2D. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Finds or creates lobbies, tracks pending reservations, and maintains occupancy. +- **Actions** + - `findMatch` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **Queues** + - `findMatch` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **State** + - SQLite + - `matches` + - `pending_players` + - `player_count` includes connected and pending players + +- **Key**: `match[matchId]` +- **Responsibility**: Runs lobby/live/finished phases, owns player state, zone progression, and eliminations. +- **Actions** + - `connect` + - Movement and combat actions +- **Queues** + - None +- **State** + - JSON + - `phase` + - `players` + - `zone` + - `eliminations` + - `snapshot data` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant M as match + + C->>MM: findMatch() + alt no open lobby + MM->>M: create(matchId) + end + MM-->>C: {matchId, playerId} + C->>M: connect(playerId) + M->>MM: pendingPlayerConnected(matchId, playerId) + MM-->>M: accepted + Note over M: lobby countdown -> live + M-->>C: snapshot + shoot events + M->>MM: closeMatch(matchId) +``` + +### Arena + +| Topic | Summary | +| --- | --- | +| Matchmaking | Mode-based fixed-capacity queues (`duo`, `squad`, `ffa`) that build only full matches and pre-assign teams (except FFA). | +| Netcode | Hybrid. Client owns movement plus prediction and smoothing. Server owns team or FFA assignment, projectiles, hit resolution, phase transitions, and scoring. | +| Tick Rate | 20 ticks/sec (`50ms`) with a tighter loop for live team and FFA snapshots. | +| Physics | Medium to high intensity; client movement with server validation and server-authoritative combat/entities. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Runs mode queues, builds full matches, assigns teams, and publishes assignments. +- **Actions** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **Queues** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **State** + - SQLite + - `player_pool` + - `matches` + - `assignments` keyed by connection and player + +- **Key**: `match[matchId]` +- **Responsibility**: Runs match phases and in-match player/team state for score and win conditions. +- **Actions** + - `connect` + - Gameplay actions +- **Queues** + - None +- **State** + - JSON + - `phase` + - `players` + - `team assignments` + - `score and win state` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant M as match + + C->>MM: queueForMatch(mode) + Note over MM: enqueue in player_pool + Note over MM: fill when capacity reached + MM->>M: create(matchId, assignments) + Note over MM: persist assignments + MM-->>C: assignmentReady + C->>M: connect(playerId) + Note over M: waiting -> live when all players connect + M->>MM: matchCompleted(matchId) +``` + +### IO Style + +| Topic | Summary | +| --- | --- | +| Matchmaking | Open-lobby routing to the fullest room below capacity; room counts are heartbeated and new lobbies are auto-created when needed. | +| Netcode | Server-authoritative with interpolation. Client sends input intents and interpolates. Server owns movement, bounds, room membership, and canonical snapshots. | +| Tick Rate | 10 ticks/sec (`100ms`) with lightweight periodic room snapshots. | +| Physics | Low to medium intensity; server-authoritative kinematic movement, escalating to a physics engine only when collisions get complex. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Routes players into the fullest open lobby and tracks reservations and occupancy. +- **Actions** + - `findLobby` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **Queues** + - `findLobby` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **State** + - SQLite + - `matches` + - `pending_players` + - Occupancy includes pending reservations + +- **Key**: `match[matchId]` +- **Responsibility**: Runs per-match movement simulation and broadcasts snapshots. +- **Actions** + - `connect` + - `setInput` +- **Queues** + - None +- **State** + - JSON + - `players` + - `inputs` + - `movement state` + - `snapshot cache` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant M as match + + C->>MM: findLobby() + alt no open lobby + MM->>M: create(matchId) + end + MM-->>C: {matchId, playerId} + C->>M: connect(playerId) + M->>MM: pendingPlayerConnected(matchId, playerId) + MM-->>M: accepted + Note over M: fixed tick simulation + M-->>C: snapshot events + M->>MM: closeMatch(matchId) +``` + +### Open World + +| Topic | Summary | +| --- | --- | +| Matchmaking | Client-driven chunk routing from world coordinates, with nearby chunk windows preloaded via adjacent chunk connections. | +| Netcode | Hybrid for sandbox (client movement with validation) or server-authoritative for MMO-like flows. Server owns chunk routing, persistence, and canonical world state. | +| Tick Rate | 10 ticks/sec per chunk actor (`100ms`), so load scales with active chunks. | +| Physics | Medium to high at scale; chunk-local simulation can be server-authoritative (MMO-like) or client movement with server validation (sandbox-like). | + +**Actors** + +- **Key**: `chunk[worldId,chunkX,chunkY]` +- **Responsibility**: Owns chunk-local players, blocks, movement tick, and chunk membership. +- **Actions** + - `connect` + - `enterChunk` + - `addPlayer` + - `setInput` + - `leaveChunk` + - `removePlayer` +- **Queues** + - None +- **State** + - JSON + - `connections` + - `players` + - `blocks` scoped to one chunk key + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant CH as chunk + + Note over C: resolve chunk keys from world position + loop each visible chunk + C->>CH: connect(worldId, chunkX, chunkY, playerId) + Note over CH: store connection metadata + end + C->>CH: enterChunk/addPlayer + loop movement updates + C->>CH: setInput(...) + CH-->>C: snapshot + end + C->>CH: leaveChunk/removePlayer or disconnect + Note over CH: remove membership and metadata +``` + +### Party + +| Topic | Summary | +| --- | --- | +| Matchmaking | Host-created private party flow using party codes and explicit joins. | +| Netcode | Server-authoritative (basic logic). Server owns membership, host permissions, and phase transitions. | +| Tick Rate | No continuous tick; updates are event-driven (`join`, `start`, `finish`). | +| Physics | Low intensity for lobby-first flows; usually no dedicated physics or indexing unless you add realtime mini-games. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Handles party create/join flow, validates join tickets, and tracks party size. +- **Actions** + - `createParty` + - `joinParty` + - `verifyJoin` + - `updatePartySize` + - `closeParty` +- **Queues** + - `createParty` + - `joinParty` + - `verifyJoin` + - `updatePartySize` + - `closeParty` +- **State** + - SQLite + - `parties` + - `join_tickets` for party lookup and join validation + +- **Key**: `match[matchId]` +- **Responsibility**: Owns party members, host role, ready flags, and phase transitions. +- **Actions** + - `connect` + - `startGame` + - `finishGame` +- **Queues** + - None +- **State** + - JSON + - `members` + - `host` + - `ready state` + - `phase` + - `party events` + +**Lifecycle** + +### Host Flow + +```mermaid +sequenceDiagram + participant H as Host Client + participant MM as matchmaker + participant M as match + + H->>MM: createParty() + MM-->>H: {matchId, partyCode, playerId, joinToken} + H->>M: connect(playerId, joinToken) + M->>MM: verifyJoin(...) + MM-->>M: allowed + M->>MM: updatePartySize(playerCount) + H->>M: startGame() / finishGame() + M->>MM: closeParty(matchId) +``` + +### Joiner Flow + +```mermaid +sequenceDiagram + participant J as Joiner Client + participant MM as matchmaker + participant M as match + + J->>MM: joinParty(partyCode) + MM-->>J: {matchId, playerId, joinToken} + J->>M: connect(playerId, joinToken) + M->>MM: verifyJoin(...) + MM-->>M: allowed / denied + M->>MM: updatePartySize(playerCount) +``` + +### Ranked + +| Topic | Summary | +| --- | --- | +| Matchmaking | ELO-based queue pairing with a widening search window as wait time increases. | +| Netcode | Hybrid. Client owns movement with local prediction and interpolation. Server owns projectiles, hit resolution, match results, and rating updates. | +| Tick Rate | 20 ticks/sec (`50ms`) with fixed live ticks for deterministic pacing and broadcast cadence. | +| Physics | Medium to high intensity; client movement with server validation and server-authoritative combat/hit resolution. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Runs rating-based queueing, pairing, assignment persistence, and completion fanout. +- **Actions** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **Queues** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **State** + - SQLite + - `player_pool` + - `matches` + - `assignments` with rating window and connection scoping + +- **Key**: `match[matchId]` +- **Responsibility**: Runs ranked match phase, score, and winner reporting. +- **Actions** + - `connect` + - Gameplay actions +- **Queues** + - None +- **State** + - JSON + - `phase` + - `players` + - `score` + - `winner` + - `completion payload` + +- **Key**: `player[username]` +- **Responsibility**: Stores canonical player MMR and win/loss profile. +- **Actions** + - `initialize` + - `getRating` + - `applyMatchResult` +- **Queues** + - None +- **State** + - JSON + - `rating` + - `wins` + - `losses` + - `match counters` + +- **Key**: `leaderboard["main"]` +- **Responsibility**: Stores and serves top-ranked players. +- **Actions** + - `updatePlayer` +- **Queues** + - None +- **State** + - SQLite + - Leaderboard score rows + - Top-list ordering + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant P as player + participant M as match + participant LB as leaderboard + + C->>MM: queueForMatch(username) + MM->>P: initialize/getRating + P-->>MM: rating + Note over MM: store queue row + retry pairing + MM->>M: create(matchId, assigned players) + MM-->>C: assignmentReady + C->>M: connect(username) + M->>MM: matchCompleted(...) + MM->>P: applyMatchResult(...) + MM->>LB: updatePlayer(...) + Note over MM: remove matches + assignments rows +``` + +### Turn-Based + +| Topic | Summary | +| --- | --- | +| Matchmaking | Async private-invite and public-queue pairing in the same pattern. | +| Netcode | Server-authoritative (basic logic). Client can draft moves before submit. Server owns turn ownership, committed move log, turn order, and completion state. | +| Tick Rate | No continuous tick; move submission and turn transitions drive updates. | +| Physics | Very low intensity; no realtime physics loop, just discrete rules validation. Indexing is optional and mostly for board or query convenience at scale. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Handles private invite and public queue pairing for async matches. +- **Actions** + - `createGame` + - `joinByCode` + - `queueForMatch` + - `unqueueForMatch` + - `closeMatch` +- **Queues** + - `createGame` + - `joinByCode` + - `queueForMatch` + - `unqueueForMatch` + - `closeMatch` +- **State** + - SQLite + - `matches` + - `player_pool` + - `assignments` for invite and queue mapping + +- **Key**: `match[matchId]` +- **Responsibility**: Owns board state, turn order, move validation, and final result. +- **Actions** + - `connect` + - `makeMove` +- **Queues** + - None +- **State** + - JSON + - `board` + - `turns` + - `players` + - `connection presence` + - `result` + +**Lifecycle** + +### Public Queue + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant MM as matchmaker + participant M as match + + A->>MM: queueForMatch() + B->>MM: queueForMatch() + Note over MM: pair first two queued players + MM->>M: create(matchId) + seed X/O players + MM-->>A: assignment/match info + MM-->>B: assignment/match info + A->>M: connect(playerId) + B->>M: connect(playerId) + A->>M: makeMove() + B->>M: makeMove() + opt all players disconnected for timeout + Note over M: destroy after idle timeout + end + M->>MM: closeMatch(matchId) +``` + +### Private Invite + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant MM as matchmaker + participant M as match + + A->>MM: createGame() + MM-->>A: {matchId, playerId, inviteCode} + B->>MM: joinByCode(inviteCode) + MM->>M: create(matchId) + seed X/O players + MM-->>A: assignment/match info + MM-->>B: assignment/match info + A->>M: connect(playerId) + B->>M: connect(playerId) + A->>M: makeMove() + B->>M: makeMove() + M->>MM: closeMatch(matchId) +``` + +### Idle + +| Topic | Summary | +| --- | --- | +| Matchmaking | No matchmaker; each player uses a direct per-player actor and a shared leaderboard actor. | +| Netcode | Server-authoritative (basic logic). Client owns UI and build intent. Server owns resources, production rates, building validation, and leaderboard totals. | +| Tick Rate | No continuous tick; use `c.schedule.after(...)` for coarse intervals and compute offline catch-up from elapsed wall time. | +| Physics | None for standard idle loops; transitions are discrete (`build`, `collect`, `upgrade`) and do not need spatial indexing. | + +**Actors** + +- **Key**: `world[playerId]` +- **Responsibility**: Owns one player's progression, buildings, production scheduling, and state updates. +- **Actions** + - `initialize` + - `build` + - `collectProduction` +- **Queues** + - None +- **State** + - JSON + - Per-player buildings + - `resources` + - `timers` + - `progression state` + +- **Key**: `leaderboard["main"]` +- **Responsibility**: Stores global scores and serves leaderboard updates. +- **Actions** + - `updateScore` +- **Queues** + - `updateScore` +- **State** + - SQLite + - `scores` table keyed by player + - Current leaderboard totals + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant W as world + participant LB as leaderboard + + C->>W: getOrCreate(playerId) + initialize() + Note over W: seed state + schedule collection + W-->>C: stateUpdate + loop gameplay loop + C->>W: build() / collectProduction() + W->>LB: updateScore(...) + Note over LB: upsert scores + LB-->>C: leaderboardUpdate + W-->>C: stateUpdate + end +``` + +_Source doc path: /cookbook/multiplayer-game_ diff --git a/.agents/skills/cron-jobs/reference/cookbook/per-tenant-database.md b/.agents/skills/cron-jobs/reference/cookbook/per-tenant-database.md new file mode 100644 index 0000000..e3c5616 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/cookbook/per-tenant-database.md @@ -0,0 +1,119 @@ +# Database per Tenant + +> Source: `src/content/cookbook/per-tenant-database.mdx` +> Canonical URL: https://rivet.dev/cookbook/per-tenant-database +> Description: Multi-tenant data isolation with one Rivet Actor per tenant: the actor key is the tenant id, so each tenant gets its own isolated dataset and migrations. + +--- +Patterns for database-per-tenant architectures with RivetKit. Instead of one shared database with a `tenant_id` column on every table, each tenant gets its own Rivet Actor, and that actor owns the tenant's entire dataset. + +## Starter Code + +Start with the working example on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/per-tenant-database) and adapt it. The example stores each tenant's dataset in JSON actor state and serves a React dashboard with live event updates. + +| Topic | Summary | +| --- | --- | +| Isolation | One `companyDatabase` actor per tenant, keyed by company name. Switching tenants swaps the entire dataset. | +| State | JSON actor state holding `employees` and `projects` arrays plus timestamps. No SQLite, no queues, no scheduling. | +| Realtime | Every write action mutates state, then broadcasts a typed event (`employeeAdded`, `projectAdded`) to all connected clients of that tenant. | +| Auth | None. The sign-in screen is cosmetic. Production guidance is in the [security checklist](#security-checklist). | + +## The Isolation Model + +The actor key is the tenant id. The client connects with `useActor({ name: "companyDatabase", key: [companyName] })` and the actor reads `c.key[0]` in `createState` to seed that tenant's dataset. This gives you: + +- **One actor per tenant**: `companyDatabase[tenantId]` addresses exactly one actor instance. Two tenants can never share an actor. +- **One dataset per tenant**: All reads and writes go through that actor's [state](/docs/actors/state), so there is no shared table with a `tenant_id` column to filter incorrectly. Cross-tenant leaks require constructing the wrong key, not forgetting a `WHERE` clause. +- **No key injection**: Keys are arrays, not interpolated strings. `key: [tenantId]` cannot be escaped the way `"tenant:" + tenantId` string concatenation can. See [Keys](/docs/actors/keys). + +The example's test ([tests/per-tenant-database.test.ts](https://github.com/rivet-dev/rivet/tree/main/examples/per-tenant-database/tests/per-tenant-database.test.ts)) proves the isolation: data written to `companyDatabase["Alpha Co"]` never appears in `companyDatabase["Beta Co"]`. + +## Choosing a State Backend + +The example uses plain JSON actor state. The same key-equals-tenant model works with any actor state backend. + +| Backend | Use When | Docs | Working Code | +| --- | --- | --- | --- | +| JSON actor state | Small datasets, simple reads, whole dataset fits comfortably in memory. What the example uses. | [State](/docs/actors/state) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/per-tenant-database) | +| Actor SQLite (`rivetkit/db`) | Tables, indexes, SQL queries, larger-than-memory data, per-tenant relational schema. | [SQLite](/docs/actors/sqlite) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/kitchen-sink/src/actors/state/sqlite-raw.ts) | +| SQLite + Drizzle | Typed schema, query builder, and generated migration files on top of actor SQLite. | [SQLite + Drizzle](/docs/actors/sqlite-drizzle) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/kitchen-sink/src/actors/state/sqlite-drizzle/) | + +With either SQLite option, every tenant gets its own embedded SQLite database, since the database is scoped to the actor and the actor is scoped to the tenant. + +## Migrations + +The per-tenant example has no migrations because JSON state has no schema. When you adopt SQLite, migrations run per tenant database: + +- **Raw SQL**: `db({ onMigrate })` runs your migration SQL inside a SQLite savepoint before the actor serves traffic. If `onMigrate` throws, all migration SQL rolls back atomically and the actor does not start. See [SQLite](/docs/actors/sqlite). +- **Drizzle**: `drizzle-kit` generates migration files from your typed schema, and `db({ schema, migrations })` applies them when the actor wakes. See [SQLite + Drizzle](/docs/actors/sqlite-drizzle). + +Because each tenant has its own database, migrations roll out per actor as each tenant's actor wakes, rather than as one large migration against a shared database. + +## Tenant Id Must Come From Auth + +The example's sign-in is cosmetic: the client picks any company string and that string becomes the actor key, so any visitor can read and write any tenant's data. Do not ship this. As a required production extension (not implemented by the example): + +- Derive the tenant id from a verified credential, such as a JWT claim, never from user input. +- Validate the credential against `c.key` in `onBeforeConnect` (pass/fail) or `createConnState` (store the verified user on connection state). See [Authentication](/docs/actors/authentication) and [Connections](/docs/actors/connections). +- Add per-action permission checks on top of connection-level auth. See [Access Control](/docs/actors/access-control). + +## Actors + +- **Key**: `companyDatabase[companyName]` (single-element array key; `c.key[0]` is the company name) +- **Responsibility**: One actor per tenant. Holds that company's employees and projects in persistent state, serves reads and writes via actions, and broadcasts mutations to connected clients. +- **Actions** + - `addEmployee` + - `listEmployees` + - `addProject` + - `listProjects` + - `getStats` +- **Queues** + - None +- **Events** + - `employeeAdded` + - `projectAdded` +- **State** + - JSON + - `company_name` + - `employees` + - `projects` + - `created_at` + - `updated_at` + +Every write action follows the same mutate-then-broadcast shape: push the record into `c.state`, bump `updated_at`, broadcast the typed event, return the record. See [Actions](/docs/actors/actions) and [Events](/docs/actors/events). + +## Lifecycle + +```mermaid +sequenceDiagram + participant A as Tenant A client + participant DA as companyDatabase A + participant B as Tenant B client + participant DB as companyDatabase B + + Note over A: authenticate and derive tenant id + A->>DA: connect with key [tenantA] + Note over DA: createState seeds company_name, employees, projects + A->>DA: listEmployees() + listProjects() + getStats() + A->>DA: addEmployee(name, role) + DA-->>A: employeeAdded event + B->>DB: connect with key [tenantB] + Note over DB: separate actor, separate dataset + B->>DB: listEmployees() + DB-->>B: tenant B data only +``` + +In the example, the "authenticate" step is a free-text company picker. The rest of the flow matches the diagram: `createState` seeds the dataset on first creation, the dashboard loads with `listEmployees`, `listProjects`, and `getStats`, and every connected client of the same tenant receives `employeeAdded` and `projectAdded` events. + +## Security Checklist + +The example ships with none of these. Apply all of them before production. + +- **Tenant identity**: Derive the tenant id from a verified JWT claim, never from a client-supplied string. +- **Connection validation**: In `onBeforeConnect` or `createConnState`, verify the credential's tenant claim matches `c.key` and reject mismatches. +- **Per-action authorization**: Check the caller's role before mutating actions (`addEmployee`, `addProject`), not just at connect time. See [Access Control](/docs/actors/access-control). +- **Input validation**: Clamp name and role lengths and validate enums. The example only trims input and substitutes fallback defaults. +- **Key construction**: Always pass the tenant id as an array element (`key: [tenantId]`). Never interpolate tenant ids into key strings, and never build keys from one tenant's input to address another tenant's actor. +- **Growth limits**: As a recommended extension, cap or paginate the `employees` and `projects` arrays. The example lets them grow unboundedly in JSON state; move to [SQLite](/docs/actors/sqlite) when the dataset outgrows memory. + +_Source doc path: /cookbook/per-tenant-database_ diff --git a/.agents/skills/cron-jobs/reference/cookbook/vpc-air-gapped.md b/.agents/skills/cron-jobs/reference/cookbook/vpc-air-gapped.md new file mode 100644 index 0000000..f7d87a3 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/cookbook/vpc-air-gapped.md @@ -0,0 +1,136 @@ +# Deploying Rivet in a VPC or Air-Gapped Network + +> Source: `src/content/cookbook/vpc-air-gapped.mdx` +> Canonical URL: https://rivet.dev/cookbook/vpc-air-gapped +> Description: Run Rivet entirely inside your own perimeter: single-binary or Docker Compose install, file system storage with no database infrastructure, and no outbound telemetry by default. + +--- +Patterns for running self-hosted Rivet inside a private network: a VPC without internet egress, an on-premises rack, or a fully air-gapped environment. The engine is one service, the recommended single-node storage backend is the local file system, and the engine makes no outbound connections by default. Self-hosting is the only Rivet deployment model that supports air-gapped networks; see the [Self-Hosting Overview](/docs/self-hosting) for the full comparison with BYOC. + +## What Runs Inside the Perimeter + +A self-hosted deployment has three components, all of which live inside your network: + +| Component | Role | Inside the perimeter | +| --- | --- | --- | +| Your backend | Your application server, including the runner that executes actor code | Yes | +| Rivet Engine | Orchestration service that manages actor lifecycle, routes messages, and serves the dashboard and APIs | Yes | +| Storage | Persistence for actor state. Local file system for single-node, PostgreSQL or FoundationDB for multi-node | Yes | + +There is no license server, no Rivet Cloud account, and no callback to `rivet.dev`. Clients inside the perimeter reach actors through the engine's gateway over your private network. See [Architecture](/docs/self-hosting#architecture). + +## Single-Binary Install + +The engine compiles to a single `rivet-engine` binary. Build it from source outside the perimeter, then copy the binary across the boundary: + +```bash +git clone https://github.com/rivet-dev/rivet.git +cd rivet +cargo build --release -p rivet-engine +# Copy target/release/rivet-engine into the perimeter. +``` + +Prebuilt binaries are coming soon; see [Installing Rivet Engine](/docs/self-hosting/install) for current options. + +Run it with the file system backend, which stores everything on local disk and is the production-ready choice for single-node deployments. The [File System](/docs/self-hosting/filesystem) docs list air-gapped environments as a primary use case because it needs no database infrastructure: + +```bash +RIVET__database__file_system__path="/var/lib/rivet/data" ./rivet-engine +``` + +Configuration can also come from files. The engine discovers config at `/etc/rivet/config.json` on Linux (JSON, JSON5, JSONC, YAML, and YML are all supported), and `--config` overrides the path. Environment variables use the `RIVET__` prefix with `__` as the separator. See [Configuration](/docs/self-hosting/configuration). + +The engine serves its own dashboard on port `6420`, so inspection and namespace management work with nothing but a browser inside the perimeter. + +## Docker Compose Deployment + +For Docker hosts without registry access, move the engine image across the boundary the standard way: + +```bash +# Outside the perimeter. +docker pull rivetdev/engine:latest +docker save rivetdev/engine:latest -o rivet-engine.tar +# Inside the perimeter. +docker load -i rivet-engine.tar +``` + +Then run the engine and your app together in one Compose file: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - rivet-data:/data + environment: + RIVET__FILE_SYSTEM__PATH: "/data" + restart: unless-stopped + + my-app: + build: . + environment: + RIVET_ENDPOINT: "http://default:admin@rivet-engine:6420" + depends_on: + - rivet-engine + restart: unless-stopped + +volumes: + rivet-data: +``` + +`RIVET_ENDPOINT` uses the format `http://namespace:token@host:port` and tells your app to connect to the engine as a runner instead of running standalone. After both services start, register your runner with the engine through the dashboard or its API. The full walkthrough, including PostgreSQL setup for multi-node deployments, is in [Docker Compose](/docs/self-hosting/docker-compose). + +## No Outbound Telemetry + +The engine exports traces and metrics only when you opt in with OpenTelemetry. Export is disabled unless `RIVET_OTEL_ENABLED=1` is set, and the export target defaults to a local collector at `http://localhost:4317`. With no configuration, nothing crosses the perimeter. + +When you want observability, keep it inside the network: + +- Set `RIVET_OTEL_ENABLED=1` and point `RIVET_OTEL_GRPC_ENDPOINT` at a collector you run inside the perimeter. +- Adjust `RIVET_OTEL_SAMPLER_RATIO` to control trace sampling. +- Use the engine's health endpoint for liveness and readiness probes. + +See the [Production Checklist](/docs/self-hosting/production-checklist) for monitoring guidance. + +## Embedding Rivet in a Customer's Environment + +If you ship software that runs inside your customers' VPCs, the same setup turns Rivet into an internal component of your product rather than a service your customers must reach over the internet: + +- **Ship the engine next to your app.** Add `rivetdev/engine` to the Compose file or chart you already deliver. Your app finds it over the private network via `RIVET_ENDPOINT`, so one artifact deploys the whole stack. +- **One namespace per install.** The endpoint URL carries the namespace and token (`http://namespace:token@host:port`), so a single image works across customer deployments. See [Endpoints](/docs/general/endpoints). +- **Generate a strong admin token per install.** Replace the default token and keep it server-side. Never include the admin token in `RIVET_PUBLIC_ENDPOINT` or anywhere clients can read it. +- **Public endpoint only when needed.** `RIVET_PUBLIC_ENDPOINT` with a public (`pk_`) token is only required when browser clients connect to actors in [serverless runtime mode](/docs/general/runtime-modes). Backend-only deployments can skip it entirely. +- **TLS at the customer's edge.** Terminate TLS with the customer's reverse proxy or load balancer in front of the engine. + +## Scaling Past One Node + +| Backend | Use when | Status | +| --- | --- | --- | +| [File System](/docs/self-hosting/filesystem) (RocksDB-based) | Single-node deployments, including air-gapped installs | Production-ready, single node only | +| [PostgreSQL](/docs/self-hosting/postgres) | Multi-node deployments | Recommended for multi-node today, but experimental | +| FoundationDB | Largest production deployments | [Enterprise](/sales) | + +For multi-node deployments, run two or more engine nodes behind a load balancer and add NATS for pub/sub, which replaces the default PostgreSQL `LISTEN`/`NOTIFY` path at high throughput. Neither is needed for a single-node file system install. See the [Production Checklist](/docs/self-hosting/production-checklist). + +## Perimeter Checklist + +- **Admin token**: Generate a strong, random token for engine authentication and verify it is not exposed to clients. +- **TLS termination**: Encrypt connections to the engine via a reverse proxy or load balancer. +- **No public exposure**: Keep port `6420` reachable only from inside the perimeter unless clients outside it genuinely need access. +- **Health checks**: Configure liveness and readiness probes against the engine health endpoint. +- **Telemetry**: Leave OpenTelemetry export off, or point it at a collector inside the network. +- **Backups**: With the file system backend, back up the data directory. With PostgreSQL, configure automated backups and failover. + +## Full Configuration + +- [Self-Hosting Overview](/docs/self-hosting) for architecture and the self-host vs BYOC comparison +- [Installing Rivet Engine](/docs/self-hosting/install) for Docker, binary, and source installs +- [Docker Container](/docs/self-hosting/docker-container) and [Docker Compose](/docs/self-hosting/docker-compose) for container deployments +- [Kubernetes](/docs/self-hosting/kubernetes) for cluster deployments +- [Configuration](/docs/self-hosting/configuration) for every option and the full JSON schema +- [Endpoints](/docs/general/endpoints) for connecting your backend and clients +- [Production Checklist](/docs/self-hosting/production-checklist) before going live + +_Source doc path: /cookbook/vpc-air-gapped_ diff --git a/.agents/skills/cron-jobs/reference/deploy/aws-ecs.md b/.agents/skills/cron-jobs/reference/deploy/aws-ecs.md new file mode 100644 index 0000000..ab381ce --- /dev/null +++ b/.agents/skills/cron-jobs/reference/deploy/aws-ecs.md @@ -0,0 +1,13 @@ +# Deploying to AWS ECS + +> Source: `src/content/docs/deploy/aws-ecs.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/aws-ecs +> Description: Run your backend on Amazon ECS with Fargate. + +--- +See the [AWS ECS template](https://github.com/rivet-dev/template-aws-ecs) for deployment instructions: + +- [Deploy with Terraform](https://github.com/rivet-dev/template-aws-ecs#option-a-deploy-with-terraform) +- [Deploy with AWS CLI](https://github.com/rivet-dev/template-aws-ecs#option-b-deploy-with-aws-cli) + +_Source doc path: /docs/deploy/aws-ecs_ diff --git a/.agents/skills/cron-jobs/reference/deploy/aws-lambda.md b/.agents/skills/cron-jobs/reference/deploy/aws-lambda.md new file mode 100644 index 0000000..f1327cc --- /dev/null +++ b/.agents/skills/cron-jobs/reference/deploy/aws-lambda.md @@ -0,0 +1,10 @@ +# Deploy To Amazon Web Services Lambda + +> Source: `src/content/docs/deploy/aws-lambda.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/aws-lambda +> Description: _AWS Lambda is coming soon_ + +--- + + +_Source doc path: /docs/deploy/aws-lambda_ diff --git a/.agents/skills/cron-jobs/reference/deploy/cloudflare.md b/.agents/skills/cron-jobs/reference/deploy/cloudflare.md new file mode 100644 index 0000000..970078e --- /dev/null +++ b/.agents/skills/cron-jobs/reference/deploy/cloudflare.md @@ -0,0 +1,53 @@ +# Deploying to Cloudflare Workers + +> Source: `src/content/docs/deploy/cloudflare.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/cloudflare +> Description: Deploy an existing Rivet project to Cloudflare Workers. + +--- +This guide covers deploying an existing Rivet project to Cloudflare Workers. + +## Prerequisites + +- [Cloudflare account](https://dash.cloudflare.com/) +- [`wrangler`](https://developers.cloudflare.com/workers/wrangler/) configured for your account +- A Rivet namespace from the [Rivet Dashboard](https://dashboard.rivet.dev/) or a self-hosted Rivet Engine + +## Steps + +### Set up your project + +Follow the [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) to set up your project locally. + +### Configure Wrangler + +Set your Rivet connection values as Worker variables. Find `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` in the [Rivet Dashboard](https://dashboard.rivet.dev/) under **Settings → Namespace → Advanced → Backend Configuration** and copy them in. + +```toml wrangler.toml +name = "rivetkit-cloudflare" +main = "src/index.ts" +compatibility_date = "2025-04-01" +compatibility_flags = ["nodejs_compat"] + +[vars] +RIVET_ENDPOINT = "https://your-namespace:sk_...@api.rivet.dev" +RIVET_PUBLIC_ENDPOINT = "https://your-namespace@api.rivet.dev" +``` + +### Deploy + +```sh +npx wrangler deploy +``` + +### Register the Serverless Runner URL + +After deploy, set the Worker URL with the `/api/rivet` path as the serverless runner URL in Rivet. + +## Related + +- [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) +- [Deploying to Supabase Functions](/docs/deploy/supabase) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/deploy/cloudflare_ diff --git a/.agents/skills/cron-jobs/reference/deploy/container-runner.md b/.agents/skills/cron-jobs/reference/deploy/container-runner.md new file mode 100644 index 0000000..7bb0c5a --- /dev/null +++ b/.agents/skills/cron-jobs/reference/deploy/container-runner.md @@ -0,0 +1,95 @@ +# Container Runner + +> Source: `src/content/docs/deploy/container-runner.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/container-runner +> Description: Run any containerized server as a Rivet Actor. + +--- +The container runner (`rivet-container-runner`) is an adapter for running arbitrary containers as Rivet Actors. Use it for non-RivetKit workloads such as Unity or Godot dedicated game servers and batch jobs like FFmpeg transcoding. + +## Steps + +### Prerequisites + +- A containerized server (a Unity or Godot dedicated server, a plain Node process, or any HTTP/WebSocket server) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) +- Docker running locally + +### Install in Your Container + +Download the static binary from Rivet's release artifacts in your Dockerfile and set it as the entrypoint, passing your server's launch command after `--`: + +```dockerfile @nocheck +FROM debian:bookworm-slim +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl && rm -rf /var/lib/apt/lists/* + +# Install the Rivet container runner. +RUN curl -fsSL https://releases.rivet.dev/rivet/latest/container-runner/rivet-container-runner-x86_64-unknown-linux-musl \ + -o /usr/local/bin/rivet-container-runner \ + && chmod +x /usr/local/bin/rivet-container-runner + +# Your server binary and assets. +COPY build/ /game/ +WORKDIR /game + +ENTRYPOINT ["rivet-container-runner", "--", "./GameServer", "-batchmode", "-nographics", "-logFile", "-"] +``` + +Artifacts are published for `x86_64-unknown-linux-musl` and `aarch64-unknown-linux-musl`. The binaries are fully static, so they run in any Linux base image, including `scratch`. Pin a version by replacing `latest` with a release version, for example `https://releases.rivet.dev/rivet/2.3.3/container-runner/rivet-container-runner-x86_64-unknown-linux-musl`. + +### Deploy + +Deploy the image to [Rivet Compute](/docs/deploy/rivet-compute) with the CLI. For game servers, configure the pool with one actor per instance: + +```bash +npx @rivetkit/cli deploy \ + --token "$RIVET_CLOUD_TOKEN" \ + --instance-request-concurrency 1 \ + --dockerfile Dockerfile +``` + +### Create Actors and Connect Clients + +Create actors against the pool's runner (`default`) and connect clients through the gateway URL shown in the dashboard. WebSocket clients connect at the bare gateway URL with the `rivet` WebSocket subprotocol. + +## How It Works + +1. The engine cold-starts your container and calls `POST /api/rivet/start` on the port it injects as `RIVET_PORT`. +2. The runner spawns your server as a child process with `PORT` set to the child port, waits for the port to open, and reports the actor as running. +3. Gateway traffic for the actor arrives over Rivet's tunnel and is proxied to `127.0.0.1:`. WebSocket clients connect at the bare gateway URL with the `rivet` WebSocket subprotocol. Raw HTTP reaches the child under the `/request/*` prefix on the actor surface (the prefix is stripped before proxying); other paths are reserved for the runtime's own endpoints. +4. Child stdout and stderr are re-emitted with an `[actorId=... key=...]` prefix so actor logs are attributed in the dashboard. +5. When an actor stops, the runner sends its child `SIGTERM`, escalates to `SIGKILL` after a grace period, and exits the process once no actors remain. + +## Configuration + +All flags can also be set through environment variables: + +| Flag | Environment variable | Default | Description | +| --- | --- | --- | --- | +| `--port` | `RIVET_PORT` / `PORT` | `8080` | Serverless front-door HTTP port. Rivet Compute injects `RIVET_PORT` automatically. | +| `--child-port` | `CHILD_PORT` | `7770` | First local child port; each actor's child gets the next free port at or above this, exported to the child as `PORT`. | +| `--actor-name` | `RIVET_ACTOR_NAME` | `game` | Actor name this runner serves. | +| `--runner-version` | `RIVET_RUNNER_VERSION` | `1` | Version reported to the engine, used to drain old runners on deploy. | +| `--base-path` | `RIVET_SERVERLESS_BASE_PATH` | `/api/rivet` | Base path the engine calls for serverless start. | +| `--stop-grace-secs` | `RIVET_STOP_GRACE_SECS` | `25` | `SIGTERM` to `SIGKILL` grace period when stopping the child. Capped to a few seconds when the platform itself is reclaiming the instance, so shutdown fits inside the platform's own kill window. | +| `--readiness-timeout-secs` | `RIVET_READINESS_TIMEOUT_SECS` | `30` | How long to wait for the child's port to open before failing the start. | + +### Per-Actor Input + +The actor's `input` payload can override the launch spec per actor. All fields are optional and fall back to the entrypoint command. RivetKit clients pass this object directly; when creating actors through the raw engine API, encode it as CBOR before base64-encoding the `input` field: + +```json +{ + "command": ["./GameServer", "-batchmode"], + "args": ["-extra-flag"], + "env": { "MATCH_MODE": "ranked" } +} +``` + +`command` replaces the entrypoint command template, `args` are appended to it, and `env` adds environment variables for the child. + +## Source and Examples + +The runner and a full end-to-end example, including a Unity FishNet demo project and a local test harness, live in the Rivet repository under [`container-runner/`](https://github.com/rivet-dev/rivet/tree/main/container-runner). + +_Source doc path: /docs/deploy/container-runner_ diff --git a/.agents/skills/cron-jobs/reference/deploy/freestyle.md b/.agents/skills/cron-jobs/reference/deploy/freestyle.md new file mode 100644 index 0000000..eb6ed57 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/deploy/freestyle.md @@ -0,0 +1,136 @@ +# Deploying to Freestyle + +> Source: `src/content/docs/deploy/freestyle.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/freestyle +> Description: Deploy RivetKit app to Freestyle.sh, a cloud platform for running AI-generated code with built-in security and scalability. + +--- +Freestyle provides built-in security for running untrusted AI-generated code, making it ideal for AI agent applications. Using Rivet, it is easy to deploy your vibe-coded or user-provided RivetKit backends straight to Freestyle. + +- [Freestyle + Rivet](https://github.com/rivet-dev/rivet/tree/main/examples/freestyle) — Complete example of deploying RivetKit app to Freestyle.sh. + +## Setup + +### Install packages + +Install RivetKit and Hono and create your registry: + +```bash +npm install rivetkit hono +``` + +### Configure serverless driver + +Update your server code to run the registry serverless with Deno. + +```typescript index.ts @hide +import { actor, setup } from "rivetkit"; + +export const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, x: number) => { + c.state.count += x; + return c.state.count; + }, + }, +}); + +export const registry = setup({ + use: { counter }, +}); +registry.start(); +``` + +```typescript server.ts @nocheck +import { registry } from "./index"; + +// Freestyle uses Deno under the hood for web deployments +// @ts-ignore Deno is a Freestyle runtime global +Deno.serve((request: Request) => registry.handler(request)); +``` + +The `Deno.serve` API is provided by Freestyle's runtime environment. The `@ts-ignore` comment suppresses TypeScript errors for this platform-specific API. + +### Deploy to Freestyle + +Deploy your application to Freestyle with the correct configuration. Create a deployment script or add this to your existing deployment process: + +```typescript @nocheck +const FREESTYLE_DOMAIN = "my-domain.style.dev"; // Change to your desired Freestyle domain + +declare const freestyle: any; +declare const buildDir: string; + +const res = await freestyle.deployWeb(buildDir, { + envVars: { + FREESTYLE_ENDPOINT: `https://${FREESTYLE_DOMAIN}`, + RIVET_RUNNER_KIND: "serverless", + // For self-hosted instances: + // RIVET_ENDPOINT: "http://127.0.0.1:6420", + RIVET_ENDPOINT: "api.rivet.dev", + }, + timeout: 60 * 5, // Increases max request lifetime on the runner + entrypoint: "server.ts", // File which starts serverless runner + domains: [FREESTYLE_DOMAIN], + build: false, +}); +``` + +Details on `buildDir` and other settings are available on [Freestyle docs](https://docs.freestyle.sh/web/web). + +Run this deployment script to push your application to Freestyle. + +**Deployment Configuration:** + +- `timeout: 60 * 5` - Set timeout to 5 minutes for actor operations - it's important to keep this high +- `entrypoint: "server.ts"` - Entry point file with your serverless setup +- `domains` - Your Freestyle domain(s) +- `build: false` - Disable build if you're pre-building your assets + +### Configure runner + +Update the runner configuration on the Rivet side to connect with your Freestyle deployment. Create a configuration script and run it after your Freestyle deployment is live: + +```typescript @nocheck +import { RivetClient } from "@rivetkit/engine-api-full"; + +const rivet = new RivetClient({ + environment: "https://api.rivet.dev", + token: process.env.RIVET_API_TOKEN, +}); + +const FREESTYLE_DOMAIN = "my-domain.style.dev"; // Change to your desired Freestyle domain +const RIVET_NAMESPACE = "my-rivet-namespace"; // Change to your Rivet namespace + +await rivet.runnerConfigsUpsert("freestyle-runner", { + namespace: RIVET_NAMESPACE, + datacenters: { + default: { + serverless: { + url: `https://${FREESTYLE_DOMAIN}/start`, + runnersMargin: 1, + minRunners: 1, + maxRunners: 1, + slotsPerRunner: 1, + // Must be shorter than Freestyle request `timeout` config + requestLifespan: 60 * 5 - 5, + }, + }, + }, +}); +``` + +Execute this configuration script to register your Freestyle deployment with Rivet. + +**Runner Configuration:** + +- `url` - Freestyle deployment URL with `/start` endpoint +- `runnersMargin` - Buffer of runners to maintain +- `minRunners/maxRunners` - Scaling limits +- `slotsPerRunner` - Concurrent actors per runner +- `requestLifespan` - Request timeout (slightly less than Freestyle timeout) + +Once executed, Rivet will be connected to your Freestyle serverless instance. + +_Source doc path: /docs/deploy/freestyle_ diff --git a/.agents/skills/cron-jobs/reference/deploy/gcp-cloud-run.md b/.agents/skills/cron-jobs/reference/deploy/gcp-cloud-run.md new file mode 100644 index 0000000..f140950 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/deploy/gcp-cloud-run.md @@ -0,0 +1,74 @@ +# Deploying to Google Cloud Run + +> Source: `src/content/docs/deploy/gcp-cloud-run.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/gcp-cloud-run +> Description: Deploy your RivetKit app to Google Cloud Run. + +--- +## Steps + +### Prerequisites + +- Google Cloud project with Cloud Run and Artifact Registry enabled +- `gcloud` CLI authenticated (`gcloud auth login`) and project set (`gcloud config set project YOUR_PROJECT`) +- Artifact Registry repository or Container Registry enabled +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Package Your App + +Create a `Dockerfile` in your project root: + +```dockerfile +FROM node:20-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev +COPY . . +ENV PORT=8080 +CMD ["node", "server.js"] +``` + +### Build and Push the Image + +Use Cloud Build to build and push the image. Replace the region and repository with your own. + +```bash +gcloud builds submit --tag us-central1-docker.pkg.dev/YOUR_PROJECT/rivetkit-app/rivetkit-app:latest +``` + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select Google Cloud Run as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables to use when deploying. + +### Deploy to Cloud Run + +Deploy the service to Cloud Run, passing the Rivet environment variables. Adjust the region and image as needed. + +```bash +gcloud run deploy rivetkit-app \ + --image us-central1-docker.pkg.dev/YOUR_PROJECT/rivetkit-app/rivetkit-app:latest \ + --region us-central1 \ + --allow-unauthenticated \ + --min-instances 1 \ + --set-env-vars RIVET_ENDPOINT=,RIVET_PUBLIC_ENDPOINT= +``` + +### Connect to Rivet + +1. After deployment, note the service URL (e.g. `https://rivetkit-app-xxxxx-uc.a.run.app`) +2. On the Rivet dashboard, paste your URL with the `/api/rivet` path into the connect form (e.g. `https://rivetkit-app-xxxxx-uc.a.run.app/api/rivet`) +3. Click "Done" + +### Verify + +Confirm the service is running: + +```bash +gcloud run services describe rivetkit-app --region us-central1 --format 'value(status.conditions[?type="Ready"].status)' +``` + +Your app should appear as connected on the Rivet dashboard once the service reports ready. + +_Source doc path: /docs/deploy/gcp-cloud-run_ diff --git a/.agents/skills/cron-jobs/reference/deploy/hetzner.md b/.agents/skills/cron-jobs/reference/deploy/hetzner.md new file mode 100644 index 0000000..5b61024 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/deploy/hetzner.md @@ -0,0 +1,10 @@ +# Deploying to Hetzner + +> Source: `src/content/docs/deploy/hetzner.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/hetzner +> Description: Please see the VM & Bare Metal guide. + +--- + + +_Source doc path: /docs/deploy/hetzner_ diff --git a/.agents/skills/cron-jobs/reference/deploy/kubernetes.md b/.agents/skills/cron-jobs/reference/deploy/kubernetes.md new file mode 100644 index 0000000..43496a9 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/deploy/kubernetes.md @@ -0,0 +1,121 @@ +# Deploying to Kubernetes + +> Source: `src/content/docs/deploy/kubernetes.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/kubernetes +> Description: Deploy your RivetKit app to any Kubernetes cluster. + +--- +## Steps + +### Prerequisites + +- A Kubernetes cluster with `kubectl` access (EKS, GKE, k3s, etc.) +- Container registry credentials (Docker Hub, GHCR, GCR, etc.) +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Package Your App + +Create a `Dockerfile` in your project root: + +```dockerfile +FROM node:20-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev +COPY . . +ENV PORT=8080 +CMD ["node", "server.js"] +``` + +### Build and Push the Image + +```bash +docker build -t registry.example.com/your-team/rivetkit-app:latest . +docker push registry.example.com/your-team/rivetkit-app:latest +``` + +Replace `registry.example.com/your-team` with your registry path. Auth with `docker login` first if needed. + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select Kubernetes as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables. + +Create a `rivetkit-secrets.yaml` for your environment variables: + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: rivetkit-secrets +type: Opaque +stringData: + RIVET_ENDPOINT: + RIVET_PUBLIC_ENDPOINT: +``` + +### Deploy to Kubernetes + +Create a `deployment.yaml`: + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: rivetkit-app +spec: + replicas: 1 + selector: + matchLabels: + app: rivetkit-app + template: + metadata: + labels: + app: rivetkit-app + spec: + # Allow enough time for actors to gracefully stop on SIGTERM. + # The runner waits up to 30m for actors to finish. + # Add buffer for runner shutdown overhead after actors stop. + # See: /docs/actors/versions#graceful-shutdown-sigterm + terminationGracePeriodSeconds: 2100 + containers: + - name: rivetkit-app + image: registry.example.com/your-team/rivetkit-app:latest + envFrom: + - secretRef: + name: rivetkit-secrets +``` + +Apply both manifests: + +```bash +kubectl apply -f rivetkit-secrets.yaml +kubectl apply -f deployment.yaml +``` + +### Connect to Rivet + +1. Add a `Service` and Ingress to expose your app externally (e.g. `my-app.example.com`) +2. On the Rivet dashboard, paste your domain with the `/api/rivet` path into the connect form (e.g. `https://my-app.example.com/api/rivet`) +3. Click "Done" + +Rivet envoys connect to your app over long-lived WebSockets, and your app's clients (browsers, SDKs) do the same. Default Ingress and cloud load balancer idle timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +Raise the idle / read / send timeout on every Ingress and load balancer in front of your app to at least 1 hour (`3600` seconds). Examples: + +- **NGINX Ingress**: `nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"` and `nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"` +- **AWS Load Balancer Controller (ALB)**: `alb.ingress.kubernetes.io/load-balancer-attributes: idle_timeout.timeout_seconds=3600` +- **GCE Ingress (GKE)**: set `timeoutSec: 3600` on the `BackendConfig` referenced by the Service. + +### Verify + +Check that the pod is running: + +```bash +kubectl get pods -l app=rivetkit-app +``` + +Your app should appear as connected on the Rivet dashboard once the pod is ready. + +_Source doc path: /docs/deploy/kubernetes_ diff --git a/.agents/skills/cron-jobs/reference/deploy/railway.md b/.agents/skills/cron-jobs/reference/deploy/railway.md new file mode 100644 index 0000000..640ac37 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/deploy/railway.md @@ -0,0 +1,45 @@ +# Deploying to Railway + +> Source: `src/content/docs/deploy/railway.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/railway +> Description: Deploy your RivetKit app to Railway. + +--- +## Steps + +### Prerequisites + +- [Railway account](https://railway.app) +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Deploy to Railway + +1. Connect your GitHub account to Railway +2. Select your repository containing your RivetKit app +3. Railway will automatically detect and deploy your app + +See [Railway's deployment docs](https://docs.railway.com/quick-start) for more details. + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select Railway as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables to add to your Railway service. + +See [Railway's environment variables docs](https://docs.railway.com/guides/variables#service-variables) for more details. + +### Connect to Rivet + +1. In your Railway project, go to **Settings > Networking** +2. Click **Create Custom Domain** then **Create Domain** to generate a Railway domain (e.g. `my-app.railway.app`) +3. On the Rivet dashboard, paste your domain with the `/api/rivet` path into the connect form (e.g. `https://my-app.railway.app/api/rivet`) +4. Click "Done" + +Rivet envoys connect to your app over long-lived WebSockets, and your app's clients (browsers, SDKs) do the same. Railway's HTTP proxy supports WebSockets, but if you front your app with your own reverse proxy (NGINX, Caddy, etc.) inside the Railway service, raise its idle / read timeout to at least 1 hour (`3600` seconds). Default proxy timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +### Configure Sleeping & Multi-Region (Optional) + +- [Enable App Sleeping](https://docs.railway.com/reference/app-sleeping) to reduce costs when idle +- [Configure Multi-Region](https://docs.railway.com/reference/deployment-regions) to deploy closer to your users + +_Source doc path: /docs/deploy/railway_ diff --git a/.agents/skills/cron-jobs/reference/deploy/rivet-compute.md b/.agents/skills/cron-jobs/reference/deploy/rivet-compute.md new file mode 100644 index 0000000..69507aa --- /dev/null +++ b/.agents/skills/cron-jobs/reference/deploy/rivet-compute.md @@ -0,0 +1,144 @@ +# Deploying to Rivet Compute + +> Source: `src/content/docs/deploy/rivet-compute.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/rivet-compute +> Description: Run your backend on Rivet Compute. + +--- +Using an AI coding agent? Open **Connect** on the [Rivet dashboard](https://dashboard.rivet.dev), select **Rivet Cloud**, and paste the one-shot prompt into your agent and have it connect with Rivet Compute for you. + +## Steps + +### Prerequisites + +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- A [Rivet Cloud](https://dashboard.rivet.dev) account and project +- Docker running locally + +### Create a Dockerfile + +Add a `Dockerfile` to your project root that builds and runs your RivetKit server: + +```dockerfile @nocheck +FROM node:24-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev +COPY . . +CMD ["node", "src/server.js"] +``` + +### Get Your Cloud Token + +1. Open the [Rivet dashboard](https://dashboard.rivet.dev) and navigate to your project +2. Click **Connect** and select **Rivet Cloud** +3. Copy the **`RIVET_CLOUD_TOKEN`** value shown + +### Deploy + +Run the deploy command from your project root. The token is saved to `~/.rivet/credentials`, so later deploys can omit it. + +```bash +npx @rivetkit/cli deploy --token cloud_api_xxxxx +``` + +The CLI resolves your project from the token, builds and pushes your Docker image to Rivet's built-in registry, upserts the managed pool, and prints the deployment URL on stdout when the pool is ready. + +### Optionally Add CI + +After local deploys work, install the GitHub Actions workflow that deploys on every push and pull request: + +```bash +npx @rivetkit/cli setup-ci +``` + +This writes `.github/workflows/rivet-deploy.yml`. Add your token as a repository secret to enable it: + +```bash +gh secret set RIVET_CLOUD_TOKEN +``` + +The workflow creates production and pull-request namespaces, posts preview links, and cleans up PR namespaces when pull requests close. See the [CLI reference](/docs/cli) for all commands. + +### Monitor Deployment + +The dashboard shows live status as Rivet Compute provisions your backend: + +| Status | Description | +| --- | --- | +| Initializing | Starting the runtime environment | +| Deploying | Pulling and launching your container | +| Binding | Connecting the runner to the network | +| Ready | Deployment complete | + +Once the status reaches **Ready**, your backend is live and actors are available for connections. + +If you are an agent monitoring the deployment via API rather than the dashboard, poll the managed-pool endpoint on the Cloud API. + +The `RIVET_CLOUD_TOKEN` secret is a `cloud_api_*` management token scoped to the Cloud API at `cloud-api.rivet.dev`. Use it for `Authorization: Bearer ...` against the Cloud API. Do not confuse it with a `pk_*` publishable key, which is scoped to the Rivet Engine API at `api.rivet.dev` and will 401 against this endpoint. + +Substitute `$CLOUD_API_URL` (typically `https://cloud-api.rivet.dev`), `$PROJECT`, `$ORG`, `$CLOUD_NAMESPACE`, and `$CLOUD_TOKEN`. + +Poll every 5 seconds until `status` is `ready`. Stop and investigate if `status` is `error`. + +```bash +curl -s "$CLOUD_API_URL/projects/$PROJECT/namespaces/$CLOUD_NAMESPACE/managed-pools/default?org=$ORG" -H "Authorization: Bearer $CLOUD_TOKEN" +``` + +## Checking Logs + +Use the CLI to read your deployment's logs. By default `rivet logs` prints the last 100 lines from the `production` namespace, oldest to newest, then exits. + +```bash +npx @rivetkit/cli logs +``` + +The CLI resolves your token the same way `deploy` does (the `--token` flag, then the `RIVET_CLOUD_TOKEN` environment variable, then `~/.rivet/credentials`). + +### Follow logs live + +Pass `--follow` (`-f`) to stream new logs as they arrive instead of fetching history: + +```bash +npx @rivetkit/cli logs --follow +``` + +Each formatted line is printed as ` [] `: + +``` +2026-06-16T18:26:51.160Z [INFO] eu-central-1 server listening on port 3000 +2026-06-17T11:24:20.425Z [ERROR] us-east-1 failed to connect to upstream +``` + +A few examples: + +```bash +# Last 200 lines from a specific namespace +npx @rivetkit/cli logs --namespace production -n 200 + +# Live tail, only lines containing "error" +npx @rivetkit/cli logs --follow --contains error + +# JSON output piped to jq +npx @rivetkit/cli logs -n 50 --json | jq . +``` + +## Troubleshooting + +If the status stays in **Initializing** for more than a few minutes, verify that: + +- The `RIVET_CLOUD_TOKEN` secret is correctly set in your GitHub repository +- The GitHub Actions workflow completed without errors — check the run logs + +If the status shows **Error**, check that your container starts successfully and does not exit immediately (you can check this with container logs). Common causes: + +- The server file is not calling `registry.start()` +- A runtime crash on startup — test the image locally with `docker run` +- The server is not listening on the `RIVET_PORT` environment variable (RivetKit reads `RIVET_PORT`, defaulting to `3000`) + +## Pricing + +You are billed for the compute resources your deployment uses while it is running. + +_Source doc path: /docs/deploy/rivet-compute_ diff --git a/.agents/skills/cron-jobs/reference/deploy/supabase.md b/.agents/skills/cron-jobs/reference/deploy/supabase.md new file mode 100644 index 0000000..fa98436 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/deploy/supabase.md @@ -0,0 +1,50 @@ +# Deploying to Supabase Functions + +> Source: `src/content/docs/deploy/supabase.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/supabase +> Description: Deploy an existing Rivet project to Supabase Edge Functions. + +--- +This guide covers deploying an existing Rivet project to Supabase Edge Functions. + +## Prerequisites + +- [Supabase project](https://supabase.com/) +- [Supabase CLI](https://supabase.com/docs/guides/cli) configured for your project +- A Rivet namespace from the [Rivet Dashboard](https://dashboard.rivet.dev/) or a self-hosted Rivet Engine + +## Steps + +### Set up your project + +Follow the [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) to set up your project locally. + +### Set Secrets + +Set your Rivet connection values as Supabase secrets. Find `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` in the [Rivet Dashboard](https://dashboard.rivet.dev/) under **Settings → Namespace → Advanced → Backend Configuration** and copy them in. + +```sh +npx supabase secrets set \ + RIVET_ENDPOINT=https://your-namespace:sk_...@api.rivet.dev \ + RIVET_PUBLIC_ENDPOINT=https://your-namespace@api.rivet.dev +``` + +### Deploy + +Make sure the function has the `deno.json` import map from the [quickstart](/docs/actors/quickstart/supabase) that points `rivetkit` at `@rivetkit/supabase`. It keeps the deploy to the WebAssembly runtime; without it the deploy pulls Rivet's native engine and fails with a `413` (request too large). + +```sh +npx supabase functions deploy rivet +``` + +### Register the Serverless Runner URL + +After deploy, set the function URL with the `/api/rivet` path as the serverless runner URL in Rivet. For a function named `rivet`, this is usually `https://your-project.functions.supabase.co/functions/v1/rivet/api/rivet`. + +## Related + +- [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) +- [Deploying to Cloudflare Workers](/docs/deploy/cloudflare) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/deploy/supabase_ diff --git a/.agents/skills/cron-jobs/reference/deploy/vercel.md b/.agents/skills/cron-jobs/reference/deploy/vercel.md new file mode 100644 index 0000000..e8b5ba3 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/deploy/vercel.md @@ -0,0 +1,138 @@ +# Deploying to Vercel + +> Source: `src/content/docs/deploy/vercel.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/vercel +> Description: Deploy your Next.js Rivet app to Vercel. + +--- +This guide assumes a Next.js app. + +## Prerequisites + +- [Vercel account](https://vercel.com/) +- A Next.js Rivet app +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +## Steps + +### Set up your project + +Follow the [Next.js Quickstart](/docs/actors/quickstart/next-js) to set up your project. + +### Verify Your Project Structure + +Your Next.js project should have the following structure: + +- `src/app/api/rivet/[...all]/route.ts`: RivetKit route handler +- `src/rivet/registry.ts`: Actor definitions and registry + +The route handler sets `maxDuration` to extend the serverless function timeout so long-lived actor requests are not cut short: + +```ts src/app/api/rivet/[...all]/route.ts @nocheck +import { toNextHandler } from "@rivetkit/next-js"; +import { registry } from "@/rivet/registry"; + +export const maxDuration = 300; + +export const { GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS } = toNextHandler(registry); +``` + +### Set Environment Variables + +Set `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` in your Vercel project settings using the URL auth format: + +``` +RIVET_ENDPOINT=https://my-namespace:sk_****@api.rivet.dev +RIVET_PUBLIC_ENDPOINT=https://my-namespace:pk_****@api.rivet.dev +``` + +`RIVET_ENDPOINT` uses the secret token for server-side access. `RIVET_PUBLIC_ENDPOINT` uses the publishable token and tells the metadata endpoint what connection info to provide to clients. + +### Deploy to Vercel + +1. Connect your GitHub repository to Vercel +2. Vercel will deploy your app + +### Configure Preview Deployments (Recommended) + +Add a GitHub action to automatically create isolated Rivet namespaces for each PR: + +1. Add these secrets to your GitHub repository: + - `RIVET_CLOUD_TOKEN`: Get from [Rivet Dashboard](https://dashboard.rivet.dev) → Settings → Advanced → Cloud API Tokens + - `VERCEL_TOKEN`: Get from [Vercel Account Settings](https://vercel.com/account/tokens) + +2. Create `.github/workflows/rivet-preview.yml`: + +```yaml +name: Rivet Preview + +on: + pull_request: + types: [opened, synchronize, reopened] + push: + branches: [main] + +concurrency: + group: rivet-preview-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + rivet-preview: + runs-on: ubuntu-latest + permissions: + pull-requests: write + steps: + - uses: rivet-dev/preview-namespace-action@v1 + with: + platform: vercel + rivet-token: ${{ secrets.RIVET_CLOUD_TOKEN }} + vercel-token: ${{ secrets.VERCEL_TOKEN }} +``` + +## Troubleshooting + +``` +Error: ENOENT: no such file or directory, mkdir '.../rivetkit/.../state' +``` + +**Cause:** The `RIVET_ENDPOINT` environment variable is not configured. RivetKit falls back to the file system driver, which fails in Vercel's read-only serverless environment. + +**Solution:** Ensure `RIVET_ENDPOINT` is set with your Rivet endpoint using the URL auth format: + +``` +RIVET_ENDPOINT=https://my-namespace:sk_****@api.rivet.dev +``` + +If using the [preview-namespace-action](https://github.com/rivet-dev/preview-namespace-action), this is configured automatically. + +The `/api/rivet/metadata` endpoint returns data but `clientEndpoint`, `clientNamespace`, and `clientToken` are missing. + +**Cause:** The `RIVET_PUBLIC_ENDPOINT` environment variable is not configured. This tells the metadata endpoint what connection info to provide to clients. + +**Solution:** Set `RIVET_PUBLIC_ENDPOINT` with the publishable token (for client access): + +``` +RIVET_PUBLIC_ENDPOINT=https://my-namespace:pk_****@api.rivet.dev +``` + +If using the [preview-namespace-action](https://github.com/rivet-dev/preview-namespace-action), this is configured automatically. + +Rivet fails to connect to your Vercel deployment with a 401 error mentioning "Authentication Required". + +**Cause:** [Vercel Deployment Protection](https://vercel.com/docs/security/deployment-protection) is blocking requests from Rivet. + +**Solution:** + +1. Create a bypass secret in your Vercel project settings +2. In Rivet, go to **Settings > Providers** +3. Click the three dots on your provider and select **Edit** +4. Click **Add Header** and add `x-vercel-protection-bypass` with your bypass secret + +If using the [preview-namespace-action](https://github.com/rivet-dev/preview-namespace-action), this is configured automatically. + +## Related + +- [Next.js Quickstart](/docs/actors/quickstart/next-js) +- [Self-Hosting](/docs/general/self-hosting) + +_Source doc path: /docs/deploy/vercel_ diff --git a/.agents/skills/cron-jobs/reference/deploy/vm-and-bare-metal.md b/.agents/skills/cron-jobs/reference/deploy/vm-and-bare-metal.md new file mode 100644 index 0000000..6a123f9 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/deploy/vm-and-bare-metal.md @@ -0,0 +1,96 @@ +# Deploying to VMs & Bare Metal + +> Source: `src/content/docs/deploy/vm-and-bare-metal.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/vm-and-bare-metal +> Description: Deploy your RivetKit app to any Linux VM or bare metal host. + +--- +## Steps + +### Prerequisites + +- A Linux VM or bare metal server with SSH access +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Upload Your App + +- Build your RivetKit app locally +- Copy the build output to your server (example): + +```bash +scp -r ./dist user@server:/opt/rivetkit-app +``` + +Place the files somewhere readable by the service user, such as `/opt/rivetkit-app`. + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select VM & Bare Metal as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables to use in the next step. + +### Create the systemd Service + +Create `/etc/systemd/system/rivetkit-app.service`: + +```ini +[Unit] +Description=RivetKit App +After=network.target + +[Service] +Type=simple +WorkingDirectory=/opt/rivetkit-app +ExecStart=/usr/bin/node server.js +Restart=on-failure +Environment=RIVET_ENDPOINT= +Environment=RIVET_PUBLIC_ENDPOINT= + +[Install] +WantedBy=multi-user.target +``` + +Replace the environment values with those from the Rivet dashboard and adjust paths to match your deployment. + +### Start the Service + +Reload systemd units and start the service: + +```bash +sudo systemctl daemon-reload +sudo systemctl enable --now rivetkit-app.service +``` + +### Connect to Rivet + +1. Ensure your server is accessible via a public URL (e.g. `https://my-app.example.com`) +2. On the Rivet dashboard, paste your URL with the `/api/rivet` path into the connect form (e.g. `https://my-app.example.com/api/rivet`) +3. Click "Done" + +If you front your app with a reverse proxy or load balancer (NGINX, HAProxy, Caddy, AWS ALB/NLB, etc.), raise its idle / read timeout to at least 1 hour (`3600` seconds). Rivet envoys connect to your app over long-lived WebSockets, and clients (browsers, SDKs) do the same. Default proxy timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +Examples: + +- **NGINX**: `proxy_read_timeout 3600s;` and `proxy_send_timeout 3600s;` in the relevant `location` block. +- **HAProxy**: `timeout client 1h` and `timeout server 1h` in the matching frontend / backend. +- **AWS ALB / NLB**: set the load balancer attribute `idle_timeout.timeout_seconds = 3600`. + +## Operating + +### Restart + +Restart the service after deploying new builds or environment changes: + +```bash +sudo systemctl restart rivetkit-app.service +``` + +### Logs + +Follow realtime logs when debugging: + +```bash +sudo journalctl -u rivetkit-app.service -f +``` + +_Source doc path: /docs/deploy/vm-and-bare-metal_ diff --git a/.agents/skills/cron-jobs/reference/general/actor-configuration.md b/.agents/skills/cron-jobs/reference/general/actor-configuration.md new file mode 100644 index 0000000..72bc6fd --- /dev/null +++ b/.agents/skills/cron-jobs/reference/general/actor-configuration.md @@ -0,0 +1,19 @@ +# Actor Configuration + +> Source: `src/content/docs/general/actor-configuration.mdx` +> Canonical URL: https://rivet.dev/docs/general/actor-configuration +> Description: This page documents the configuration options available when defining a RivetKit actor. The actor configuration is passed to the `actor()` function. + +--- +## Basic Example + +## Configuration Reference + +## Related + +- [Registry Configuration](/docs/general/registry-configuration): Configure the RivetKit registry +- [State](/docs/actors/state): Managing actor state +- [Actions](/docs/actors/actions): Defining actor actions +- [Lifecycle](/docs/actors/lifecycle): Actor lifecycle hooks + +_Source doc path: /docs/general/actor-configuration_ diff --git a/.agents/skills/cron-jobs/reference/general/architecture.md b/.agents/skills/cron-jobs/reference/general/architecture.md new file mode 100644 index 0000000..3da2912 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/general/architecture.md @@ -0,0 +1,452 @@ +# Architecture + +> Source: `src/content/docs/general/architecture.mdx` +> Canonical URL: https://rivet.dev/docs/general/architecture +> Description: - rivetkit is the typescript library used for both local development & to connect your application to rivet - a rivetkit instance is called a "runner." you can run multiple runners to scale rivetkit horizontally. read omre about runners below. + +--- +## 3 ways of running + +### rivetkit + +- rivetkit is the typescript library used for both local development & to connect your application to rivet +- a rivetkit instance is called a "runner." you can run multiple runners to scale rivetkit horizontally. read more about runners below. + +#### local development + +- in local development, rivetkit provides a full actor environment for single-node deployments + +#### drivers + +- rivetkit supports multiple drivers. currently supports: file system (default in local dev), memory, rivet engine (used for rivet cloud & self-hosting), cloudflare durable objects (does not rely on rivet engine) +- drivers are very flexible to enable you to write your actors once and plug in to any system that fits your architecture adequately +- see the driver interface + - actordriver https://github.com/rivet-dev/rivet/blob/eeb01fc4d9ca0e06f2e740d267bd53280ca7330e/rivetkit-typescript/packages/rivetkit/src/actor/driver.ts + - managerdriver https://github.com/rivet-dev/rivet/blob/eeb01fc4d9ca0e06f2e740d267bd53280ca7330e/rivetkit-typescript/packages/rivetkit/src/manager/driver.ts + +### rivet cloud + +- provides multi-region and highest performance out of the box +- accessible at dashboard.rivet.dev and the api is avialble at api.rivet.dev + +### rivet self-hosted + +- available as a standalone rust binary or a docker contianer +- can be configured to persist to postgres or rocksdb +- can scale horiziontally across multipe nodes and can scale across multiple regions +- see [self-hosting docs](/docs/self-hosting/) + +## actors + +- Actors for long-lived processes with durable state, realtime, and hibernate when not in use. read more about actors at a high level at (link to actors/index) + +### actor-per-entity + +- actors are designed to have an actor-per-entity +- you can think about actors a bit like objects in object-oriented programming where each is responsible for their own state and expose methods (ie actions in our case) +- examples include + - actor per user + - actor per user session + - actor per document + - actor per game room + - actor per tenant + - actor per rate limit topic + +### architecting for scale + +- actors scale by: + - having isolated state to each actor that combines compute and storage for in-memory reads and writes + - communication is standardized based on actions & events + - scale horizontally +- read more about scaling at [Design Patterns](/docs/actors/design-patterns) + +### horizontal scaling + +- actors can run across multiple rivetkit runners. this is orchestrated by rivetkit itself. + +### lifecycle + +actors have create, destroy, wake, and sleep lifecycle hooks that you can implement to modify behavior. see the lifecycle docs for reference on actor lifecycel hook sequences + +### actor sleeping + +- actors sleep when not in use +- an actor is considered not in use when there are no active network connections to the actor (or the network connections are hibernatable websockets, see below) and there are no actions in flight +- actors have a sleep timeout (configured in `options.sleepTimeout`) that decides how long to keep the actor in memory with no recent activity +- sleep can be held off for the lifetime of a promise with `c.keepAwake(promise)` +- see the [sleeping docs](/docs/actors/lifecycle#sleeping) for full details + +### wake events + +- actors can wake to any of the follwoing events: + - network requests + - websocket messages + - alarms (see scheduling docs) + +### live actor migration + +- live actor migrations lets your application ugprade, crash, or hot reload cahnges without interruption to your user or application (including websockets) +- this is powered by hibernating websockets for live websocket migraiton & our fault tolerance mechanism (read more below) + +### coldstart performance + +- actors have negligible coldstart performance. the code to run the actor is already started (ie the runner), so creating/starting an actor is incredibly cheap. +- creating new actors with a key requires some overhead to communicate with other regions in order to reserve the actor's key (see below). actors can be created without keys with near-0 latency. + +### multi-region, globally unique actor keys + +- actors can optionally have a globally unique "key" +- when creating an actor with a key +- this system is highly optimized to reduce wan round trips using per-key Paxos with a custom database called Epoxy (https://github.com/rivet-dev/rivet/tree/main/engine/packages/epoxy) +- limitation: when creating an actor with a given key, that key will always be pinned to that region even if the actor is destroyed. creating a new actor with the same key will always live in the same region. +- see the actors keys document + +### input + +- actors have input data that can be passed to them when constructed +- this is similar to apssing data to a constructor in an object + +### generic parameters + +actor definitions include the following generic parameters that you'll see frequently in the code: + +- state +- conn state +- conn params +- ephemeral variables +- input data +- (experimental) database connector + +### persistence + +- state automatically flushes to storage intelligently +- to force a state flush and wait for it to finish, call (TODO: look this up in state document) +- read more about state persistence in the state document (link to document) +- state is stored in the same place as where the actor lives. loading an actor in to memory has comparable performance to network attached storage, and once in memory, has performance of any standard in-memory read/write like a variable. + +### scheduling & alarms + +- actors have a scheduling api to be able to wake up at any time in the indefinite future +- think of this like setTimeout but without a max timeout +- rivet is responsible for waking the actor when this timeout wakes + +### ephemeral variables + +- actors have the ability to create ephemrla variables for things that you do not want to be persisted with the actor's state +- this is useful for non-serializable data like a utility class like a pubsubs erver or something (TODO extra info) +- link to ephemeral variables docs + +### actions + +- for stateless clients, actions are sent as http requests via `POST /gateway/{actor id}/actions/{action name}` +- for stateful clients, actions are sent as websocket messages + +### events & subscriptions + +- events are sent as websocket messages + +### error handling + +- this is different than fault tolerance: + - error handling is a user error + - fault tolerance is something goes wrong that your applciation was not built to handle (ie hard crash, oom, network error) +- rivet provdies a special UserError class to throw custom errors that will be returned to the client +- all other errors are returned as a generic "internal error" +- this is becuase leaking error deatils is a common security hole, so we default to expose-nothing errors + +### logging + +- rivet uses pino for logging +- we expose a scoped child logger for each actor at `c.log` that automatically logs the actor id + key +- this allows you to search lgos easily by actor id without having to log the actor id frequently +- logs can be configured via the `RIVET_LOG_LEVEL` env var + +### fault tolerance + +- actors are fault tolerant, meaning that the host machine can crash and the actors will proceed to operate as if nothing happened +- runners maintain a socket with rivet engine. when this socket closes or takes to long to ping, actors will reschedule +- hibernating websockets (enabled by default) will live-migrate to the new actor as if nothing happened + +### crash policy + +- there are 3 crash policies: sleep, restart, and destroyed + - sleep (default, usually the option you want): + - when to use: actors that need high-performance in-memory logic. + - when not to use: you need this actor running at all times no matter what, even if idle + - examples: (list commone xamples) + - destroy: + - when to use: actors that need to run once until completion. on crash, do not try to reschedule. + - when not to use: if you want your actor to have fault tolerance and be able to run transaprenlty to the underlying runner + - examples: batch jobs, image conversions, ephemeral jobs, (TODO come up with better eaxmples) + - restart: + - when to use: actors that should be running at all times + - when not to use: if you don't absolutely need something running at all times, since this consumes needless compute resources. considure using the scheduling api instead. + - examples: maintain outbound sockets, daemons, always-running jobs, (TODO come up with better examples) + +the behavior for each is described below: + +| Event | Restart | Sleep | Destroy | +|------------------------------|--------------|--------------|--------------| +| Graceful exit (StopCode::Ok) | Destroy | Destroy | Destroy | +| Crash (non-Ok exit) | Reschedule | Sleep | Destroy | +| Lost (runner disappeared) | Reschedule | Sleep | Destroy | +| Lost + force_reschedule | Reschedule | Reschedule | Reschedule | +| GoingAway (runner draining) | Reschedule | Sleep | Destroy | +| No capacity (allocation) | Queue (wait) | Sleep | Queue (wait) | +| No capacity + serverless | Queue (wait) | Queue (wait) | Queue (wait) | +| Wake signal (while sleeping) | Reschedule | Reschedule | Reschedule | + +### inspector + +- actors provide an inspector api to implement the: + - repl + - state read/write + - network inspector + - event log +- this is impelmented over a websocket over bare + +### http api + +- see the http api document on actors + +### multi-region + +- actors can be scheduled across multiple regions +- each actor has an actor id which embeds which region it lives in +- networking is automatically routed to the region that an actor lives in +- limitation: actors curretnly cannot migrate across regions + +### backpressure + +#### no runner capacity + +- this is how actors with different crash policies behave when when there's backpressure: + - sleep = sleeps (sheds load by not rescheduling) + - restart = queues + - destroy = queues +- see the above matrix for more details on actor crash policy on how it handles no capacity. + +- the actor queue is built to withstand high amounts of backpressure on rivet, so queueing actors is fine here +- a large queue means it'll take more time for your application to process the queue to catch up with demand when it comes online. + +#### per-actor cpu & networking exhaustion + +- actors are isolated, so they each have their own individual bottleneck. you can think of this like a process thread where each thread can only do so much. +- there is no durable message queue/"mailbox" for actors. if the actor cannot respond in time, then the request is dropped. +- if an actor exhauses its cpu or networking, then the runner +- returns service unavailble (503) if the actor fails to respond to a request in time +- there is no hard cap on the networking or cpu usage for each actor at the moment +- if your actor is resource intensive, it's common to use a separate mailbox actor to act as a queue + +## runners + +### regular vs serverless runners + +there are 2 types of runners: + +- regular: these are standard nodejs processes connected to rivet that rivet can orchestrate actors to and send network requests to at any time +- serverless: rivet works with serverless platforms. when an actor is created, it has a request-per-actor model where it opens a long-running request on the serverless platofrm to run a given actor. + +### runner pool + +- runners are pooled together by sharing a common name (ie "default") +- when an actor is created, it chooses the pool by selecting the runner name to run on +- rivet will automatically load balance actors across these runners + +### runner key + +- not relevnat for serverless runners +- each runner has a unique key that it provides when connecting. keys are unique to the instace the runner is running on and should be the same if the runner is restarted. +- this can be the: machine's ip, k8s pod name, etc +- if there is an existing runner connected with a given key, the runner will disconnect the old runner and replace it +- rivet is designed to handle network partitions by waiting for runners to miss a ping, indicating it's no longer alive. however, often times runners restart immediately after a hard crash and reconnect. in this case, the runner will reconnect on restart and terminate the old runner in order to prevent further actors from scheduling to the crashed runner. + +### capacity + +- not relevnat for serverless runners +- each runner can be assigned a capacity of how many actors it can run +- rivet will schedule with spread (not binpacking) in order to spread load over actors + +#### usefulness of capacity = 1 + +- setting a capacity of 1 is helpful for situations where you have cpu-intensive apps that should not run with any other actors +- examples include game servers, ffmpeg jobs, etc + +### versions & upgrading code + +- each runner has a version index +- actors are always scheduled to the highest verison index (see runner priority below) +- this means that when a new runner is deployed: + 1. runners with higher index come online + 2. actors schedule to the highest index, stop scheduling to the older index + 3. old index runners start draining and migrating actors to new index + 4. all old runners are now shut down +- websocekts are live migrated to the new version when upgrading using hibernating websockets to users see no hiccup in their applications +- this is important because actors should never downgrade their runner. they should always move to a newer version of code in order to prevent corruption. + +### runner scheduling prioroty + +- actors are scheduled to runners sorted by priority of (version DESC, remaining capacity ASC) + +### multi-region + +TODO + +### shutdown sequence + +- runner shutdown is important to ensure that actors do not get unexpectedly terminated when either: + - upgrading your applciation and taking down old pods + - scaling down your runners horizontally (ie from an hpa) + - pressing ctrl-c when in development +- on shutdown: + 1. tell rivet the runner is stopping + 2. rivet tells all the actors on this runner to migrate + 3. runner waits for all actors to finish migrating + 4. runner exits process + +### reconnection + +- runners can handle temporary network partitions +- they'll automatically reconnect and replay missed commands/events between rivet and the runner +- this happens transparenlty to the user +- if disconnected for too long (indicating a network partition), the runner will shut itself down and exit + +### autoscaling + +- not relevant to serverless +- runners currently autoscale on cpu. more intelligent scaling is coming soon. +- tune your runner total slots capacity accordingly +- it's up to you to configure your hpa/etc to work like this. see the Connect guides (link to index page) for reference on hwo to configure this. + +### serverless timeouts + +- serverless runners take in to account the maximum run duration of the serverless platform +- the runners will mgirate actors to a new request before the request times out +- this is completely transparent to you and the user because of the fault tolerance and websocket migraiton characteristics +- it's common for actors to go sleep before hitting the serverless timeout + +## networking + +### web standards + +- everything in rivet is built on webstandards by default +- nothing in rivet requires you to use our sdk, our sdks are meant to be a convenience. it's built to be as easy to use raw http/websocket endpoints from scratch. +- actions, events, etc are all built on simple, well-documented http/websocket under the hood (link to openapi & asyncapi docs). +- you can use low-level request handlers (lnk to dock) and low-level weboscket handlers (link to doc) to handle low-level primtivies yourself + +### encoding + +- rivetkit's action/events api supports communicating via [VBARE](link to github repo, see the blog post for the link), CBOR, or JSON + - VBARE: high-perofrmance & compact, optimal use case + - CBOR: descent encoding/decoding perf + portable libraries, good for implemnting high-ish performance on other platforms + - JSON: good for fast implementations & debugging (easy to read) + +### tunneling + +- when a runner connects it opens a tunnel to rivet to allow incoming traffic + - this is simila to systems like tailscale, ngrok, or other vpns + - we do this for security & configuraiton simplicity since it means that you don't have to manage exposing your rivetkit applications' networkig to rivet. instead, anything that can open a socket to rivet can accept inbound traffic to actors. + +### gateway + +- incoming traffic to actors come to the Rivet gateway and are routed to the appropriate runner +- the rivet gateway automatically handles: + - multi-region routing to route traffic to the correct reigon for an actor + - automatically waking the actor if needed + - sending traffic over the runner + +### hibernating websockets + +- hibernating web sockets are a core component of live actor migration & fault tolerance. it allows us to maintain an open websocket while the actor crashes, upgrades, or moves to another runner. +TODO: copy the rest of this from low-level webosckets document and rephrase + +### actor health endpoin + +- actors provide a simple, utility health endpoint at `/health` that lets you check if your actor is reachable (e.g. `curl https://api.rivet.dev/gateway/{actor id}/health`) + +## multi-region + +### networking + +- actors may live in different regions than inbound requests +- Rivet uses the Epoxy (link again) system to handle global routing to route traffic to the correct region with high performance +- this is completely transparent to you. your app sends traffic to https://api.rivet.dev/gateway/* and it automatically routes to the correct actor in the appropriate region + +### globally unique actor keys + +- actor keys are globally unique to be able to benefit from multi-region capabilities without any extra work +- see more about globally uniuqe actor keys above +- see the actor keys document + +### regional endpoints + +- each reigon has a regional endpoint +- this endpoint is used specifically for connecting runners (for example https://api-us-east-1.rivet.dev), opt to use api.rivet.dev for all other traffic +- runners are required to connect to the regional endpoints + - this is because runners are sensitive to latency to the rivet regional datacenter + - we add datacenters regularly so each runner needs to be pinned to a single datacenter in order to ensure your availble datacneter list doesn't change sporadically without your consent + +### persistence + +- data is always persisted in the same region that is written +- this is important for minimal coldstarts & data locality laws + +## namespaces + +- rivet provides namespaces to run multiple actor systems in isolation +- this makes it really easy to have prod/staging environments or completely different applications running on the same rivet instance +- when you connect to rivet, you can specify which namespace you're connecting to +- self-hotsed rivet defaults to namespace "default" +- rivet cloud provdies isolated tokens for each namespace + +## manager api + +- rivet provides a standard rest api for managing actors + - useful endoints include: + - get /actors + - delete /actors/{} + - get /actors/names -> get all actor types available + +## comparison to prior art for actors + +### runtime + +- there are very few serious actor implementation targeted at the javascirpt eocsystem. rivet is arguably the most serious open-source actor implementation for typescript out there. + +### library vs orchestrator + +- some actor systems opt to be purely a library while rivet opts to have an orchestrator (i.e. the single rust binary) +- this lets us to a lot of things other actor systems can't: + - separating orchestration, persistence, and proxy lets us isoalte the core to be incredibly reliable while the fast-changing applications that ocnnect to rivet can be more error-prone safely. with a library, the blast radius of your application also affects the entire actor system. + - support for serverless platforms to benefit from cost, multi-region, blitz scaling, and relibaiblity benefits + - optimize fault tolerance since we can make more assumtions about application state when the rivet core does not crash and your app does + +### scheduling + +actors is a loose term, but there are generally 2 types of schedulign in practice: + +- ephemeral actors + - examples: erlang/otp, akka, swift + - provides no persistence or sleeping mechanism by defualt + - relies on supervisors for managing persistence +- [virtual actors](https://www.microsoft.com/en-us/research/project/orleans-virtual-actors/) + - an extension of the actor pattern that provides actors that can hibernate ("sleep") when not in use + - examples: orleans, dapr, durable objects + +rivet has similarities with both to provide more flexibility: + +- crash policies provdie for 3 types of actors: + - sleep -> most similar to virutal actors + - restart -> most similar to ephemeral actors but with a supervisor to auto-restart, however still has a durable queue ot handle backpressure + - crash -> most similar to traditional actors but with no supervisor to restart, however still has a durable queue to handle backpressure + +### communication + +- many actor frameworks use inbox patterns (think: queue-per-actor) to handle sending messages between actors +- there is no callback mechanims, instead you need to send messages back to the actual actor +- rivet opts to behave like web standards instead of using the message pattern + - actors can impelment the inbox pattern optionally + - but we provide lower-level networking to be able to be compatible with more techniologies + - rivet assumes the same serial concurerntly that other actors do (by the nature of javascript being single-threaded) but we allow you to run promises in parallel or handl eyour own concurrency control (which some other actor frameworks might require a spawning new actor to do) + +_Source doc path: /docs/general/architecture_ diff --git a/.agents/skills/cron-jobs/reference/general/cors.md b/.agents/skills/cron-jobs/reference/general/cors.md new file mode 100644 index 0000000..330fe38 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/general/cors.md @@ -0,0 +1,18 @@ +# Cross-Origin Resource Sharing + +> Source: `src/content/docs/general/cors.mdx` +> Canonical URL: https://rivet.dev/docs/general/cors +> Description: Cross-Origin Resource Sharing (CORS) controls which origins (domains) can access your actors. When actors are exposed to the public internet, proper origin validation is critical to prevent security breaches and denial of service attacks. + +--- +Unlike stateless HTTP APIs that use CORS headers, Rivet Actors are stateful and support persistent WebSocket connections. Since WebSockets don't natively support CORS, we validate origins manually in the `onBeforeConnect` hook before connections may open. + +## Implementing Origin Restrictions + +To implement origin restrictions on Rivet Actors, use the `onBeforeConnect` hook to verify the request. + +To catch the error on the client, use the following code: + + See tracking issue for [configuring CORS per-actor on the gateway](https://github.com/rivet-dev/rivet/issues/3539) that will remove the need to implement origin restrictions in `onBforeRequest`. + +_Source doc path: /docs/general/cors_ diff --git a/.agents/skills/cron-jobs/reference/general/docs-for-llms.md b/.agents/skills/cron-jobs/reference/general/docs-for-llms.md new file mode 100644 index 0000000..db0c216 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/general/docs-for-llms.md @@ -0,0 +1,51 @@ +# Documentation for LLMs & AI + +> Source: `src/content/docs/general/docs-for-llms.mdx` +> Canonical URL: https://rivet.dev/docs/general/docs-for-llms +> Description: Rivet provides optimized documentation formats specifically designed for Large Language Models (LLMs) and AI integration tools. + +--- +## Skills (Recommended) + +For AI coding assistants like Claude Code, Cursor, or Windsurf, install Rivet skills for the best development experience: + +```sh +npx skills add rivet-dev/skills +``` + +Skills provide your AI assistant with Rivet-specific knowledge, best practices, and code patterns directly in your project context. + +## Available Formats + +### `llms.txt` (Condensed) +A condensed version of the documentation perfect for quick reference and context-aware AI assistance. + +**Access:** /llms.txt + +This format includes: +- Key concepts and features +- Essential getting started information +- Summaries of main functionality +- Optimized for token efficiency + +### `llms-full.txt` (Complete) +The complete documentation in a single file, ideal for comprehensive AI assistance and in-depth analysis. + +**Access:** /llms-full.txt + +This format includes: +- Complete documentation content +- All examples and detailed explanations +- Full API references and guides +- Suitable for complex queries and comprehensive understanding + +## Access Pages As Markdown + +Each documentation page is also available as clean markdown by appending `.md` to any documentation URL path. + +For example: + +- Original URL: `https://rivet.dev/docs/actors` +- Markdown URL: `https://rivet.dev/docs/actors.md` + +_Source doc path: /docs/general/docs-for-llms_ diff --git a/.agents/skills/cron-jobs/reference/general/edge.md b/.agents/skills/cron-jobs/reference/general/edge.md new file mode 100644 index 0000000..814dde2 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/general/edge.md @@ -0,0 +1,24 @@ +# Edge Networking + +> Source: `src/content/docs/general/edge.mdx` +> Canonical URL: https://rivet.dev/docs/general/edge +> Description: Actors automatically run near your users on your provider's global network. + +--- +At the moment, edge networking is only supported on Rivet Cloud & Cloudflare Workers. More self-hosted platforms are on the roadmap. + +## Region selection + +### Automatic region selection + +By default, actors will choose the nearest region based on the client's location. + +Under the hood, Rivet and Cloudflare use [Anycast routing](https://en.wikipedia.org/wiki/Anycast) to automatically find the best location for the client to connect to without relying on a slow manual pinging process. + +### Manual region selection + +The region an actor is created in can be overridden using region options: + +See [Create Manage Actors](/docs/actors/communicating-between-actors) for more information. + +_Source doc path: /docs/general/edge_ diff --git a/.agents/skills/cron-jobs/reference/general/endpoints.md b/.agents/skills/cron-jobs/reference/general/endpoints.md new file mode 100644 index 0000000..5c376e1 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/general/endpoints.md @@ -0,0 +1,98 @@ +# Endpoints + +> Source: `src/content/docs/general/endpoints.mdx` +> Canonical URL: https://rivet.dev/docs/general/endpoints +> Description: Configure how your backend connects to Rivet and how clients reach your actors. + +--- +## Local Development + +No configuration is needed for local development. RivetKit runs entirely on your local machine without any extra configuration to run Rivet Actors. + +## Production Deployment + +When deploying to production, you need to configure endpoints so your backend can communicate with Rivet Engine and clients can reach your actors. + +Diagram showing Client connecting to Rivet, which connects to Your Backend + +### Private Endpoint + +The private endpoint tells your backend where to find the Rivet Engine. + +### Environment Variable + +```bash +RIVET_ENDPOINT=https://my-namespace:sk_xxxxx@api.rivet.dev +``` + +### Config + +### Public Endpoint + +The public endpoint tells clients where to connect to reach your actors. + +This endpoint and token will be exposed to the internet. Use a public token (`pk_`), not your secret token (`sk_`). + +The public endpoint is only required if using the [serverless runtime mode](/docs/general/runtime-modes#runners) and if you have a frontend using RivetKit. + +### Environment Variable + +```bash +RIVET_PUBLIC_ENDPOINT=https://my-namespace:pk_xxxxx@api.rivet.dev +``` + +### Config + +## Advanced + +### URL Auth Syntax + +Endpoint URLs support embedding namespace and token directly in the URL: + +``` +https://namespace:token@host/path +``` + +This is the recommended approach for simplicity. Alternatively, you can use separate environment variables: + +```bash +RIVET_ENDPOINT=https://api.rivet.dev +RIVET_NAMESPACE=my-namespace +RIVET_TOKEN=sk_xxxxx +``` + +### Security + +In serverless mode, the private endpoint is used to validate that requests to `GET /api/rivet/start` are coming from your trusted Rivet endpoint. If the private endpoint is not configured, anyone can run a self-hosted instance of Rivet and connect to your backend from any endpoint. + +### How Clients Connect + +This flow applies to [serverless runtime mode](/docs/general/runtime-modes#serverless). For [runner runtime mode](/docs/general/runtime-modes#runners) or [clients configured to connect directly to Rivet](/docs/clients/javascript), clients connect directly to Rivet and this metadata flow is not needed. + +When a client connects to your serverless application, it follows this flow: + +1. Client makes a request to `https://my-app.example.com/api/rivet/metadata` +2. Your app returns the public endpoint configuration: + ```json + { + "clientEndpoint": "https://api.rivet.dev", + "clientNamespace": "my-namespace", + "clientToken": "pk_xxxxx" + } + ``` +3. Client caches these values and uses them for subsequent requests +4. Client connects to `https://api.rivet.dev/gateway/{actor}`, which routes requests to your actors + +This indirection exists because Rivet acts as a gateway between clients and your actors. This is because Rivet handles routing, load balancing, and actor lifecycle management of actors. + +## Reference + +| Environment Variable | Config Option | Description | +|---------------------|---------------|-------------| +| `RIVET_ENDPOINT` | `endpoint` | Rivet Engine URL for your backend | +| `RIVET_NAMESPACE` | `namespace` | Namespace for actor isolation | +| `RIVET_TOKEN` | `token` | Authentication token for engine connection | +| `RIVET_PUBLIC_ENDPOINT` | `serverless.publicEndpoint` | Client-facing endpoint | +| `RIVET_PUBLIC_TOKEN` | `serverless.publicToken` | Client-facing token | + +_Source doc path: /docs/general/endpoints_ diff --git a/.agents/skills/cron-jobs/reference/general/environment-variables.md b/.agents/skills/cron-jobs/reference/general/environment-variables.md new file mode 100644 index 0000000..2a86e98 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/general/environment-variables.md @@ -0,0 +1,87 @@ +# Environment Variables + +> Source: `src/content/docs/general/environment-variables.mdx` +> Canonical URL: https://rivet.dev/docs/general/environment-variables +> Description: This page documents all environment variables that configure RivetKit behavior. + +--- +## Connection + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_ENDPOINT` | Endpoint URL to connect to Rivet Engine. Supports [URL auth syntax](/docs/general/endpoints#url-auth-syntax). | +| `RIVET_TOKEN` | Authentication token for Rivet Engine | +| `RIVET_NAMESPACE` | Namespace to use (default: "default") | + +## Public Endpoint + +These variables configure how clients connect to your actors. + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_PUBLIC_ENDPOINT` | Public endpoint for client connections. Supports [URL auth syntax](/docs/general/endpoints#url-auth-syntax). | +| `RIVET_PUBLIC_TOKEN` | Public token for client authentication | + +## Runner Configuration + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_RUNNER` | Runner name (default: "default") | +| `RIVET_RUNNER_VERSION` | Version number for the runner. See [Versions & Upgrades](/docs/actors/versions). | +| `RIVET_RUNNER_KIND` | Type of runner | +| `RIVET_TOTAL_SLOTS` | Total actor slots available (default: 100000) | + +## Engine + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_RUN_ENGINE` | Set to `1` to spawn the engine process | +| `RIVET_RUN_ENGINE_HOST` | Host to bind the spawned local engine process to. Defaults to `127.0.0.1`. | +| `RIVET_RUN_ENGINE_PORT` | Port to bind the spawned local engine process to. Defaults to `6420`. | +| `RIVET_RUN_ENGINE_VERSION` | Version of engine to download | + +## Inspector + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_INSPECTOR_DISABLE` | Set to `1` to disable the inspector | + +## Metrics + +| Environment Variable | Description | +|---------------------|-------------| +| `_RIVET_METRICS_TOKEN` | Bearer token that gates the per-actor Prometheus `/metrics` endpoint. When unset, `/metrics` is disabled. | + +## Experimental + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_EXPERIMENTAL_OTEL` | Set to `1` to enable experimental OTel tracing in Rivet Actors | + +## Storage + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVETKIT_RUNTIME` | Runtime binding to use for RivetKit core: `auto`, `native`, or `wasm`. Defaults to `auto`. | +| `RIVETKIT_STORAGE_PATH` | Overrides the default file-system storage path used by RivetKit when using the default driver. | + +## Lifecycle + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVETKIT_RUNTIME_MODE` | Controls how `registry.start()` runs. Accepted values are `envoy` and `serverless`; any other explicit value errors. Defaults to `envoy`: opens a long-lived WebSocket to the engine (Mode A). Set to `serverless` to bind an HTTP listener via `registry.listen()` (Mode B). | +| `RIVETKIT_PUBLIC_DIR` | Directory of static assets to serve alongside the framework routes when calling `registry.listen()`. Used as a fallback when `opts.publicDir` is not passed. On auto-listen via `registry.start()`, defaults to `/public` when this env var is unset. | +| `RIVET_PORT` | Port the listener binds when calling `registry.listen()` without an explicit `opts.port`. Must be an integer between 1 and 65535. Defaults to `3000`. | + +## Logging + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_LOG_LEVEL` | Log level: `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `silent` | +| `RIVET_LOG_TARGET` | Set to `1` to include log target | +| `RIVET_LOG_TIMESTAMP` | Set to `1` to include timestamps | +| `RIVET_LOG_MESSAGE` | Set to `1` to include message formatting | +| `RIVET_LOG_ERROR_STACK` | Set to `1` to include error stack traces | +| `RIVET_LOG_HEADERS` | Set to `1` to log request headers | + +_Source doc path: /docs/general/environment-variables_ diff --git a/.agents/skills/cron-jobs/reference/general/http-server.md b/.agents/skills/cron-jobs/reference/general/http-server.md new file mode 100644 index 0000000..c3a386c --- /dev/null +++ b/.agents/skills/cron-jobs/reference/general/http-server.md @@ -0,0 +1,96 @@ +# HTTP Server + +> Source: `src/content/docs/general/http-server.mdx` +> Canonical URL: https://rivet.dev/docs/general/http-server +> Description: Different ways to run your RivetKit HTTP server. + +--- +## Methods of Running Your Server + +### registry.start() + +The simplest way to run your server. Starts a local RivetKit server, serves static files from a `public` directory, and starts the actor runner: + +Run with `npx tsx --watch index.ts` (Node.js), `bun --watch index.ts` (Bun), or `deno run --allow-net --allow-read --allow-env --watch index.ts` (Deno). Clients connect to the Rivet Engine on `http://localhost:6420`. + +### With Fetch Handlers + +A [fetch handler](https://wintercg.org/) is a function that takes a `Request` and returns a `Response`. This is the standard pattern used by Cloudflare Workers, Deno Deploy, Bun, and other modern runtimes. + +Use `registry.serve()` to get a fetch handler: + +To integrate with a router like [Hono](https://hono.dev/) or [Elysia](https://elysiajs.com/), use `registry.handler()`: + +### Hono + +### Elysia + +Then run your server: + +```bash Node.js +npx tsx --watch server.ts +``` + +```bash Bun +bun --watch server.ts +``` + +```bash Deno +deno run --allow-net --allow-read --allow-env --watch server.ts +``` + +### Explicit HTTP Server + +If you need to explicitly start the HTTP server instead of using the fetch handler pattern: + +### Node.js (Hono) + +Using Hono with `@hono/node-server`: + +### Node.js (Adapter) + +Using `@whatwg-node/server` to adapt the fetch handler to Node's HTTP server: + +```ts server.ts @nocheck +import { actor, setup } from "rivetkit"; +import { createServer } from "node:http"; +import { createServerAdapter } from "@whatwg-node/server"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +const handler = createServerAdapter(registry.serve().fetch); +const server = createServer(handler); +server.listen(3000); +``` + +### Bun + +Using Bun's native server: + +```ts server.ts @nocheck +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +Bun.serve({ + port: 3000, + fetch: (request: Request) => registry.handler(request), +}); +``` + +### Deno + +Using Deno's native server: + +```ts server.ts @nocheck +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +Deno.serve({ port: 3000 }, (request: Request) => registry.handler(request)); +``` + +_Source doc path: /docs/general/http-server_ diff --git a/.agents/skills/cron-jobs/reference/general/logging.md b/.agents/skills/cron-jobs/reference/general/logging.md new file mode 100644 index 0000000..f7ce9eb --- /dev/null +++ b/.agents/skills/cron-jobs/reference/general/logging.md @@ -0,0 +1,74 @@ +# Logging + +> Source: `src/content/docs/general/logging.mdx` +> Canonical URL: https://rivet.dev/docs/general/logging +> Description: Actors provide a built-in way to log complex data to the console. + +--- +Using the context's log object (`c.log`) allows you to log complex data using structured logging. + +Using the actor logging API is completely optional. + +## Log levels + +There are 7 log levels: + +| Level | Call | Description | +| ------ | ------------------------------- | ---------------------------------------------------------------- | +| Fatal | `c.log.fatal(message, ...args);` | Critical errors that prevent core functionality | +| Error | `c.log.error(message, ...args);` | Errors that affect functionality but allow continued operation | +| Warn | `c.log.warn(message, ...args);` | Potentially harmful situations that should be addressed | +| Info | `c.log.info(message, ...args);` | General information about significant events & state changes | +| Debug | `c.log.debug(message, ...args);` | Detailed debugging information, usually used in development | +| Trace | `c.log.trace(message, ...args);` | Very detailed debugging information, usually for tracing flow | +| Silent | N/A | Disables all logging output | + +## Structured logging + +The built-in logging API (using `c.log`) provides structured logging to let you log key-value +pairs instead of raw strings. Structured logs are readable by both machines & +humans to make them easier to parse & search. + +When using `c.log`, the actor's name, key, and actor ID are automatically included in every log output. This makes it easy to filter and trace logs by specific actors in production environments. + +### Examples + +The logging system is built on [Pino](https://getpino.io/#/docs/api?id=logger), a high-performance structured logger for Node.js. + +## Configuration + +### Environment Variables + +You can configure logging behavior using environment variables: + +| Variable | Description | Values | Default | +| -------- | ----------- | ------ | ------- | +| `RIVET_LOG_LEVEL` | Sets the minimum log level to display | `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `silent` | `warn` | +| `RIVET_LOG_TARGET` | Include the module name that logged the message | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_TIMESTAMP` | Include timestamp in log output | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_MESSAGE` | Enable detailed message logging for debugging | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_ERROR_STACK` | Include stack traces in error output | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_HEADERS` | Log HTTP headers in requests | `1` to enable, `0` to disable | `0` | + +Example: +```bash +RIVET_LOG_LEVEL=debug RIVET_LOG_TARGET=1 RIVET_LOG_TIMESTAMP=1 node server.js +``` + +### Log Level + +You can configure the log level programmatically when setting up your registry: + +### Custom Pino Logger + +You can also provide a custom Pino base logger for more advanced logging configurations: + +If using a custom base logger, you must manually configure your own log level in the Pino logger. + +For more advanced Pino configuration options, see the [Pino API documentation](https://getpino.io/#/docs/api?id=export). + +### Disable Welcome Message + +You can disable the default RivetKit welcome message with: + +_Source doc path: /docs/general/logging_ diff --git a/.agents/skills/cron-jobs/reference/general/pool-configuration.md b/.agents/skills/cron-jobs/reference/general/pool-configuration.md new file mode 100644 index 0000000..21b00f1 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/general/pool-configuration.md @@ -0,0 +1,119 @@ +# Pool Configuration + +> Source: `src/content/docs/general/pool-configuration.mdx` +> Canonical URL: https://rivet.dev/docs/general/pool-configuration +> Description: Reference for runner pool configuration, including drain behavior, actor eviction rate limiting, and serverless-specific options. + +--- +A **runner pool** is the set of runners Rivet manages for a given runner name within a namespace. The pool configuration controls how runners are scaled, drained on version upgrades, and how quickly actors are evicted from drained runners. + +There are two pool kinds: + +- **`normal`** — runners connect to the engine themselves (for example a long-running process started by you, Docker, or Kubernetes). The engine does not start or stop runners. +- **`serverless`** — the engine calls an HTTP endpoint to wake runners on demand. Used by serverless platforms (Vercel, Cloudflare Workers, Freestyle, etc.). See [Runtime Modes](/docs/general/runtime-modes). + +## Setting the Configuration + +Configure a pool from the [Rivet dashboard](https://dashboard.rivet.dev) under your namespace's runner settings. The dashboard is the recommended way to manage pool configuration. + +You can also set pool configuration directly through the API or the TypeScript SDK: + +```typescript SDK @nocheck +import { RivetClient } from "@rivetkit/engine-api-full"; + +const rivet = new RivetClient({ + environment: "https://api.rivet.dev", + token: process.env.RIVET_TOKEN!, +}); + +await rivet.runnerConfigsUpsert("default", { + namespace: "default", + datacenters: { + default: { + serverless: { + url: "https://my-app.example.com/api/rivet", + requestLifespan: 60 * 15, + actorEvictionDelay: 5, + actorEvictionPeriod: 60, + actorEvictionRate: 1, + }, + }, + }, +}); +``` + +```bash curl +curl -X PUT "https://api.rivet.dev/runner-configs/default?namespace=default" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "datacenters": { + "default": { + "serverless": { + "url": "https://my-app.example.com/api/rivet", + "request_lifespan": 900, + "actor_eviction_delay": 5, + "actor_eviction_period": 60, + "actor_eviction_rate": 1 + } + } + } + }' +``` + +The HTTP API uses `snake_case`. The TypeScript SDK uses `camelCase`. The field names below use `camelCase`. + +## Common Options + +These options apply to both `normal` and `serverless` pools. + +| Option | Type | Default | Description | +|---|---|---|---| +| `drainOnVersionUpgrade` | `bool` | `true` | When a new runner version is deployed, stop old runners and migrate their actors. See [Versions & Upgrades](/docs/actors/versions#drain-on-version-upgrade). | +| `actorEvictionDelay` | `u32` (seconds) | `0` | Delay before actor eviction begins after a drain is triggered. Gives clients time to receive the drain signal before migrations start. | +| `actorEvictionPeriod` | `u32` (seconds) | `0` | Window over which evictions are batched. Used together with `actorEvictionRate` to smooth eviction load on the rest of the pool. | +| `actorEvictionRate` | `f32` (actors/sec) | `1.0` | Maximum number of actors evicted per second once eviction is underway. Set higher for fast cutovers, lower to spread reschedule load. | +| `metadata` | `object` | — | Arbitrary JSON metadata attached to the pool. Useful for tagging and dashboards. | + +### Tuning eviction rate limiting + +Eviction kicks in whenever a runner is drained — most commonly during a version upgrade with `drainOnVersionUpgrade: true`, but also when a runner disconnects ungracefully or is replaced. + +A typical tuning starts from: + +- `actorEvictionDelay: 5` — five-second head start so clients see the drain notification before migrations begin. +- `actorEvictionPeriod: 60` — batch over a one-minute window. +- `actorEvictionRate: 1` — evict one actor per second. + +Increase `actorEvictionRate` for small pools where a full cutover finishes in seconds. Decrease it for large pools to avoid bursts of reschedule traffic. + +## Serverless-Only Options + +These options only apply when `kind: "serverless"`. + +| Option | Type | Default | Description | +|---|---|---|---| +| `url` | `string` | — | HTTP endpoint the engine calls to wake a runner. | +| `headers` | `map` | `{}` | Additional headers sent with the wake request (for example an auth token). | +| `requestLifespan` | `u32` (seconds) | — | Total lifespan of a serverless request before drain begins. Must be shorter than your platform's request timeout. | +| `maxConcurrentActors` | `u64` | `1000` | Soft cap on concurrent actors hosted across the pool. | +| `drainGracePeriod` | `u32` (seconds) | `1800` (30 min) | Time a serverless runner reserves at the end of its lifespan for actors to stop gracefully. | +| `metadataPollInterval` | `u64` (ms) | engine default | How often each runner re-fetches pool metadata to detect new versions. | + +### Deprecated options + +The following options still parse for backwards compatibility but should not be used in new configurations: + +- `slotsPerRunner` +- `minRunners` +- `maxRunners` +- `runnersMargin` + +## Related + +- [Runtime Modes](/docs/general/runtime-modes) — runner vs serverless behavior. +- [Versions & Upgrades](/docs/actors/versions) — how `drainOnVersionUpgrade` interacts with version detection. +- [Limits](/docs/actors/limits) — request lifespan and drain grace period limits. +- [Debugging](/docs/actors/debugging) — inspect a pool configuration via the API. + +_Source doc path: /docs/general/pool-configuration_ diff --git a/.agents/skills/cron-jobs/reference/general/production-checklist.md b/.agents/skills/cron-jobs/reference/general/production-checklist.md new file mode 100644 index 0000000..1ebe257 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/general/production-checklist.md @@ -0,0 +1,98 @@ +# Production Checklist + +> Source: `src/content/docs/general/production-checklist.mdx` +> Canonical URL: https://rivet.dev/docs/general/production-checklist +> Description: Checklist for deploying Rivet Actors to production. + +--- +We recommend passing this page to your coding agent to verify your configuration before deploying. + +## Environment + +- **Set `NODE_ENV=production`.** Ensures optimized performance and disables development-only behavior. +- **Ensure log level is not set to debug.** Leave `RIVET_LOG_LEVEL` at its default or explicitly set it to `warn` to avoid excessive logging. See [Logging](/docs/general/logging). +- **Do not set `RIVET_EXPOSE_ERRORS=1` in production.** This exposes internal error details to clients. It is automatically enabled when `NODE_ENV=development`. See [Errors](/docs/actors/errors). + +## Runtime Mode + +- **Configure a runner version.** Required for graceful upgrades and draining of old actors. Applies to both serverless and runner modes. See [Versions & Upgrades](/docs/actors/versions). + +### Serverless + +- **Check platform timeouts.** Rivet handles migration between invocations automatically, but shorter timeouts increase migration frequency. See [Timeouts](/docs/general/runtime-modes#timeouts). +- **Verify `/api/rivet/start` body size limits.** Serverless actor starts carry actor config and preloaded KV or SQLite startup data in the request body. Keep `serverless.maxStartPayloadBytes` and your platform or proxy body limit at **16 MiB or higher**, or lower the preload budget if your platform cannot accept that size. See [Limits](/docs/actors/limits#kv-preloading). +- **Configure max runners.** Go to Settings > Providers > Edit Provider > Max Runners to set the limit. The default is 100,000 runners. This is effectively your max actor count. +- **Verify your platform rate limit accommodates your actor create and wake frequency.** Actor start requests are sent from Rivet's servers, so they all originate from the same IP. Per-IP rate limits will throttle the engine well before they would throttle real end-user traffic. Size your platform's rate limit to your peak actor create and wake rate, not your end-user request rate. +- **Set the per-instance max concurrent actor limit.** Each serverless instance hosts one actor per in-flight `/api/rivet/start` request, so your platform's per-instance concurrency (e.g. GCP Cloud Run `--concurrency`, AWS Lambda reserved concurrency, Vercel `maxDuration` + concurrency) directly caps actors per instance. Pick a value based on per-actor memory and CPU; the platform autoscales out additional instances once existing ones hit the cap. +- **Tune `requestLifespan` to your platform's hard request timeout.** `requestLifespan` (default `3600`, 60 minutes) is the total lifespan of each serverless request before actors migrate to a fresh instance. Set it just below your platform's hard timeout (e.g. `295` for Vercel Hobby, `3595` for Vercel Pro, `840` for Cloud Run's 15-min cap). Configure via [`configurePool`](/docs/general/registry-configuration). See [Timeouts](/docs/general/runtime-modes#timeouts). +- **Tune `drainGracePeriod` to cover graceful actor shutdown.** Time reserved at the end of `requestLifespan` for actors to stop gracefully before the request is forcibly closed. Default is 30 minutes from the engine; lower it for short-lived stateless actors, raise it if your actors do non-trivial cleanup or final SQLite writes. Configure via [`configurePool`](/docs/general/registry-configuration). See [Limits](/docs/actors/limits). + +### Runner + +- **Set a graceful shutdown period of at least 35 minutes.** Runners need up to 30 minutes to drain actors during upgrades, plus buffer for shutdown overhead. In Kubernetes, set `terminationGracePeriodSeconds: 2100` on the pod spec. + +## Actors + +### Design Patterns + +- **Do not use god actors.** Avoid putting all logic into a single actor type. See [Design Patterns](/docs/actors/design-patterns). +- **Do not use actor-per-request patterns.** Avoid creating a new actor for each request. See [Design Patterns](/docs/actors/design-patterns). + +### Lifecycle + +- **Do not rely on `onSleep` for critical cleanup.** `onSleep` is not called during crashes or forced terminations. See [Lifecycle](/docs/actors/lifecycle). + +### State + +- **Verify `c.state` does not grow unbounded.** Avoid using arrays or objects that grow over time in state. Use [SQLite](/docs/actors/sqlite) for unbounded or append-heavy data instead. +- **Verify actor data does not exceed 10 GB.** Contact [enterprise support](https://rivet.dev/sales) if you need more storage. +- **Use input parameters and `createState` for actor initialization.** See [Input Parameters](/docs/actors/input). + +### Events + +- **Use `conn.send()` instead of `c.broadcast()` for private events.** `c.broadcast()` sends to all connected clients. Use `conn.send()` to send events to a specific connection. See [Realtime](/docs/actors/events). + +### Actions + +- **Review action timeout configuration.** The default `actionTimeout` is 60 seconds. Increase it if you have long-running actions like API calls or file processing. See [Actor Configuration](/docs/general/actor-configuration). +- **Review message size limits.** The default `maxIncomingMessageSize` is 64 KiB and `maxOutgoingMessageSize` is 1 MiB. Increase if your actors send or receive large JSON payloads. See [Registry Configuration](/docs/general/registry-configuration). + +### Queues + +- **Review queue limits.** The default `maxQueueSize` is 1,000 messages and `maxQueueMessageSize` is 64 KiB. Increase if you expect burst traffic or large queue payloads. See [Actor Configuration](/docs/general/actor-configuration). +- **Ensure queue handlers are idempotent.** If processing fails before `message.complete()`, the message will be retried. See [Queues](/docs/actors/queues). + +### Workflows + +- **Verify workflows do not generate infinite steps.** Use `ctx.loop` to avoid creating unbounded step histories. See [Workflows](/docs/actors/workflows). + +## Security + +### Authentication + +- **Validate connections in `createConnState` or `onBeforeConnect`.** Do not trust client input without validation. See [Authentication](/docs/actors/authentication). + +### CORS + +- **Configure CORS for production.** Restrict allowed origins instead of allowing all. See [CORS](/docs/general/cors). + +### Tokens (Rivet Cloud) + +- **Use `pk_*` tokens for `RIVET_PUBLIC_ENDPOINT`.** Public tokens are safe to expose to clients. +- **Use `sk_*` tokens for `RIVET_ENDPOINT`.** Secret tokens should only be used server-side. +- **Do not leak your secret token.** Never expose `sk_*` tokens in client-side code, public repositories, or browser environments. See [Endpoints](/docs/general/endpoints). +- **Verify you're connecting to the correct region.** Use the nearest datacenter endpoint (e.g. `api-us-west-1.rivet.dev`) for lowest latency. + +### Access Control + +Access control is only needed if you want granular permissions for different clients. For most use cases, basic authentication in `onBeforeConnect` or `createConnState` is sufficient. + +- **Use deny-by-default rules.** Reject unknown roles in `onBeforeConnect`, action handlers, `canPublish`, and `canSubscribe`. See [Access Control](/docs/actors/access-control). +- **Authorize actions explicitly.** Check the caller's role in each action handler and throw `forbidden` for unauthorized access. +- **Gate event subscriptions and queue publishes.** Use `canSubscribe` and `canPublish` hooks to restrict which clients can subscribe to events or publish to queues. + +## Clients + +- **Dispose connections and/or client when not in use (JavaScript client).** Call `conn.dispose()` or `client.dispose()` when no longer needed to free resources. React and SwiftUI clients handle this automatically. See [Connection Lifecycle](/docs/clients/javascript#connection-lifecycle). + +_Source doc path: /docs/general/production-checklist_ diff --git a/.agents/skills/cron-jobs/reference/general/registry-configuration.md b/.agents/skills/cron-jobs/reference/general/registry-configuration.md new file mode 100644 index 0000000..3574c4a --- /dev/null +++ b/.agents/skills/cron-jobs/reference/general/registry-configuration.md @@ -0,0 +1,32 @@ +# Registry Configuration + +> Source: `src/content/docs/general/registry-configuration.mdx` +> Canonical URL: https://rivet.dev/docs/general/registry-configuration +> Description: This page documents the configuration options available when setting up a RivetKit registry. The registry configuration is passed to the `setup()` function. + +--- +## Example Configurations + +### Basic Setup + +### Connecting to Rivet Engine + +## Starting Your App + +After configuring your registry, start it: + +See [Runtime Modes](/docs/general/runtime-modes) for details on when to use each mode. + +## Environment Variables + +Many configuration options can be set via environment variables. See [Environment Variables](/docs/general/environment-variables) for a complete reference. + +## Configuration Reference + +## Related + +- [Actor Configuration](/docs/general/actor-configuration): Configure individual actors +- [HTTP Server Setup](/docs/general/http-server): Set up HTTP routing and middleware +- [Architecture](/docs/general/architecture): Understand how RivetKit works + +_Source doc path: /docs/general/registry-configuration_ diff --git a/.agents/skills/cron-jobs/reference/general/runtime-modes.md b/.agents/skills/cron-jobs/reference/general/runtime-modes.md new file mode 100644 index 0000000..43ba986 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/general/runtime-modes.md @@ -0,0 +1,99 @@ +# Runtime Modes + +> Source: `src/content/docs/general/runtime-modes.mdx` +> Canonical URL: https://rivet.dev/docs/general/runtime-modes +> Description: RivetKit supports two runtime modes for running your actors: + +--- +- **Serverless**: Default mode. Responds to HTTP requests and scales automatically. +- **Runners**: Background processes without HTTP endpoints. Only needed for advanced scenarios. + +## Serverless + +Serverless is the default and recommended mode. Rivet sends HTTP requests to your backend to run actor logic, allowing your infrastructure to scale automatically. + +### Benefits + +- **Platform support**: Works with serverless platforms (Vercel, Cloudflare Workers, etc.) +- **Scale to zero**: No cost when idle +- **Edge deployments**: Easier to deploy to edge locations +- **Preview deployments**: Integrates with preview deployments on platforms like Vercel and Railway +- **Efficient autoscaling**: Request-based autoscaling can be faster and more efficient than CPU-based autoscaling depending on the platform + +### Example + +See [Server Setup](/docs/general/http-server/) for more configuration options. + +### Architecture + +When a client creates an actor, it sends a request to the Rivet Engine. The engine then calls `GET /api/rivet/start` on your serverless backend to run the actor. + +Serverless architecture diagram + +### Advanced + +#### Endpoints + +Rivet exposes the following endpoints: + +- `GET /api/rivet/metadata`: Validates configuration +- `GET /api/rivet/start`: Runs an actor + +You should never call these endpoints yourself, this is included purely for comprehension of how Rivet works under the hood. + +#### Timeouts + +Serverless platforms like Vercel have function timeouts. Rivet handles this automatically by migrating actors between function invocations, preserving state through `ctx.state`. Write your code as if it runs forever, Rivet handles the rest. + +Read more about [how we handle timeouts](/blog/2025-10-20-how-we-built-websocket-servers-for-vercel-functions/#timeouts-and-failover). + +#### Shutdown Sequence + +Each serverless request has a configurable lifespan (`requestLifespan`, default: 60 minutes). Set this to match your platform's function timeout (e.g. `requestLifespan: 3600` for Vercel Pro). + +When the request nears its lifespan, the engine reserves a grace period (`serverless_drain_grace_period`, default: 10 seconds) at the end to gracefully stop actors. For example, with a 3600-second lifespan, actors begin stopping at 3590 seconds. After the full lifespan elapses, the connection is forcibly closed and any remaining actors are rescheduled. + +See [Limits](/docs/actors/limits#serverless-shutdown) for configuration details. + +## Runners + +Runners run actors as long-running background processes without exposing an HTTP endpoint. + +### When to Use Runners + +- **No HTTP server**: Your app does not or cannot expose an HTTP server +- **No load balancer**: You don't have a load balancer to distribute HTTP requests across your servers +- **Custom scaling**: You have custom scaling requirements + +### Example + +The runner runs in the background, ready to run actors. + +### Architecture + +On startup, your backend calls `registry.startEnvoy()` which opens a persistent connection to the Rivet Engine. When a client creates an actor, the engine sends a command through this connection to start the actor on your backend. + +Runners architecture diagram + +### Configuration + +#### Runner Pool + +Use `RIVET_RUNNER` to assign runners to a pool. This lets you control which runners handle specific actors. + +```bash +RIVET_RUNNER=gpu-workers +``` + +See [Pool Configuration](/docs/general/pool-configuration) for how pools are scaled, drained on version upgrades, and rate-limited during actor eviction. + +## Comparison + +| Mode | Method | Use Case | +|------|--------|----------| +| Auto | `registry.start()` | Simplest setup. Starts server, serves static files, and runs actors. | +| Serverless | `registry.serve()` | Fetch handler for serverless platforms | +| Serverless | `registry.handler()` | Integrating with existing routers (Hono, Elysia, etc.) | +| Runner | `registry.startEnvoy()` | Long-running processes without HTTP endpoints | + +_Source doc path: /docs/general/runtime-modes_ diff --git a/.agents/skills/cron-jobs/reference/general/wasm-vs-native-sdk.md b/.agents/skills/cron-jobs/reference/general/wasm-vs-native-sdk.md new file mode 100644 index 0000000..18cdd13 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/general/wasm-vs-native-sdk.md @@ -0,0 +1,79 @@ +# WASM vs Native SDK + +> Source: `src/content/docs/general/wasm-vs-native-sdk.mdx` +> Canonical URL: https://rivet.dev/docs/general/wasm-vs-native-sdk +> Description: RivetKit runs your actors on a native or a WebAssembly runtime depending on your platform. + +--- +RivetKit ships two runtimes for executing actor logic. Most projects use the +native runtime automatically. Edge and serverless platforms that cannot run +native binaries use the WebAssembly runtime. + +- **Native**: Default. Runs on Node.js and Bun via native bindings. Best performance. +- **WebAssembly (wasm)**: Runs anywhere a `WebAssembly.Module` can be instantiated, including Cloudflare Workers, Supabase Edge Functions, and Deno Deploy. + +## Native runtime + +The native runtime is the default and requires no configuration. It loads +platform-specific native bindings for the best performance and full feature +support on Node.js and Bun. + +## WebAssembly runtime + +Edge platforms run on isolates (V8, Deno) that cannot load native binaries, so +RivetKit provides a WebAssembly build of its core runtime in the +`@rivetkit/rivetkit-wasm` package. You select it with `runtime: "wasm"` and pass +the wasm bindings and binary through the `wasm` option. + +### Recommended: use a platform package + +For supported platforms, use the dedicated package instead of wiring the wasm +runtime by hand. They install the wasm runtime, load the binary, and (on +Cloudflare) provide the outbound WebSocket the engine tunnel needs. + +- **Cloudflare Workers**: [`@rivetkit/cloudflare-workers`](/docs/actors/quickstart/cloudflare) +- **Supabase Edge Functions**: [`@rivetkit/supabase`](/docs/actors/quickstart/supabase) + +```typescript @nocheck +// Cloudflare Workers +import { actor } from "rivetkit"; +import { createHandler } from "@rivetkit/cloudflare-workers"; + +const counter = actor({ state: { count: 0 }, actions: {} }); + +export default createHandler({ use: { counter } }); +``` + +### Manual configuration + +For platforms without a dedicated package, configure the wasm runtime directly. +Pass the bindings from `@rivetkit/rivetkit-wasm` and the wasm binary as +`initInput`. `initInput` accepts a `Uint8Array`, `URL`, `Response`, or a +`WebAssembly.Module`. + +```typescript @nocheck +import { actor, setup } from "rivetkit"; +import * as wasmBindings from "@rivetkit/rivetkit-wasm"; +import wasmModule from "@rivetkit/rivetkit-wasm/rivetkit_wasm_bg.wasm"; + +const counter = actor({ state: { count: 0 }, actions: {} }); + +const registry = setup({ + runtime: "wasm", + wasm: { bindings: wasmBindings, initInput: wasmModule }, + use: { counter }, +}); +``` + +On platforms without an outbound `new WebSocket(url)` constructor (such as +Cloudflare Workers), you must also install a fetch-based `globalThis.WebSocket` +shim so the actor can open its tunnel to the engine. The platform packages handle +this for you, which is why they are recommended. + +## Related + +- [Runtime Modes](/docs/general/runtime-modes) +- [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) +- [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) + +_Source doc path: /docs/general/wasm-vs-native-sdk_ diff --git a/.agents/skills/cron-jobs/reference/self-hosting/configuration.md b/.agents/skills/cron-jobs/reference/self-hosting/configuration.md new file mode 100644 index 0000000..a71d16e --- /dev/null +++ b/.agents/skills/cron-jobs/reference/self-hosting/configuration.md @@ -0,0 +1,74 @@ +# Configuration + +> Source: `src/content/docs/self-hosting/configuration.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/configuration +> Description: Rivet Engine can be configured through environment variables or configuration files. + +--- +The full JSON Schema for the configuration is available at [/docs/engine-config-schema.json](/docs/engine-config-schema.json). + +## Configuration Sources + +Rivet supports JSON, JSON5, JSONC, YAML, YML, and environment variable configurations. + +**Environment Variables** + +Use the `RIVET__` prefix with `__` as separator to configure properties in the config. For example: set the `RIVET__database__postgres__url` environment variable for `database.postgres.url`. + +**Configuration Paths** + +Configuration files are automatically discovered in platform-specific directories: + +- Linux: `/etc/rivet/config.json` +- macOS: `/Library/Application Support/rivet/config.json` +- Windows: `C:\ProgramData\rivet\config.json` + +**Multiple Files** + +Multiple configuration files in the same directory are loaded and merged together. For example: `/etc/rivet/config.json` and `/etc/rivet/database.json` will be merged together. + +**Override Configuration Path** + +You can override the default configuration path using the `--config` flag: + +```bash +# Load from a specific file +rivet-engine --config /path/to/config.json + +# Load from a directory +rivet-engine --config /etc/rivet + +# Load multiple paths (merged in order) +rivet-engine --config /etc/rivet/base.json --config /etc/rivet/override.json +``` + +## Configuration Reference + +### Pegboard Envoy Load Balancing + +`pegboard.envoy_load_balancer` supports the `hash` strategy for hash-ring-based envoy selection: + +```json +{ + "pegboard": { + "envoy_load_balancer": { + "hash": { + "virtual_nodes": 8, + "samples": 2, + "max_scan": 16, + "use_snapshot_read": true + } + } + } +} +``` + +Use `samples: 1` for a uniform random pick that skips slot reads. Use `samples >= 2` for power-of-K choices over envoy slot counts. Treat `virtual_nodes` as an operational invariant once envoys have registered. + +## Related + +- RivetKit actor runtime persistence lives in SQLite. Existing actor KV data is imported into SQLite the first time an actor wakes on the migrated runtime, then the original KV data is left frozen for downgrade safety. +- [PostgreSQL](/docs/self-hosting/postgres): Configure the experimental PostgreSQL backend +- [File System](/docs/self-hosting/filesystem): Configure file system storage for development + +_Source doc path: /docs/self-hosting/configuration_ diff --git a/.agents/skills/cron-jobs/reference/self-hosting/docker-compose.md b/.agents/skills/cron-jobs/reference/self-hosting/docker-compose.md new file mode 100644 index 0000000..8f2cea1 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/self-hosting/docker-compose.md @@ -0,0 +1,188 @@ +# Docker Compose + +> Source: `src/content/docs/self-hosting/docker-compose.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/docker-compose +> Description: Deploy Rivet Engine with docker-compose for multi-container setups. + +--- +## Quick Start + +### Create docker-compose.yaml + +Create a `docker-compose.yaml` in your project root: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - rivet-data:/data + environment: + RIVET__FILE_SYSTEM__PATH: "/data" + restart: unless-stopped + +volumes: + rivet-data: +``` + +### Start the engine + +```bash +docker-compose up -d +``` + +## Connecting Your Project + +Once the engine is running, add your app as a service in the same Compose file. + +### Create your server + +Follow the [quickstart](/docs/actors/quickstart/backend) to create a working server with actors. + +### Create a Dockerfile + +Create a `Dockerfile` in your project root: + +```dockerfile @nocheck +FROM node:22-slim +WORKDIR /app +COPY package.json pnpm-lock.yaml ./ +RUN corepack enable && pnpm install --frozen-lockfile +COPY . . +RUN pnpm build +CMD ["node", "dist/index.js"] +``` + +### Add your app to docker-compose.yaml + +Update your `docker-compose.yaml` to include your app alongside the engine: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - rivet-data:/data + environment: + RIVET__FILE_SYSTEM__PATH: "/data" + restart: unless-stopped + + my-app: + build: . + environment: + RIVET_ENDPOINT: "http://default:admin@rivet-engine:6420" + depends_on: + - rivet-engine + restart: unless-stopped + +volumes: + rivet-data: +``` + +`RIVET_ENDPOINT` tells your app to connect to the engine as a runner instead of running standalone. The URL uses the format `http://namespace:token@host:port`. Inside the Docker network, your app reaches the engine at `rivet-engine:6420`. See [Endpoints](/docs/general/endpoints) for all options. + +### Start the services + +```bash +docker-compose up -d +``` + +### Register your runner with the engine + +### Dashboard + +1. Open the Rivet Engine dashboard at `http://localhost:6420`. +2. Enter your admin token when prompted. +3. In the namespace sidebar, click **Settings**. +4. Click **Add Provider**, then choose **Custom**. +5. Click **Next** (these settings can be changed later). +6. Click **Next** (you can safely skip the env ar step for Docker Compose). +5. Go to **Confirm Connection**, enter your app endpoint (`http://my-app:6420/api/rivet`), then click **Add**. + +### CLI (curl) + +Register your runner programmatically via the engine API: + +```bash @nocheck +curl -X PUT "http://localhost:6420/runner-configs/default?namespace=default" \ + -H "Content-Type: application/json" \ + -d '{ + "datacenters": { + "default": { + "normal": {} + } + } + }' +``` + +## Configuration + +### Config File + +Mount a JSON configuration file in your `docker-compose.yaml`: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - ./rivet-config.json:/etc/rivet/config.json:ro + - rivet-data:/data + restart: unless-stopped + +volumes: + rivet-data: +``` + +Create `rivet-config.json` in the same directory as your `docker-compose.yaml`. See the [Configuration](/docs/self-hosting/configuration) docs for all available options and the full [JSON Schema](/docs/engine-config-schema.json). + +```json +{ + "postgres": { + "url": "postgresql://rivet:password@postgres:5432/rivet" + } +} +``` + +### Postgres Setup + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +```yaml +services: + postgres: + image: postgres:15 + environment: + POSTGRES_DB: rivet + POSTGRES_USER: rivet + POSTGRES_PASSWORD: rivet_password + volumes: + - postgres-data:/var/lib/postgresql/data + restart: unless-stopped + + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + environment: + RIVET__POSTGRES__URL: postgresql://rivet:rivet_password@postgres:5432/rivet + depends_on: + - postgres + restart: unless-stopped + +volumes: + postgres-data: +``` + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/docker-compose_ diff --git a/.agents/skills/cron-jobs/reference/self-hosting/docker-container.md b/.agents/skills/cron-jobs/reference/self-hosting/docker-container.md new file mode 100644 index 0000000..e6983ae --- /dev/null +++ b/.agents/skills/cron-jobs/reference/self-hosting/docker-container.md @@ -0,0 +1,150 @@ +# Docker Container + +> Source: `src/content/docs/self-hosting/docker-container.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/docker-container +> Description: Run Rivet Engine in a single Docker container. + +--- +## Quick Start + +### Start the engine + +```bash +docker run -d \ + --name rivet-engine \ + -p 6420:6420 \ + -v rivet-data:/data \ + -e RIVET__FILE_SYSTEM__PATH="/data" \ + rivetdev/engine:latest +``` + +### Verify the engine is running + +```bash +curl http://localhost:6420/health +``` + +## Connecting Your Project + +Once the engine is running, connect your app to it. + +### Create your server + +Follow the [quickstart](/docs/actors/quickstart/backend) to create a working server with actors. + +### Start your app with RIVET_ENDPOINT + +Set `RIVET_ENDPOINT` to tell your app to connect to the engine as a runner instead of running standalone: + +```bash @nocheck +RIVET_ENDPOINT="http://default:admin@host.docker.internal:6420" npm start +``` + +If running your app outside of Docker, use `localhost` instead of `host.docker.internal`: + +```bash @nocheck +RIVET_ENDPOINT="http://default:admin@localhost:6420" npm start +``` + +See [Endpoints](/docs/general/endpoints) for all options. + +### Register your runner with the engine + +### Dashboard + +1. Open the Rivet Engine dashboard at `http://localhost:6420`. +2. Enter your admin token when prompted. +3. In the namespace sidebar, click **Settings**. +4. Click **Add Provider**, then choose **Custom**. +5. Click **Next**. +6. Go to **Confirm Connection**, enter your app endpoint, then click **Add**. + +### CLI (curl) + +Register your runner programmatically via the engine API: + +```bash @nocheck +curl -X PUT "http://localhost:6420/runner-configs/default?namespace=default" \ + -H "Content-Type: application/json" \ + -d '{ + "datacenters": { + "default": { + "normal": {} + } + } + }' +``` + +## Configuration + +### Environment Variables + +Configure Rivet using environment variables: + +```bash +docker run -d \ + --name rivet-engine \ + -p 6420:6420 \ + -v rivet-data:/data \ + -e RIVET__FILE_SYSTEM__PATH="/data" \ + -e RIVET__POSTGRES__URL="postgresql://postgres:password@localhost:5432/db" \ + rivetdev/engine:latest +``` + +### Config File + +Mount a JSON configuration file: + +```bash +docker run -d \ + --name rivet-engine \ + -p 6420:6420 \ + -v rivet-data:/data \ + -v $(pwd)/rivet-config.json:/etc/rivet/config.json:ro \ + rivetdev/engine:latest +``` + +Create `rivet-config.json` in your working directory. See the [Configuration](/docs/self-hosting/configuration) docs for all available options and the full [JSON Schema](/docs/engine-config-schema.json). + +```json +{ + "postgres": { + "url": "postgresql://postgres:password@localhost:5432/db" + } +} +``` + +### Postgres Setup + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +```bash +# Create network +docker network create rivet-net + +# Run PostgreSQL +docker run -d \ + --name postgres \ + --network rivet-net \ + -e POSTGRES_DB=rivet \ + -e POSTGRES_USER=rivet \ + -e POSTGRES_PASSWORD=rivet_password \ + -v postgres-data:/var/lib/postgresql/data \ + postgres:15 + +# Run Rivet Engine +docker run -d \ + --name rivet-engine \ + --network rivet-net \ + -p 6420:6420 \ + -e RIVET__POSTGRES__URL="postgresql://rivet:rivet_password@postgres:5432/rivet" \ + rivetdev/engine +``` + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- Use [Docker Compose](/docs/self-hosting/docker-compose) for multi-container setups +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/docker-container_ diff --git a/.agents/skills/cron-jobs/reference/self-hosting/filesystem.md b/.agents/skills/cron-jobs/reference/self-hosting/filesystem.md new file mode 100644 index 0000000..30f7bdb --- /dev/null +++ b/.agents/skills/cron-jobs/reference/self-hosting/filesystem.md @@ -0,0 +1,47 @@ +# File System + +> Source: `src/content/docs/self-hosting/filesystem.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/filesystem +> Description: The file system backend stores all data on the local disk. This is suitable for single-node deployments, development, and testing. + +--- +For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based); for multi-node deployments, PostgreSQL is the recommended backend today but remains experimental as we evaluate the best fit for scalability and performance, and Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB. + +## Configuration + +```json Configuration-file +{ + "database": { + "file_system": { + "path": "/var/lib/rivet/data" + } + } +} +``` + +```bash Environment-variables +RIVET__database__file_system__path="/var/lib/rivet/data" +``` + +## Default Paths + +If no path is specified, Rivet uses platform-specific default locations: + +- Linux: `~/.local/share/rivet-engine/db` +- macOS: `~/Library/Application Support/rivet-engine/db` +- Windows: `%APPDATA%\rivet-engine\db` + +When running in a container or as a service, the path defaults to `./data/db` relative to the working directory. + +## When to Use File System + +The file system backend is ideal for: + +- Local development +- Single-node deployments +- Testing and prototyping +- Air-gapped environments without database infrastructure + +If you need a production-ready Rivet deployment today, use this backend for smaller single-node setups; for multi-node deployments, PostgreSQL is the recommended backend today though still experimental, and Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +_Source doc path: /docs/self-hosting/filesystem_ diff --git a/.agents/skills/cron-jobs/reference/self-hosting/foundationdb.md b/.agents/skills/cron-jobs/reference/self-hosting/foundationdb.md new file mode 100644 index 0000000..b8331bb --- /dev/null +++ b/.agents/skills/cron-jobs/reference/self-hosting/foundationdb.md @@ -0,0 +1,35 @@ +# FoundationDB (Enterprise) + +> Source: `src/content/docs/self-hosting/foundationdb.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/foundationdb +> Description: FoundationDB is the recommended storage backend for scalable production Rivet deployments. + +--- +FoundationDB requires an enterprise license. Contact [enterprise support](https://rivet.dev/sales) for setup guidance and access. + +## Overview + +FoundationDB is the recommended storage backend for scalable, production-ready Rivet deployments. It is a distributed, ordered key-value store originally built by Apple. + +FoundationDB powers some of the largest infrastructure in the world: + +- **Apple**: iCloud and other Apple services +- **Snowflake**: Cloud data platform metadata layer +- **Datadog**: Observability and monitoring platform +- **Tigris Data**: Globally distributed object storage + +Its strict serializability guarantees, fault tolerance, and ability to scale linearly across nodes make it the ideal backend for Rivet's actor state and orchestration layer. + +## Why FoundationDB + +| | RocksDB (File System) | PostgreSQL | FoundationDB | +|---|---|---|---| +| **Scalability** | Single node | Primary/replica failover | Linear horizontal scaling | +| **Fault tolerance** | None | Primary/replica failover | Automatic recovery with no data loss | +| **Production readiness** | Development and small deployments | Experimental for multi-node | Battle-tested at global scale | + +## Getting Started + +FoundationDB configuration and cluster setup are handled as part of enterprise onboarding. Contact [enterprise support](https://rivet.dev/sales) to get started. + +_Source doc path: /docs/self-hosting/foundationdb_ diff --git a/.agents/skills/cron-jobs/reference/self-hosting/install.md b/.agents/skills/cron-jobs/reference/self-hosting/install.md new file mode 100644 index 0000000..344be8e --- /dev/null +++ b/.agents/skills/cron-jobs/reference/self-hosting/install.md @@ -0,0 +1,32 @@ +# Installing Rivet Engine + +> Source: `src/content/docs/self-hosting/install.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/install +> Description: Install Rivet Engine using Docker, binaries, or a source build. + +--- +For more options: + +- [Docker Container](/docs/self-hosting/docker-container) for persistent storage, configuration, and production setups +- [Docker Compose](/docs/self-hosting/docker-compose) for multi-container deployments with PostgreSQL + +## Docker + +```bash +docker run -p 6420:6420 rivetdev/engine +``` + +## Prebuilt Binaries + + Prebuilt binaries coming soon + +## Build From Source + +```bash +git clone https://github.com/rivet-dev/rivet.git +cd rivet +cargo build --release -p rivet-engine +./target/release/rivet-engine +``` + +_Source doc path: /docs/self-hosting/install_ diff --git a/.agents/skills/cron-jobs/reference/self-hosting/kubernetes.md b/.agents/skills/cron-jobs/reference/self-hosting/kubernetes.md new file mode 100644 index 0000000..a2c619c --- /dev/null +++ b/.agents/skills/cron-jobs/reference/self-hosting/kubernetes.md @@ -0,0 +1,236 @@ +# Kubernetes + +> Source: `src/content/docs/self-hosting/kubernetes.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/kubernetes +> Description: Deploy production-ready Rivet Engine to Kubernetes with PostgreSQL storage. + +--- +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Prerequisites + +- Kubernetes cluster +- `kubectl` configured +- [Metrics server](https://github.com/kubernetes-sigs/metrics-server) (required for HPA) — included by default in most distributions (k3d, GKE, EKS, AKS) + +## Deploy Rivet Engine + + +### Download Manifests + + Download the `self-host/k8s/engine` directory from the Rivet repository: + + ```bash + npx giget@latest gh:rivet-dev/rivet/self-host/k8s/engine rivet-k8s + cd rivet-k8s + ``` + + + +### Configure Engine + + In `02-engine-configmap.yaml`, set `public_url` to your engine's external URL. + + + +### Configure PostgreSQL + + In `11-postgres-secret.yaml`, update the PostgreSQL password. See [Using a Managed PostgreSQL Service](#using-a-managed-postgresql-service) for external databases. + + + +### Configure Admin Token + + Generate a secure admin token and save it somewhere safe: + + ```bash + openssl rand -hex 32 + ``` + + Create the namespace and store the token as a Kubernetes secret: + + ```bash + kubectl create namespace rivet-engine + kubectl -n rivet-engine create secret generic rivet-secrets --from-literal=admin-token=YOUR_TOKEN_HERE + ``` + + + +### Deploy + + ```bash + # Apply all manifests + kubectl apply -f . + + # Wait for all pods to be ready + kubectl -n rivet-engine wait --for=condition=ready pod -l app=nats --timeout=300s + kubectl -n rivet-engine wait --for=condition=ready pod -l app=postgres --timeout=300s + kubectl -n rivet-engine wait --for=condition=ready pod -l app=rivet-engine --timeout=300s + + # Verify all pods are running + kubectl -n rivet-engine get pods + ``` + + + +### Access the Engine + + Visit `/ui` on your `public_url` to access the dashboard. + + +## Connecting Your Project + +### Create your server + +Follow the [quickstart](/docs/actors/quickstart/backend) to create a working server with actors. + +### Create Kubernetes manifests + +Create these manifest files for your app: + +```yaml deployment.yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: rivetkit-app + namespace: your-namespace +spec: + replicas: 1 + selector: + matchLabels: + app: rivetkit-app + template: + metadata: + labels: + app: rivetkit-app + spec: + # Allow enough time for actors to gracefully stop on SIGTERM. + # The runner waits up to 30m for actors to finish. + # Add buffer for runner shutdown overhead after actors stop. + # See: /docs/actors/versions#graceful-shutdown-sigterm + terminationGracePeriodSeconds: 2100 + containers: + - name: rivetkit-app + image: registry.example.com/your-team/rivetkit-app:latest + envFrom: + - secretRef: + name: rivetkit-secrets +``` + +```yaml service.yaml +apiVersion: v1 +kind: Service +metadata: + name: rivetkit-app + namespace: your-namespace +spec: + selector: + app: rivetkit-app + ports: + - name: http + port: 8080 + targetPort: 8080 +``` + +### Configure the endpoint + +Create `rivetkit-secrets.yaml` with `RIVET_ENDPOINT` pointing to the engine. This tells your app to connect as a runner instead of running standalone. See [Endpoints](/docs/general/endpoints) for all options. + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: rivetkit-secrets + namespace: your-namespace +type: Opaque +stringData: + RIVET_ENDPOINT: http://my-app:your-admin-token@your-engine.example.com +``` + +### Deploy your app + +```bash +kubectl apply -f rivetkit-secrets.yaml +kubectl apply -f deployment.yaml +kubectl apply -f service.yaml +``` + +### Register your runner with the engine + +### Dashboard + +1. Open the Rivet Engine dashboard in your browser. +2. Enter your admin token when prompted. +3. In the namespace sidebar, click **Settings**. +4. Click **Add Provider**, then choose **Custom**. +5. Click **Next**. +6. Go to **Confirm Connection**, enter your app endpoint (e.g. `http://rivetkit-app.your-namespace:8080/api/rivet`), then click **Add**. + +### CLI (curl) + +Register your runner programmatically via the engine API: + +```bash @nocheck +curl -X PUT "https://your-engine.example.com/runner-configs/default?namespace=default" \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer your-admin-token" \ + -d '{ + "datacenters": { + "default": { + "normal": {} + } + } + }' +``` + +## Advanced + +### Using a Managed PostgreSQL Service + +If you prefer to use a managed PostgreSQL service (e.g. Amazon RDS, Cloud SQL, Azure Database) instead of the bundled Postgres deployment: + +- Update the `postgres.url` connection string in `02-engine-configmap.yaml` to point to your managed instance +- Delete the bundled PostgreSQL manifests: + - `10-postgres-configmap.yaml` + - `11-postgres-secret.yaml` + - `12-postgres-statefulset.yaml` + - `13-postgres-service.yaml` + +### Applying Configuration Updates + +When making subsequent changes to `02-engine-configmap.yaml`, restart the engine pods to pick up the new configuration: + +```bash +kubectl apply -f 02-engine-configmap.yaml +kubectl -n rivet-engine rollout restart deployment/rivet-engine +``` + +### Ingress and Load Balancer Timeouts + +Rivet uses long-lived WebSocket connections for both client traffic (browsers, SDKs) and envoy traffic (actor hosts connecting back to the engine). Default Ingress and cloud load balancer idle timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +Raise the idle / read / send timeout on every Ingress and load balancer in front of the engine to at least 1 hour (`3600` seconds). Examples: + +- **NGINX Ingress** (annotations on the Ingress): + + ```yaml + nginx.ingress.kubernetes.io/proxy-read-timeout: "3600" + nginx.ingress.kubernetes.io/proxy-send-timeout: "3600" + ``` + +- **AWS Load Balancer Controller (ALB)**: + + ```yaml + alb.ingress.kubernetes.io/load-balancer-attributes: idle_timeout.timeout_seconds=3600 + ``` + +- **GCE Ingress (GKE)**: set `timeoutSec: 3600` on the `BackendConfig` referenced by the Service. + +The same guidance applies to the load balancer fronting your RivetKit app, since envoys connect to it over WebSocket. + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all engine config options + +_Source doc path: /docs/self-hosting/kubernetes_ diff --git a/.agents/skills/cron-jobs/reference/self-hosting/multi-region.md b/.agents/skills/cron-jobs/reference/self-hosting/multi-region.md new file mode 100644 index 0000000..2ecca85 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/self-hosting/multi-region.md @@ -0,0 +1,10 @@ +# Multi-Region + +> Source: `src/content/docs/self-hosting/multi-region.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/multi-region +> Description: Rivet Engine supports scaling transparently across multiple regions. + +--- +Documentation coming soon + +_Source doc path: /docs/self-hosting/multi-region_ diff --git a/.agents/skills/cron-jobs/reference/self-hosting/postgres.md b/.agents/skills/cron-jobs/reference/self-hosting/postgres.md new file mode 100644 index 0000000..e935246 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/self-hosting/postgres.md @@ -0,0 +1,192 @@ +# PostgreSQL + +> Source: `src/content/docs/self-hosting/postgres.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/postgres +> Description: Configure PostgreSQL for self-hosted Rivet deployments. + +--- +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Basic Configuration + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://user:password@host:5432/database" + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://user:password@host:5432/database" +``` + +## Managed Postgres Compatibility + +Some hosted PostgreSQL platforms require additional configuration due to platform-specific restrictions. + +### PlanetScale + +Use direct connection (not connection pooler). + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://pscale_api_.:@.pg.psdb.cloud:5432/postgres?sslmode=require", + "unstable_disable_lock_customization": true + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://pscale_api_.:@.pg.psdb.cloud:5432/postgres?sslmode=require" +RIVET__database__postgres__unstable_disable_lock_customization=true +``` + +### Supabase + +Use direct connection on port `5432` (not connection pooler). + +#### Without SSL + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=disable", + "unstable_disable_lock_customization": true + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=disable" +RIVET__database__postgres__unstable_disable_lock_customization=true +``` + +#### With SSL + +Download the root certificate from your Supabase dashboard and specify its path. See [Supabase SSL Enforcement](https://supabase.com/docs/guides/platform/ssl-enforcement) for details. + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=require", + "unstable_disable_lock_customization": true, + "ssl": { + "root_cert_path": "/path/to/supabase-ca.crt" + } + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=require" +RIVET__database__postgres__unstable_disable_lock_customization=true +RIVET__database__postgres__ssl__root_cert_path="/path/to/supabase-ca.crt" +``` + +## SSL/TLS Support + +To enable SSL for Postgres, add `sslmode=require` to your PostgreSQL connection URL: + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://user:password@host.example.com:5432/database?sslmode=require" + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://user:password@host.example.com:5432/database?sslmode=require" +``` + +The `sslmode` parameter controls TLS usage: + +- `disable`: Do not use TLS +- `prefer`: Use TLS if available, otherwise connect without TLS (default) +- `require`: Require TLS connection (fails if TLS is not available) + +To verify the server certificate against a CA or verify the hostname, use custom SSL certificates (see below). + +### Custom SSL Certificates + +For databases using custom certificate authorities (e.g., Supabase) or requiring client certificate authentication, you can specify certificate paths in the configuration: + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://user:password@host:5432/database?sslmode=require", + "ssl": { + "root_cert_path": "/path/to/root-ca.crt", + "client_cert_path": "/path/to/client.crt", + "client_key_path": "/path/to/client.key" + } + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://user:password@host:5432/database?sslmode=require" +RIVET__database__postgres__ssl__root_cert_path="/path/to/root-ca.crt" +RIVET__database__postgres__ssl__client_cert_path="/path/to/client.crt" +RIVET__database__postgres__ssl__client_key_path="/path/to/client.key" +``` + +| Parameter | Description | PostgreSQL Equivalent | +|-----------|-------------|----------------------| +| `root_cert_path` | Path to the root certificate file for verifying the server's certificate | `sslrootcert` | +| `client_cert_path` | Path to the client certificate file for client certificate authentication | `sslcert` | +| `client_key_path` | Path to the client private key file for client certificate authentication | `sslkey` | + +All SSL paths are optional. If not specified, Rivet uses the default system root certificates from Mozilla's root certificate store. + +## Do Not Use Connection Poolers + +Rivet requires direct PostgreSQL connections for session-level features and does not support connection poolers. + +Do not use: + +- PgBouncer +- Supavisor +- AWS RDS Proxy + +## Troubleshooting + +### Permission Denied Errors + +If you see errors like: + +``` +ERROR: permission denied to set parameter "deadlock_timeout" +ERROR: current transaction is aborted, commands ignored until end of transaction block +``` + +Add `unstable_disable_lock_customization: true` to your configuration: + +```json +{ + "database": { + "postgres": { + "url": "postgresql://...", + "unstable_disable_lock_customization": true + } + } +} +``` + +This disables Rivet's attempt to set `lock_timeout = 0` and `deadlock_timeout = 10ms`. Since `lock_timeout` defaults to `0` in PostgreSQL, skipping these settings is safe. Deadlock detection will use the default `1s` timeout instead of `10ms`. + +_Source doc path: /docs/self-hosting/postgres_ diff --git a/.agents/skills/cron-jobs/reference/self-hosting/production-checklist.md b/.agents/skills/cron-jobs/reference/self-hosting/production-checklist.md new file mode 100644 index 0000000..3cefa5a --- /dev/null +++ b/.agents/skills/cron-jobs/reference/self-hosting/production-checklist.md @@ -0,0 +1,53 @@ +# Production Checklist + +> Source: `src/content/docs/self-hosting/production-checklist.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/production-checklist +> Description: Checklist for deploying a self-hosted Rivet Engine to production. + +--- +We recommend passing this page to your coding agent to verify your configuration before deploying. + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +Also review the [general production checklist](/docs/general/production-checklist). + +## Security + +- **Validate that you have an admin token configured.** Generate a strong, random token for engine authentication. See [Configuration](/docs/self-hosting/configuration). +- **Verify your admin token is not exposed publicly.** Do not include the admin token in `RIVET_PUBLIC_ENDPOINT` or anywhere accessible to clients. See [Endpoints](/docs/general/endpoints#public-endpoint). +- **Configure TLS termination.** Ensure connections to the engine are encrypted via a reverse proxy or load balancer. + +## Resources + +- **Set container resource limits.** Recommended at least 1 CPU and 2 GB of RAM per Rivet Engine instance. +- **Configure health checks.** Set up liveness and readiness probes on port `6421` at `/health`. Recommended timeout of 5 seconds. + +## Scaling + +- **Configure autoscaling for the Rivet Engine.** Set target CPU utilization to 70% and memory to 80% to ensure headroom for traffic spikes. In Kubernetes, this is configured via a Horizontal Pod Autoscaler (HPA). +- **Use 2+ engine nodes for redundancy.** Running a single engine node is a single point of failure. Deploy at least two engine instances behind a load balancer. +- **RocksDB only supports a single node.** Do not run multiple RocksDB nodes. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). For multi-node deployments, PostgreSQL is the recommended backend today, though it remains experimental as we evaluate the best fit for scalability and performance. +- **Validate the rate limit on your serverless actor host.** Actor start requests are sent from your engine instances, so they all originate from a small set of IPs. Per-IP rate limits on the actor host will throttle the engine before they would throttle end-user traffic. Size the limit to your peak actor create and wake rate, and configure platform max concurrency (e.g. on GCP Cloud Run) to match your expected concurrent actor count. + +## PostgreSQL + +- **PostgreSQL is recommended for multi-node deployments, but remains experimental.** Validate the deployment carefully before rollout. +- **Configure automated backups.** Set up regular backups for your PostgreSQL database to prevent data loss. +- **Configure failover.** Set up a standby replica with automatic failover to ensure high availability. +- **Use FoundationDB for the most scalable production-ready deployments.** FoundationDB provides the best performance, scalability, and uptime for Rivet. Contact [enterprise support](https://rivet.dev/sales) for FoundationDB guidance. + +## NATS + +- **Use NATS for pub/sub (recommended).** By default, Rivet uses PostgreSQL `LISTEN`/`NOTIFY` for pub/sub which has limited throughput. NATS significantly improves performance for high-traffic deployments. This is not needed if using RocksDB. See [Configuration](/docs/self-hosting/configuration). +- **Deploy 2+ NATS replicas.** Run at least two NATS replicas for high availability. + +## Monitoring + +- **Configure OpenTelemetry.** The Rivet Engine supports exporting traces and metrics via OpenTelemetry. Set `RIVET_OTEL_ENABLED=1` and `RIVET_OTEL_GRPC_ENDPOINT` to your collector endpoint (defaults to `http://localhost:4317`). Adjust `RIVET_OTEL_SAMPLER_RATIO` to control trace sampling (defaults to `0.001`). See [Configuration](/docs/self-hosting/configuration). +- **Set up alerts for critical metrics.** Monitor engine CPU, memory, request latency, and error rates. Configure alerts to notify your team before issues become outages. + +## Enterprise + +- **Contact [enterprise support](https://rivet.dev/sales) for production-ready deployments.** We can help with architecture review, scaling guidance, and FoundationDB support. + +_Source doc path: /docs/self-hosting/production-checklist_ diff --git a/.agents/skills/cron-jobs/reference/self-hosting/railway.md b/.agents/skills/cron-jobs/reference/self-hosting/railway.md new file mode 100644 index 0000000..c4bb922 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/self-hosting/railway.md @@ -0,0 +1,99 @@ +# Railway Deployment + +> Source: `src/content/docs/self-hosting/railway.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/railway +> Description: Railway provides a simple platform for deploying Rivet Engine with automatic scaling and managed infrastructure. + +--- +## Video Tutorial + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Quick Deploy + +Choose the template that best fits your needs: + +| **Rivet Template** | **Rivet Starter** | +|-------------------|-------------------| +| [![Deploy on Railway](https://railway.com/button.svg)](https://railway.com/deploy/rivet?referralCode=RC7bza&utm_medium=integration&utm_source=template&utm_campaign=generic) | [![Deploy Rivet Starter](https://railway.com/button.svg)](https://railway.com/deploy/rivet-starter) | +| **Blank template** to start fresh | **Complete example** with chat app | +| - Rivet Engine | - Pre-configured Rivet Engine | +| - PostgreSQL database | - Example chat application with Actors | +| - Basic configuration | - PostgreSQL database | +| - Manual setup required | - Rivet Inspector for debugging | +| | - Ready to run immediately | + +You can also use the [Rivet Railway template](https://github.com/rivet-dev/template-railway) as a starting point for your application. + +After deploying either template, you can find the `RIVET__AUTH__ADMIN_TOKEN` under the **Variables** tab in the Railway dashboard. This token is required to access the Rivet Inspector. + +## Manual Deployment + +### Prerequisites + +1. [Railway account](https://railway.app) +2. [Railway CLI](https://docs.railway.app/develop/cli) (optional) + +### Step 1: Create New Project + +```bash +# Using Railway CLI +railway init + +# Or create via dashboard +# https://railway.app/new +``` + +### Step 2: Add Services + +#### Deploy PostgreSQL Database + +1. Click "New Service" → "Database" → "PostgreSQL" +2. Railway automatically provisions and configures PostgreSQL +3. Note the connection string from the service variables + +#### Deploy Rivet Engine + +1. Click "New Service" → "Docker Image" +2. Set image: `rivetdev/engine:latest` +3. Configure environment variables: + - `RIVET__POSTGRES__URL=${{Postgres.DATABASE_URL}}` +4. Configure graceful shutdown (see [Graceful Shutdown](#graceful-shutdown) below) + +### Step 3: Deploy Your Application + +Follow the [Railway Quick Start guide](https://docs.railway.com/quick-start) to deploy your repository: + +1. Connect your GitHub account to Railway +2. Select your repository containing your Rivet application +3. Railway will automatically detect and deploy your application +4. Configure environment variables for your application: + - `RIVET_ENDPOINT=${{Rivet.RAILWAY_PRIVATE_DOMAIN}}` - Points to the Rivet Engine service's private domain + +## WebSocket Timeouts + +Rivet uses long-lived WebSocket connections for both client traffic (browsers, SDKs) and envoy traffic (actor hosts connecting back to the engine). Railway's HTTP proxy supports WebSockets, but you must make sure no app-side timeout cuts them off. + +If you front the engine with your own reverse proxy (NGINX, Caddy, etc.) inside the Railway service, raise its idle / read timeout to at least 1 hour (`3600` seconds). The same guidance applies to the Railway service hosting your RivetKit app, since envoys connect to it over WebSocket. + +## Graceful Shutdown + +By default, Railway kills the old deploy 0 seconds after sending `SIGTERM` (see [Railway's docs](https://docs.railway.com/deployments/reference#singleton-deploys)), so in-flight requests are dropped and state flushes can be interrupted on every deploy. Rivet ships with a `SIGTERM` handler that drains cleanly, but it only gets to run if Railway is configured to give it time. + +Configure the following under **Settings → Deploy** on your service: + +- **Draining seconds** — the grace window between `SIGTERM` and `SIGKILL`. This is how long Rivet has to finish in-flight work and flush state. See [Railway's deployment teardown docs](https://docs.railway.com/deployments/deployment-teardown). + +Set draining seconds in the dashboard, via `drainingSeconds` in config-as-code, or via the `RAILWAY_DEPLOYMENT_DRAINING_SECONDS` service variable. A reasonable value is **60 seconds**. + +If your start command is a wrapper process (for example `npm start`, `yarn start`, `pnpm start`, or a shell script), the wrapper becomes PID 1 and swallows the signal — your app never drains and Railway force-kills it at the end of the window. + +- Invoke your binary directly as the start command (for example `node dist/index.js`, not `npm start`). +- Or run `dumb-init` / `tini` as PID 1 in your Dockerfile so signals forward to your process. + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/railway_ diff --git a/.agents/skills/cron-jobs/reference/self-hosting/render.md b/.agents/skills/cron-jobs/reference/self-hosting/render.md new file mode 100644 index 0000000..0bc6d6c --- /dev/null +++ b/.agents/skills/cron-jobs/reference/self-hosting/render.md @@ -0,0 +1,131 @@ +# Render Deployment + +> Source: `src/content/docs/self-hosting/render.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/render +> Description: Deploy Rivet Engine to Render with managed PostgreSQL and automatic HTTPS, using the experimental PostgreSQL backend. + +--- +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Prerequisites + +1. A [Render account](https://render.com) +2. A GitHub repository + +## Deploy Rivet Engine + + +### Create the Blueprint Files + + Add these three files to the root of your GitHub repository: + + **render.yaml** + + ```yaml + databases: + - name: rivet-db + plan: basic-256mb + databaseName: rivet + user: rivet + + services: + - type: web + name: rivet-engine + runtime: docker + dockerfilePath: ./Dockerfile.render + plan: starter + healthCheckPath: /health + envVars: + - key: DATABASE_URL + fromDatabase: + name: rivet-db + property: connectionString + - key: RIVET__AUTH__ADMIN_TOKEN + generateValue: true + ``` + + **Dockerfile.render** + + ```dockerfile + FROM rivetdev/engine:latest + + COPY entrypoint.render.sh /entrypoint.render.sh + RUN chmod +x /entrypoint.render.sh + + ENTRYPOINT ["/entrypoint.render.sh"] + ``` + + **entrypoint.render.sh** + + ```bash + #!/bin/sh + + if [ -n "$DATABASE_URL" ]; then + export RIVET__POSTGRES__URL="${DATABASE_URL}?sslmode=disable" + fi + + exec /usr/bin/rivet-engine start + ``` + + Commit and push these files to your repository. + + + +### Deploy to Render + + 1. Go to the [Render Dashboard](https://dashboard.render.com/) + 2. Click **Blueprints** in the left sidebar + 3. Click **New Blueprint Instance** + 4. Connect your GitHub account if you haven't already + 5. Select the repository containing the files from the previous step + 6. Click **Apply** + + Render will automatically create the PostgreSQL database and deploy the Rivet Engine. + + + +### Get Your Admin Token + + 1. Once deployed, go to your **rivet-engine** service in the Render Dashboard + 2. Click the **Environment** tab + 3. Find `RIVET__AUTH__ADMIN_TOKEN` and click the eye icon to reveal the value + 4. Copy this token — you'll need it to access the dashboard + + + +### Access the Rivet Dashboard + + Open your service URL in a browser: + + ``` + https://rivet-engine-xxxx.onrender.com/ui/ + ``` + + Replace `rivet-engine-xxxx` with your actual service name from the Render Dashboard. + + Enter the admin token from the previous step to log in. + + +## WebSocket Timeouts + +Rivet uses long-lived WebSocket connections for both client traffic (browsers, SDKs) and envoy traffic (actor hosts connecting back to the engine). Render's HTTP proxy supports WebSockets, but its default idle timeout will close connections that have no traffic for too long. + +If you front the engine with your own reverse proxy (NGINX, Caddy, etc.) on Render, raise its idle / read timeout to at least 1 hour (`3600` seconds). The same guidance applies to the Render service hosting your RivetKit app, since envoys connect to it over WebSocket. + +## Connecting Your Application + +To connect a RivetKit application to your self-hosted engine, set these environment variables in your app: + +```bash +RIVET_ENDPOINT=https://:@rivet-engine-xxxx.onrender.com +RIVET_PUBLIC_ENDPOINT=https://@rivet-engine-xxxx.onrender.com +``` + +See the [Connect guide](/docs/deploy/custom) for more details on connecting your application. + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/render_ diff --git a/.agents/skills/cron-jobs/reference/self-hosting/tls.md b/.agents/skills/cron-jobs/reference/self-hosting/tls.md new file mode 100644 index 0000000..63573d2 --- /dev/null +++ b/.agents/skills/cron-jobs/reference/self-hosting/tls.md @@ -0,0 +1,22 @@ +# TLS & Certificates + +> Source: `src/content/docs/self-hosting/tls.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/tls +> Description: How Rivet validates TLS root certificates. + +--- +Public CAs (Let's Encrypt, AWS ACM, and so on) work out of the box. You only need to read this page if you're running behind a corporate or private CA. + +Rivet reads the operating system trust store (`/etc/ssl/certs` on Linux, Keychain on macOS, Schannel on Windows) for all outbound HTTPS. Operator-installed corporate CAs live there and are honored automatically. + +To trust a private CA inside the official `rivetdev/engine` image, extend it the standard Debian way: + +```dockerfile +FROM rivetdev/engine:latest +COPY my-corp-ca.crt /usr/local/share/ca-certificates/ +RUN update-ca-certificates +``` + +Rebuild and redeploy. The same approach works for any machine running a Rivet client: install the CA into the OS trust store and Rivet picks it up. + +_Source doc path: /docs/self-hosting/tls_ diff --git a/.agents/skills/rivetkit-client-javascript/SKILL.md b/.agents/skills/rivetkit-client-javascript/SKILL.md new file mode 100644 index 0000000..9ff21a0 --- /dev/null +++ b/.agents/skills/rivetkit-client-javascript/SKILL.md @@ -0,0 +1,145 @@ +--- +name: "rivetkit-client-javascript" +description: "RivetKit JavaScript client guidance. Use for browser, Node.js, or Bun clients that connect to Rivet Actors with rivetkit/client, create clients, call actions, or manage connections." +--- + +# RivetKit JavaScript Client + +Use this skill when building JavaScript clients (browser, Node.js, or Bun) that connect to Rivet Actors with `rivetkit/client`. + +## First Steps + +1. Install the client (latest: 2.3.4) + ```bash + npm install rivetkit@2.3.4 + ``` +2. Create a client with `createClient()` and call actor actions. + +## Error Handling Policy + +- Prefer fail-fast behavior by default. +- Avoid `try/catch` unless absolutely needed. +- If a `catch` is used, handle the error explicitly, at minimum by logging it. + +## Getting Started + +See the [backend quickstart guide](/docs/actors/quickstart/backend) for getting started. + +## Minimal Client + +## Stateless vs Stateful + +## Getting Actors + +## Connection Parameters + +Use `params` for static connection parameters. Use `getParams` when the value can change between connection attempts, such as refreshing a JWT before each `.connect()` or reconnect. + +## Subscribing to Events + +## Connection Lifecycle + +## Low-Level HTTP & WebSocket + +For actors that implement `onRequest` or `onWebSocket`, call them directly: + +```ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("history"); +const history = await response.json(); + +const ws = await handle.webSocket("stream"); +ws.addEventListener("message", (event) => { + console.log("message:", event.data); +}); +ws.send("hello"); +``` + +## Calling from Backend + +## Error Handling + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`createClient()` automatically reads: + +- `RIVET_ENDPOINT` (endpoint) +- `RIVET_NAMESPACE` +- `RIVET_TOKEN` +- `RIVET_RUNNER` + +Defaults to `http://localhost:6420` when unset. RivetKit runs on port 6420 by default. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, use your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## Advanced + +### Skip Ready Wait + +Requests are normally held at the gateway until the actor is ready to accept traffic. An actor is not ready while it's still starting (before `onWake` finishes) or while it's in the [sleep grace period](/docs/actors/lifecycle#shutdown-sequence) (running `onSleep`, `waitUntil`, and pending disconnects). + +Pass `skipReadyWait: true` on the [low-level HTTP and WebSocket APIs](#low-level-http--websocket) to deliver immediately and reach the actor's `onRequest` / `onWebSocket` handler in either window: + +```ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("/healthz", { + skipReadyWait: true, +}); + +const ws = await handle.webSocket("probe", undefined, { + skipReadyWait: true, +}); +``` + +Requests can still return transient lifecycle or gateway errors. Retry once the actor is available again. + +- `actor.stopping`: the actor has fully stopped, i.e. the sleep grace period has ended but it has not yet restarted. +- `guard.actor_stopped_while_waiting`: the request reached the actor tunnel, but the actor stopped before the gateway received a response. +- `guard.tunnel_request_aborted`: the actor tunnel aborted the request before a response started. +- `guard.tunnel_message_timeout`: the gateway dropped the in-flight tunnel request after its tunnel message timeout. +- `guard.tunnel_response_closed`: the actor tunnel closed before sending a response. +- `guard.gateway_response_start_timeout`: the gateway timed out waiting for the actor response to start. + +## API Reference + +**Package:** [rivetkit](https://www.npmjs.com/package/rivetkit) + +See the [RivetKit client overview](/docs/clients). + +- [`createClient`](/typedoc/functions/rivetkit.client_mod.createClient.html) - Create a client +- [`Client`](/typedoc/types/rivetkit.mod.Client.html) - Client type + +## Need More Than the Client? + +If you need more about Rivet Actors, registries, or server-side RivetKit, add the main skill: + +```bash +npx skills add rivet-dev/skills +``` + +Then use the `rivetkit` skill for backend guidance. + diff --git a/.agents/skills/rivetkit-client-javascript/index.json b/.agents/skills/rivetkit-client-javascript/index.json new file mode 100644 index 0000000..7dada52 --- /dev/null +++ b/.agents/skills/rivetkit-client-javascript/index.json @@ -0,0 +1,7 @@ +{ + "name": "rivetkit-client-javascript", + "description": "RivetKit JavaScript client guidance. Use for browser, Node.js, or Bun clients that connect to Rivet Actors with rivetkit/client, create clients, call actions, or manage connections.", + "skill_url": "/metadata/skills/rivetkit-client-javascript/SKILL.md", + "generated_at": "2026-07-18T12:40:07.476Z", + "references": [] +} \ No newline at end of file diff --git a/.agents/skills/rivetkit-client-react/SKILL.md b/.agents/skills/rivetkit-client-react/SKILL.md new file mode 100644 index 0000000..8390405 --- /dev/null +++ b/.agents/skills/rivetkit-client-react/SKILL.md @@ -0,0 +1,113 @@ +--- +name: "rivetkit-client-react" +description: "RivetKit React client guidance. Use for React apps that connect to Rivet Actors with @rivetkit/react, create hooks with createRivetKit, or manage realtime state with useActor." +--- + +# RivetKit React Client + +Use this skill when building React apps that connect to Rivet Actors with `@rivetkit/react`. + +## First Steps + +1. Install the React client (latest: 2.3.4) + ```bash + npm install @rivetkit/react@2.3.4 + ``` +2. Create hooks with `createRivetKit()` and connect with `useActor()`. + +## Error Handling Policy + +- Prefer fail-fast behavior by default. +- Avoid `try/catch` unless absolutely needed. +- If a `catch` is used, handle the error explicitly, at minimum by logging it. + +## Getting Started + +See the [React quickstart guide](/docs/actors/quickstart/react) for getting started. + +## Install + +## Minimal Client + +## Stateless vs Stateful + +## Getting Actors + +## Connection Parameters + +## Subscribing to Events + +## Connection Lifecycle + +## Low-Level HTTP & WebSocket + +Use the JavaScript client for raw HTTP and WebSocket access: + +```tsx @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("history"); +const history = await response.json(); + +const ws = await handle.webSocket("stream"); +ws.addEventListener("message", (event) => { + console.log("message:", event.data); +}); +ws.send("hello"); +``` + +## Calling from Backend + +Use the JavaScript client on your backend (Node.js/Bun). See the [JavaScript client docs](/docs/clients/javascript). + +## Error Handling + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`createRivetKit()` (and the underlying `createClient()` instance) automatically read: + +- `RIVET_ENDPOINT` +- `RIVET_NAMESPACE` +- `RIVET_TOKEN` +- `RIVET_RUNNER` + +Defaults to `http://localhost:6420` when unset. RivetKit runs on port 6420 by default. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, use your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## API Reference + +**Package:** [@rivetkit/react](https://www.npmjs.com/package/@rivetkit/react) + +- [`createRivetKit`](/docs/clients/react) - Create hooks for React +- [`useActor`](/docs/clients/react) - Hook for actor instances + +## Need More Than the Client? + +If you need more about Rivet Actors, registries, or server-side RivetKit, add the main skill: + +```bash +npx skills add rivet-dev/skills +``` + +Then use the `rivetkit` skill for backend guidance. + diff --git a/.agents/skills/rivetkit-client-react/index.json b/.agents/skills/rivetkit-client-react/index.json new file mode 100644 index 0000000..5f3e686 --- /dev/null +++ b/.agents/skills/rivetkit-client-react/index.json @@ -0,0 +1,7 @@ +{ + "name": "rivetkit-client-react", + "description": "RivetKit React client guidance. Use for React apps that connect to Rivet Actors with @rivetkit/react, create hooks with createRivetKit, or manage realtime state with useActor.", + "skill_url": "/metadata/skills/rivetkit-client-react/SKILL.md", + "generated_at": "2026-07-18T12:40:07.477Z", + "references": [] +} \ No newline at end of file diff --git a/.agents/skills/rivetkit/SKILL.md b/.agents/skills/rivetkit/SKILL.md new file mode 100644 index 0000000..ca710ba --- /dev/null +++ b/.agents/skills/rivetkit/SKILL.md @@ -0,0 +1,537 @@ +--- +name: "rivetkit" +description: "RivetKit backend and Rivet Actor runtime guidance. Use for building, modifying, debugging, or testing Rivet Actors, registries, serverless/runner modes, deployment, or actor-based workflows." +--- + +# Rivet Actors + +Build high-performance, long-lived, in-memory processes on Rivet's actor runtime. Use this skill whenever HTTP endpoints, databases, or queues no longer meet the requirements for AI agents, realtime collaboration, workflow orchestration, or geo-distributed data. + +## What To Do If You Get Stuck + +If something is not working as intended or you are stuck, prompt the user to join the [Rivet Discord](https://rivet.dev/discord) or file an issue on the [Rivet GitHub](https://github.com/rivet-dev/rivet) to report an issue and get help. + +Provide the user with a pre-generated report with: + +- Symptoms + - If this is happening in local dev, deployed, or both + - The error you're seeing + - Relevant source code related to this +- What you've tried to solve it +- Environment + - RivetKit version + - Runtime (Node, Bun, etc) including version + - If applicable, provider in use (e.g. Vercel, Railway, etc) + - If applicable, HTTP router in use (e.g. Hono, Express, Elysia) + +## Debugging Actors + +Use the inspector HTTP API to examine running actors. These endpoints are accessible through the gateway at `/gateway/{actor_id}/inspector/*`. Key endpoints: + +- `GET /inspector/summary` - full actor snapshot (state, connections, RPCs, queue) +- `GET /inspector/state` / `PATCH /inspector/state` - read/write actor state +- `GET /inspector/connections` - active connections +- `GET /inspector/rpcs` - available actions +- `POST /inspector/action/{name}` - execute an action with `{"args": [...]}` +- `POST /inspector/database/execute` - run SQL with `{"sql": "...", "args": [...]}` or `{"sql": "...", "properties": {...}}` for reads or mutations +- `GET /inspector/queue?limit=50` - queue status +- `GET /inspector/traces?startMs=0&endMs=...&limit=1000` - trace spans (OTLP JSON) +- `GET /inspector/workflow-history` - workflow history and status as JSON (`nameRegistry`, `entries`, `entryMetadata`) +- `POST /inspector/workflow/replay` - replay a workflow from a specific step or from the beginning; returns `409 actor/workflow_in_flight` if the workflow is still running +- `GET /inspector/database/schema` - SQLite tables and views exposed by `c.db` +- `GET /inspector/database/rows?table=...&limit=100&offset=0` - paged SQLite rows for a table or view + +In local dev, no auth token is needed. In production, pass `Authorization: Bearer `, where the inspector token is the actor-specific token auto-generated on first start and persisted in the actor's internal KV at key `0x03`. The Rivet dashboard retrieves this token automatically; for direct API access, fetch it through the management KV endpoint. See the [debugging docs](https://rivet.dev/docs/actors/debugging) for details. + +## Citing Sources + +When providing information from Rivet documentation, cite the canonical URL so users can learn more. Each reference file includes its canonical URL in the header metadata. + +**How to cite:** + +- Use inline links for key concepts: "Use [actor keys](https://rivet.dev/docs/actors/keys) to uniquely identify instances." +- Add a "Learn more" link after explanations for complex topics + +**Finding canonical URLs:** + +The Reference Map below links to reference files. Each file's header contains: + +``` +> Canonical URL: https://rivet.dev/docs/actors/actions +``` + +Use that canonical URL when citing, not the reference file path. + +**Examples:** + +- Actions → `https://rivet.dev/docs/actors/actions` +- React client → `https://rivet.dev/docs/clients/react` +- Self-hosting on Kubernetes → `https://rivet.dev/docs/self-hosting/kubernetes` + +## Version Check + +Before starting any work, check if the user's project is on the latest version of RivetKit (latest: 2.3.4). Look at the `rivetkit` version in the user's `package.json` (check both `dependencies` and `devDependencies`). If the installed version is older than 2.3.4, inform the user and suggest upgrading: + +```bash +npm install rivetkit@2.3.4 +``` + +If the user also uses `@rivetkit/react`, `@rivetkit/next-js`, or other `@rivetkit/*` client packages, suggest upgrading those too. Outdated versions may have known bugs or missing features that cause issues. + +## First Steps + +1. Install RivetKit (latest: 2.3.4) + ```bash + npm install rivetkit@2.3.4 + ``` +2. Define a registry with `setup({ use: { /* actors */ } })`. +3. Call `registry.start()` to start the server. For custom HTTP server integration, use `registry.handler()` with a router like Hono. For serverless deployments, use `registry.serve()`. For runner-only mode, use `registry.startEnvoy()`. +4. Verify `/api/rivet/metadata` returns 200 before deploying. +5. Configure Rivet Cloud or self-hosted engine + - You must configure versioning for production builds. This is not needed for local development. See [Versions & Upgrades](https://rivet.dev/docs/actors/versions). +6. Integrate clients (see client guides below for JavaScript, React, or Swift) +7. Prompt the user if they want to deploy. If so, go to Deploying Rivet Backends. + +For more information, read the quickstart guide relevant to the user's project. + +## Project Setup + +### .gitignore + +Every RivetKit project should have a `.gitignore`. Include at minimum: + +``` +node_modules/ +dist/ +.env +``` + +### .dockerignore + +Every project with a Dockerfile should have a `.dockerignore` to keep the image small and avoid leaking secrets: + +``` +node_modules/ +dist/ +.env +.git/ +``` + +### Dockerfile + +Use this as a base Dockerfile for deploying a RivetKit project. The `RIVET_RUNNER_VERSION` build arg is only needed when self-hosting or using a custom runner (not needed for Rivet Compute). It lets Rivet track which version of the actor is running and drain old actors on deploy. See https://rivet.dev/docs/actors/versions for details. + +```dockerfile +FROM node:24-alpine + +ARG RIVET_RUNNER_VERSION +ENV RIVET_RUNNER_VERSION=$RIVET_RUNNER_VERSION + +WORKDIR /app + +COPY package.json package-lock.json ./ +RUN npm ci + +COPY . . +RUN npm run build --if-present + +CMD ["node", "dist/index.js"] +``` + +Build with: + +```bash +docker build --build-arg RIVET_RUNNER_VERSION=$(date +%s) . +``` + +Adjust the `CMD` to match the project's entry point. If the project uses a different output directory or start command, update accordingly. + +## Error Handling Policy + +- Prefer fail-fast behavior by default. +- Avoid `try/catch` unless it is required for a real recovery path, cleanup boundary, or to add actionable context. +- Never swallow errors. If you add a `catch`, you must handle the error explicitly, at minimum by logging it. +- When you cannot recover, log context and rethrow. + +## State vs Vars: Persistence Rules + +**`c.vars` is ephemeral.** Data in `c.vars` is lost on every restart, crash, upgrade, or sleep/wake cycle. Only use `c.vars` for non-serializable objects (e.g., physics engines, WebSocket references, event emitters, caches) or truly transient runtime data (e.g., current input direction that doesn't matter after disconnect). + +**Persistent storage options.** Any data that must survive restarts belongs in one of these, NOT in `c.vars`: + +- **`c.state`** — CBOR-serializable data for small, bounded datasets. Ideal for configuration, counters, small player lists, phase flags, etc. Keep under 128 KB. Do not store unbounded or growing data here (e.g., chat logs, event histories, spawned entity lists that grow without limit). State is read/written as a single blob on every persistence cycle. +- **`c.kv`** — Key-value store for unbounded data. This is what `c.state` uses under the hood. Supports binary values. Use for larger or variable-size data like user inventories, world chunks, file blobs, or any collection that may grow over time. Keys are scoped to the actor instance. +- **`c.db`** — SQLite database for structured or complex data. Use when you need queries, indexes, joins, aggregations, or relational modeling. Ideal for leaderboards, match histories, player pools, or any data that benefits from SQL. + +**Common mistake:** Storing meaningful game/application data in `c.vars` instead of persisting it. For example, if users can spawn objects in a physics simulation, the spawn definitions (position, size, type) must be persisted in `c.state` (or `c.kv` if unbounded), even though the physics engine handles (non-serializable) live in `c.vars`. On restart, `run()` should recreate the runtime objects from the persisted data. + +## Deploying Rivet Backends + +Assume the user is deploying to Rivet Cloud, unless otherwise specified. If user is self-hosting, read the self-hosting guides below. + +1. Verify that Rivet Actors are working in local dev +2. Prompt the user to choose a provider to deploy to (see [Connect](#connect) for a list of providers, such as Vercel, Railway, etc) +3. Follow the deploy guide for that given provider. You will need to instruct the user when you need manual intervention. + +## API Reference + +The RivetKit OpenAPI specification is available in the skill directory at `openapi.json`. This file documents all HTTP endpoints for managing actors. + +## Misc Notes + +- The Rivet domain is rivet.dev, not rivet.gg + +## TypeScript Caveat: Actor Client Inference + +- In multi-file TypeScript projects, bidirectional actor calls can create a circular type dependency when both actors use `c.client()`. +- Symptoms usually include `c.state` becoming `unknown`, actor methods becoming possibly `undefined`, or `TS2322` / `TS2722` errors after the first cross-actor call. +- If an action returns the result of another actor call, prefer an explicit return type annotation on that action instead of relying on inference through `c.client()`. +- If explicit return types are not enough, use a narrower client or registry type for only the actors that action needs. +- As a last resort, pass `unknown` for the registry type and be explicit that this gives up type safety at that call site. + +## Features + +- **Long-Lived, Stateful Compute**: Each unit of compute is like a tiny server that remembers things between requests – no need to re-fetch data from a database or worry about timeouts. Like AWS Lambda, but with memory and no timeouts. +- **Blazing-Fast Reads & Writes**: State is stored on the same machine as your compute, so reads and writes are ultra-fast. No database round trips, no latency spikes. State is persisted to Rivet for long term storage, so it survives server restarts. +- **Realtime**: Update state and broadcast changes in realtime with WebSockets. No external pub/sub systems, no polling – just built-in low-latency events. +- **Infinitely Scalable**: Automatically scale from zero to millions of concurrent actors. Pay only for what you use with instant scaling and no cold starts. +- **Fault Tolerant**: Built-in error handling and recovery. Actors automatically restart on failure while preserving state integrity and continuing operations. + +## When to Use Rivet Actors + +- **AI agents & sandboxes**: multi-step toolchains, conversation memory, sandbox orchestration. +- **Multiplayer or collaborative apps**: CRDT docs, shared cursors, realtime dashboards, chat. +- **Workflow automation**: background jobs, cron, rate limiters, durable queues, backpressure control. +- **Data-intensive backends**: geo-distributed or per-tenant databases, in-memory caches, sharded SQL. +- **Networking workloads**: WebSocket servers, custom protocols, local-first sync, edge fanout. + +## Minimal Project + +### Backend + +**index.ts** + +### Client Docs + +Use the client SDK that matches your app: + +- [JavaScript Client](/docs/clients/javascript) +- [React Client](/docs/clients/react) +- [Swift Client](/docs/clients/swift) + +## Actor Quick Reference + +### In-Memory State + +Persistent data that survives restarts, crashes, and deployments. State is persisted on Rivet Cloud or Rivet self-hosted, so it survives restarts if the current process crashes or exits. + +### Static Initial State + +### Dynamic Initial State + +[Documentation](/docs/actors/state) + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +[Documentation](/docs/actors/keys) + +### Input + +Pass initialization data when creating actors. Input is only available in `createState` and `onCreate`, so store it in state if you need it later. + +[Documentation](/docs/actors/input) + +### Temporary Variables + +Temporary data that doesn't survive restarts. Use for non-serializable objects (event emitters, connections, etc). + +### Static Initial Vars + +### Dynamic Initial Vars + +[Documentation](/docs/actors/state) + +### Actions + +Actions are the primary way clients and other actors communicate with an actor. + +[Documentation](/docs/actors/actions) + +### Events & Broadcasts + +Events enable real-time communication from actors to connected clients. + +[Documentation](/docs/actors/events) + +### Connections + +Access the current connection via `c.conn` or all connected clients via `c.conns`. Use `c.conn.id` or `c.conn.state` to securely identify who is calling an action. `c.conn` is only available for actions invoked through a connected client; stateless actor-handle calls run without a connection, so guard against that. Connection state is initialized via `connState` or `createConnState`, which receives parameters passed by the client on connect. + +### Static Connection Initial State + +### Dynamic Connection Initial State + +[Documentation](/docs/actors/connections) + +### Queues + +Use queues to process durable messages in order inside a `run` loop. + +[Documentation](/docs/actors/queues) + +### Workflows + +Use workflows when your `run` logic needs durable, replayable multi-step execution. + +[Documentation](/docs/actors/workflows) + +### Actor-to-Actor Communication + +Actors can call other actors using `c.client()`. + +[Documentation](/docs/actors/communicating-between-actors) + +### Scheduling + +Schedule actions to run after a delay or at a specific time. Schedules persist across restarts, upgrades, and crashes. + +[Documentation](/docs/actors/schedule) + +### Destroying Actors + +Permanently delete an actor and its state using `c.destroy()`. + +[Documentation](/docs/actors/destroy) + +### Lifecycle Hooks + +Actors support hooks for initialization, background processing, connections, networking, and state changes. Use `run` for long-lived background loops, and use `c.aborted` or `c.abortSignal` for graceful shutdown. + +[Documentation](/docs/actors/lifecycle) + +### Context Types + +When writing helper functions outside the actor definition, use `*ContextOf` to extract the correct context type. Helpers like `ActionContextOf`, `CreateContextOf`, `ConnContextOf`, and `ConnInitContextOf` are exported from `"rivetkit"`. Do not manually define your own context interface. Always derive it from the actor definition. + +[Documentation](/docs/actors/types) + +### Errors + +Use `UserError` to throw errors that are safely returned to clients. Pass `metadata` to include structured data. Other errors are converted to generic "internal error" for security. + +### Actor + +### Client + +[Documentation](/docs/actors/errors) + +### Low-Level HTTP & WebSocket Handlers + +For custom protocols or integrating libraries that need direct access to HTTP `Request`/`Response` or WebSocket connections, use `onRequest` and `onWebSocket`. + +[HTTP Handler Documentation](/docs/actors/request-handler) · [WebSocket Handler Documentation](/docs/actors/websocket-handler) + +### Icons & Names + +Customize how actors appear in the UI with display names and icons. It's recommended to always provide a name and icon to actors in order to make them easier to distinguish in the dashboard. + +```typescript +import { actor } from "rivetkit"; + +const chatRoom = actor({ + options: { + name: "Chat Room", + icon: "💬", // or FontAwesome: "comments", "chart-line", etc. + }, + // ... +}); +``` + +[Documentation](/docs/actors/appearance) + +## Client Documentation + +Find the full client guides here: + +- [JavaScript Client](/docs/clients/javascript) +- [React Client](/docs/clients/react) +- [Swift Client](/docs/clients/swift) + +## Common Patterns + +Actors scale naturally through isolated state and message-passing. Structure your applications with these patterns: + +[Documentation](/docs/actors/design-patterns) + +### Actor Per Entity + +Create one actor per user, document, or room. Use compound keys to scope entities: + +### Coordinator & Data Actors + +**Data actors** handle core logic (chat rooms, game sessions, user data). **Coordinator actors** track and manage collections of data actors—think of them as an index. + +### Run Loop + +Use a `run` loop for continuous background work inside an actor. Process queue messages in order, run logic on intervals, stream AI responses, or coordinate long-running tasks. + +### Workflow Loop + +Use this pattern for long-lived, durable workflows that initialize resources, process commands in a loop, then clean up. + +[Documentation](/docs/actors/workflows) + +### Actions vs Queues + +- **Actions** are not durable. Use them for realtime reads, ephemeral data, and low-latency communication like player input. +- **Queues** are durable. Use them to serialize mutations through the run loop, avoiding race conditions with SQLite and other local state. Callers can still wait for a response from queued work. + +### Authentication, Security, & CORS + +- Validate credentials in `onBeforeConnect` or `createConnState` and throw an error to reject unauthorized connections. +- Use `c.conn.state` to securely identify users in actions rather than trusting action parameters. +- For cross-origin access, validate the request origin in `onBeforeConnect`. + +[Authentication Documentation](/docs/actors/authentication) · [CORS Documentation](/docs/general/cors) + +### Versions & Upgrades + +When deploying new code, set a version number so Rivet can route new actors to the latest runner and optionally drain old ones. Use a build timestamp, git commit count, or CI build number as the version. It is very important to [configure versioning](/docs/actors/versions) before deploying to production. Without versioning, actors can regress by running on older runner versions, and existing actors will never be forced to migrate to new runners. They will continue running indefinitely on the old runners until they exit. + +[Documentation](/docs/actors/versions) + +### Anti-Patterns + +#### Never build a "god" actor + +Do not put all your logic in a single actor. A god actor serializes every operation through one bottleneck, kills parallelism, and makes the entire system fail as a unit. Split into focused actors per entity. + +#### Never create an actor per request + +Actors are long-lived and maintain state across requests. Creating a new actor for every incoming request throws away the core benefit of the model and wastes resources on actor creation and teardown. Use actors for persistent entities and regular functions for stateless work. + +## Reference Map + +### Actors + +- [Access Control](reference/actors/access-control.md) +- [Actions](reference/actors/actions.md) +- [Actor Keys](reference/actors/keys.md) +- [Actor Runtime Socket](reference/actors/actor-runtime-socket.md) +- [Actor Scheduling](reference/actors/schedule.md) +- [Actor Statuses](reference/actors/statuses.md) +- [Authentication](reference/actors/authentication.md) +- [Cloudflare Workers Quickstart](reference/actors/quickstart/cloudflare.md) +- [Communicating Between Actors](reference/actors/communicating-between-actors.md) +- [Connections](reference/actors/connections.md) +- [Custom Inspector Tabs](reference/actors/inspector-tabs.md) +- [Debugging](reference/actors/debugging.md) +- [Design Patterns](reference/actors/design-patterns.md) +- [Destroying Actors](reference/actors/destroy.md) +- [Effect.ts Quickstart (Beta)](reference/actors/quickstart/effect.md) +- [Errors](reference/actors/errors.md) +- [Fetch and WebSocket Handler](reference/actors/fetch-and-websocket-handler.md) +- [Helper Types](reference/actors/helper-types.md) +- [Icons & Names](reference/actors/appearance.md) +- [In-Memory State](reference/actors/state.md) +- [Input Parameters](reference/actors/input.md) +- [Lifecycle](reference/actors/lifecycle.md) +- [Limits](reference/actors/limits.md) +- [Low-Level HTTP Request Handler](reference/actors/request-handler.md) +- [Low-Level KV Storage](reference/actors/kv.md) +- [Low-Level WebSocket Handler](reference/actors/websocket-handler.md) +- [Metadata](reference/actors/metadata.md) +- [Next.js Quickstart](reference/actors/quickstart/next-js.md) +- [Node.js & Bun Quickstart](reference/actors/quickstart/backend.md) +- [Queues & Run Loops](reference/actors/queues.md) +- [React Quickstart](reference/actors/quickstart/react.md) +- [Realtime](reference/actors/events.md) +- [Rust Quickstart (Beta)](reference/actors/quickstart/rust.md) +- [Scaling & Concurrency](reference/actors/scaling.md) +- [Sharing and Joining State](reference/actors/sharing-and-joining-state.md) +- [SQLite](reference/actors/sqlite.md) +- [SQLite + Drizzle](reference/actors/sqlite-drizzle.md) +- [Supabase Functions Quickstart](reference/actors/quickstart/supabase.md) +- [Testing](reference/actors/testing.md) +- [Troubleshooting](reference/actors/troubleshooting.md) +- [Types](reference/actors/types.md) +- [Vanilla HTTP API](reference/actors/http-api.md) +- [Versions & Upgrades](reference/actors/versions.md) +- [Workflows](reference/actors/workflows.md) + +### Cli + +- [CLI](reference/cli.md) + +### Clients + +- [Node.js & Bun](reference/clients/javascript.md) +- [React](reference/clients/react.md) +- [Rust (Beta)](reference/clients/rust.md) +- [Swift](reference/clients/swift.md) +- [SwiftUI](reference/clients/swiftui.md) + +### Cookbook + +- [AI Agent](reference/cookbook/ai-agent.md) +- [Chat Room](reference/cookbook/chat-room.md) +- [Collaborative Text Editor](reference/cookbook/collaborative-text-editor.md) +- [Cron Jobs and Scheduled Tasks](reference/cookbook/cron-jobs.md) +- [Database per Tenant](reference/cookbook/per-tenant-database.md) +- [Deploying Rivet in a VPC or Air-Gapped Network](reference/cookbook/vpc-air-gapped.md) +- [Live Cursors and Presence](reference/cookbook/live-cursors.md) +- [Multiplayer Game](reference/cookbook/multiplayer-game.md) + +### Deploy + +- [Container Runner](reference/deploy/container-runner.md) +- [Deploy To Amazon Web Services Lambda](reference/deploy/aws-lambda.md) +- [Deploying to AWS ECS](reference/deploy/aws-ecs.md) +- [Deploying to Cloudflare Workers](reference/deploy/cloudflare.md) +- [Deploying to Freestyle](reference/deploy/freestyle.md) +- [Deploying to Google Cloud Run](reference/deploy/gcp-cloud-run.md) +- [Deploying to Hetzner](reference/deploy/hetzner.md) +- [Deploying to Kubernetes](reference/deploy/kubernetes.md) +- [Deploying to Railway](reference/deploy/railway.md) +- [Deploying to Rivet Compute](reference/deploy/rivet-compute.md) +- [Deploying to Supabase Functions](reference/deploy/supabase.md) +- [Deploying to Vercel](reference/deploy/vercel.md) +- [Deploying to VMs & Bare Metal](reference/deploy/vm-and-bare-metal.md) + +### General + +- [Actor Configuration](reference/general/actor-configuration.md) +- [Architecture](reference/general/architecture.md) +- [Cross-Origin Resource Sharing](reference/general/cors.md) +- [Documentation for LLMs & AI](reference/general/docs-for-llms.md) +- [Edge Networking](reference/general/edge.md) +- [Endpoints](reference/general/endpoints.md) +- [Environment Variables](reference/general/environment-variables.md) +- [HTTP Server](reference/general/http-server.md) +- [Logging](reference/general/logging.md) +- [Pool Configuration](reference/general/pool-configuration.md) +- [Production Checklist](reference/general/production-checklist.md) +- [Registry Configuration](reference/general/registry-configuration.md) +- [Runtime Modes](reference/general/runtime-modes.md) +- [WASM vs Native SDK](reference/general/wasm-vs-native-sdk.md) + +### Self Hosting + +- [Configuration](reference/self-hosting/configuration.md) +- [Docker Compose](reference/self-hosting/docker-compose.md) +- [Docker Container](reference/self-hosting/docker-container.md) +- [File System](reference/self-hosting/filesystem.md) +- [FoundationDB (Enterprise)](reference/self-hosting/foundationdb.md) +- [Installing Rivet Engine](reference/self-hosting/install.md) +- [Kubernetes](reference/self-hosting/kubernetes.md) +- [Multi-Region](reference/self-hosting/multi-region.md) +- [PostgreSQL](reference/self-hosting/postgres.md) +- [Production Checklist](reference/self-hosting/production-checklist.md) +- [Railway Deployment](reference/self-hosting/railway.md) +- [Render Deployment](reference/self-hosting/render.md) +- [TLS & Certificates](reference/self-hosting/tls.md) + diff --git a/.agents/skills/rivetkit/index.json b/.agents/skills/rivetkit/index.json new file mode 100644 index 0000000..a356fea --- /dev/null +++ b/.agents/skills/rivetkit/index.json @@ -0,0 +1,694 @@ +{ + "name": "rivetkit", + "description": "RivetKit backend and Rivet Actor runtime guidance. Use for building, modifying, debugging, or testing Rivet Actors, registries, serverless/runner modes, deployment, or actor-based workflows.", + "skill_url": "/metadata/skills/rivetkit/SKILL.md", + "generated_at": "2026-07-18T12:40:07.475Z", + "references": [ + { + "name": "actors/access-control", + "title": "Access Control", + "description": "Authorize actions, queue publishes, and event subscriptions with explicit hooks.", + "canonical_url": "https://rivet.dev/docs/actors/access-control", + "reference_url": "/metadata/skills/rivetkit/reference/actors/access-control.md" + }, + { + "name": "actors/actions", + "title": "Actions", + "description": "Actions are how your backend, frontend, or other actors can communicate with actors.", + "canonical_url": "https://rivet.dev/docs/actors/actions", + "reference_url": "/metadata/skills/rivetkit/reference/actors/actions.md" + }, + { + "name": "general/actor-configuration", + "title": "Actor Configuration", + "description": "This page documents the configuration options available when defining a RivetKit actor. The actor configuration is passed to the `actor()` function.", + "canonical_url": "https://rivet.dev/docs/general/actor-configuration", + "reference_url": "/metadata/skills/rivetkit/reference/general/actor-configuration.md" + }, + { + "name": "actors/keys", + "title": "Actor Keys", + "description": "Actor keys uniquely identify actor instances within each actor type. Keys are used for addressing which specific actor to communicate with.", + "canonical_url": "https://rivet.dev/docs/actors/keys", + "reference_url": "/metadata/skills/rivetkit/reference/actors/keys.md" + }, + { + "name": "actors/actor-runtime-socket", + "title": "Actor Runtime Socket", + "description": "Connect trusted local tools to a running Rivet Actor over an experimental actor-local protocol.", + "canonical_url": "https://rivet.dev/docs/actors/actor-runtime-socket", + "reference_url": "/metadata/skills/rivetkit/reference/actors/actor-runtime-socket.md" + }, + { + "name": "actors/schedule", + "title": "Actor Scheduling", + "description": "Schedule actor actions in the future with persistent timers that survive restarts and upgrades.", + "canonical_url": "https://rivet.dev/docs/actors/schedule", + "reference_url": "/metadata/skills/rivetkit/reference/actors/schedule.md" + }, + { + "name": "actors/statuses", + "title": "Actor Statuses", + "description": "Understand the lifecycle statuses of Rivet Actors, what they mean, how they appear in the API, and how to troubleshoot common issues.", + "canonical_url": "https://rivet.dev/docs/actors/statuses", + "reference_url": "/metadata/skills/rivetkit/reference/actors/statuses.md" + }, + { + "name": "cookbook/ai-agent", + "title": "AI Agent", + "description": "Build an AI agent backend with persistent memory: one Rivet Actor per conversation, queued message handling, and streaming LLM responses as realtime events.", + "canonical_url": "https://rivet.dev/cookbook/ai-agent", + "reference_url": "/metadata/skills/rivetkit/reference/cookbook/ai-agent.md" + }, + { + "name": "general/architecture", + "title": "Architecture", + "description": "- rivetkit is the typescript library used for both local development & to connect your application to rivet - a rivetkit instance is called a \"runner.\" you can run multiple runners to scale rivetkit horizontally. read omre about runners below.", + "canonical_url": "https://rivet.dev/docs/general/architecture", + "reference_url": "/metadata/skills/rivetkit/reference/general/architecture.md" + }, + { + "name": "actors/authentication", + "title": "Authentication", + "description": "Secure your actors with authentication and authorization.", + "canonical_url": "https://rivet.dev/docs/actors/authentication", + "reference_url": "/metadata/skills/rivetkit/reference/actors/authentication.md" + }, + { + "name": "cookbook/chat-room", + "title": "Chat Room", + "description": "Build a realtime chat room backend with Rivet Actors: one actor per room, SQLite-backed message history, and WebSocket broadcast to every connected client.", + "canonical_url": "https://rivet.dev/cookbook/chat-room", + "reference_url": "/metadata/skills/rivetkit/reference/cookbook/chat-room.md" + }, + { + "name": "cli", + "title": "CLI", + "description": "Reference for the optional rivet CLI: deploy to Rivet Compute and run local dev for serverless platforms.", + "canonical_url": "https://rivet.dev/docs/cli", + "reference_url": "/metadata/skills/rivetkit/reference/cli.md" + }, + { + "name": "actors/quickstart/cloudflare", + "title": "Cloudflare Workers Quickstart", + "description": "Set up a Rivet project locally targeting Cloudflare Workers.", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/cloudflare", + "reference_url": "/metadata/skills/rivetkit/reference/actors/quickstart/cloudflare.md" + }, + { + "name": "cookbook/collaborative-text-editor", + "title": "Collaborative Text Editor", + "description": "Build a collaborative text editor backend with Yjs CRDTs and Rivet Actors: per-document actors relay sync and awareness updates and persist snapshots.", + "canonical_url": "https://rivet.dev/cookbook/collaborative-text-editor", + "reference_url": "/metadata/skills/rivetkit/reference/cookbook/collaborative-text-editor.md" + }, + { + "name": "actors/communicating-between-actors", + "title": "Communicating Between Actors", + "description": "Learn how actors can call other actors and share data", + "canonical_url": "https://rivet.dev/docs/actors/communicating-between-actors", + "reference_url": "/metadata/skills/rivetkit/reference/actors/communicating-between-actors.md" + }, + { + "name": "self-hosting/configuration", + "title": "Configuration", + "description": "Rivet Engine can be configured through environment variables or configuration files.", + "canonical_url": "https://rivet.dev/docs/self-hosting/configuration", + "reference_url": "/metadata/skills/rivetkit/reference/self-hosting/configuration.md" + }, + { + "name": "actors/connections", + "title": "Connections", + "description": "Connections represent client connections to your actor. They provide a way to handle client authentication, manage connection-specific data, and control the connection lifecycle.", + "canonical_url": "https://rivet.dev/docs/actors/connections", + "reference_url": "/metadata/skills/rivetkit/reference/actors/connections.md" + }, + { + "name": "deploy/container-runner", + "title": "Container Runner", + "description": "Run any containerized server as a Rivet Actor.", + "canonical_url": "https://rivet.dev/docs/deploy/container-runner", + "reference_url": "/metadata/skills/rivetkit/reference/deploy/container-runner.md" + }, + { + "name": "cookbook/cron-jobs", + "title": "Cron Jobs and Scheduled Tasks", + "description": "Durable cron jobs with Rivet Actors: schedule.after and schedule.at timers survive restarts and crashes, plus re-arming recurring jobs and idempotent handlers.", + "canonical_url": "https://rivet.dev/cookbook/cron-jobs", + "reference_url": "/metadata/skills/rivetkit/reference/cookbook/cron-jobs.md" + }, + { + "name": "general/cors", + "title": "Cross-Origin Resource Sharing", + "description": "Cross-Origin Resource Sharing (CORS) controls which origins (domains) can access your actors. When actors are exposed to the public internet, proper origin validation is critical to prevent security breaches and denial of service attacks.", + "canonical_url": "https://rivet.dev/docs/general/cors", + "reference_url": "/metadata/skills/rivetkit/reference/general/cors.md" + }, + { + "name": "actors/inspector-tabs", + "title": "Custom Inspector Tabs", + "description": "Ship your own UI tabs alongside a Rivet Actor — embedded directly in the dashboard inspector.", + "canonical_url": "https://rivet.dev/docs/actors/inspector-tabs", + "reference_url": "/metadata/skills/rivetkit/reference/actors/inspector-tabs.md" + }, + { + "name": "cookbook/per-tenant-database", + "title": "Database per Tenant", + "description": "Multi-tenant data isolation with one Rivet Actor per tenant: the actor key is the tenant id, so each tenant gets its own isolated dataset and migrations.", + "canonical_url": "https://rivet.dev/cookbook/per-tenant-database", + "reference_url": "/metadata/skills/rivetkit/reference/cookbook/per-tenant-database.md" + }, + { + "name": "actors/debugging", + "title": "Debugging", + "description": "Inspect and debug running Rivet Actors, runners, and provider configs using management, runner, and actor inspector HTTP APIs.", + "canonical_url": "https://rivet.dev/docs/actors/debugging", + "reference_url": "/metadata/skills/rivetkit/reference/actors/debugging.md" + }, + { + "name": "deploy/aws-lambda", + "title": "Deploy To Amazon Web Services Lambda", + "description": "_AWS Lambda is coming soon_", + "canonical_url": "https://rivet.dev/docs/deploy/aws-lambda", + "reference_url": "/metadata/skills/rivetkit/reference/deploy/aws-lambda.md" + }, + { + "name": "cookbook/vpc-air-gapped", + "title": "Deploying Rivet in a VPC or Air-Gapped Network", + "description": "Run Rivet entirely inside your own perimeter: single-binary or Docker Compose install, file system storage with no database infrastructure, and no outbound telemetry by default.", + "canonical_url": "https://rivet.dev/cookbook/vpc-air-gapped", + "reference_url": "/metadata/skills/rivetkit/reference/cookbook/vpc-air-gapped.md" + }, + { + "name": "deploy/aws-ecs", + "title": "Deploying to AWS ECS", + "description": "Run your backend on Amazon ECS with Fargate.", + "canonical_url": "https://rivet.dev/docs/deploy/aws-ecs", + "reference_url": "/metadata/skills/rivetkit/reference/deploy/aws-ecs.md" + }, + { + "name": "deploy/cloudflare", + "title": "Deploying to Cloudflare Workers", + "description": "Deploy an existing Rivet project to Cloudflare Workers.", + "canonical_url": "https://rivet.dev/docs/deploy/cloudflare", + "reference_url": "/metadata/skills/rivetkit/reference/deploy/cloudflare.md" + }, + { + "name": "deploy/freestyle", + "title": "Deploying to Freestyle", + "description": "Deploy RivetKit app to Freestyle.sh, a cloud platform for running AI-generated code with built-in security and scalability.", + "canonical_url": "https://rivet.dev/docs/deploy/freestyle", + "reference_url": "/metadata/skills/rivetkit/reference/deploy/freestyle.md" + }, + { + "name": "deploy/gcp-cloud-run", + "title": "Deploying to Google Cloud Run", + "description": "Deploy your RivetKit app to Google Cloud Run.", + "canonical_url": "https://rivet.dev/docs/deploy/gcp-cloud-run", + "reference_url": "/metadata/skills/rivetkit/reference/deploy/gcp-cloud-run.md" + }, + { + "name": "deploy/hetzner", + "title": "Deploying to Hetzner", + "description": "Please see the VM & Bare Metal guide.", + "canonical_url": "https://rivet.dev/docs/deploy/hetzner", + "reference_url": "/metadata/skills/rivetkit/reference/deploy/hetzner.md" + }, + { + "name": "deploy/kubernetes", + "title": "Deploying to Kubernetes", + "description": "Deploy your RivetKit app to any Kubernetes cluster.", + "canonical_url": "https://rivet.dev/docs/deploy/kubernetes", + "reference_url": "/metadata/skills/rivetkit/reference/deploy/kubernetes.md" + }, + { + "name": "deploy/railway", + "title": "Deploying to Railway", + "description": "Deploy your RivetKit app to Railway.", + "canonical_url": "https://rivet.dev/docs/deploy/railway", + "reference_url": "/metadata/skills/rivetkit/reference/deploy/railway.md" + }, + { + "name": "deploy/rivet-compute", + "title": "Deploying to Rivet Compute", + "description": "Run your backend on Rivet Compute.", + "canonical_url": "https://rivet.dev/docs/deploy/rivet-compute", + "reference_url": "/metadata/skills/rivetkit/reference/deploy/rivet-compute.md" + }, + { + "name": "deploy/supabase", + "title": "Deploying to Supabase Functions", + "description": "Deploy an existing Rivet project to Supabase Edge Functions.", + "canonical_url": "https://rivet.dev/docs/deploy/supabase", + "reference_url": "/metadata/skills/rivetkit/reference/deploy/supabase.md" + }, + { + "name": "deploy/vercel", + "title": "Deploying to Vercel", + "description": "Deploy your Next.js Rivet app to Vercel.", + "canonical_url": "https://rivet.dev/docs/deploy/vercel", + "reference_url": "/metadata/skills/rivetkit/reference/deploy/vercel.md" + }, + { + "name": "deploy/vm-and-bare-metal", + "title": "Deploying to VMs & Bare Metal", + "description": "Deploy your RivetKit app to any Linux VM or bare metal host.", + "canonical_url": "https://rivet.dev/docs/deploy/vm-and-bare-metal", + "reference_url": "/metadata/skills/rivetkit/reference/deploy/vm-and-bare-metal.md" + }, + { + "name": "actors/design-patterns", + "title": "Design Patterns", + "description": "Common patterns and anti-patterns for building scalable actor systems.", + "canonical_url": "https://rivet.dev/docs/actors/design-patterns", + "reference_url": "/metadata/skills/rivetkit/reference/actors/design-patterns.md" + }, + { + "name": "actors/destroy", + "title": "Destroying Actors", + "description": "Actors can be permanently destroyed. Common use cases include:", + "canonical_url": "https://rivet.dev/docs/actors/destroy", + "reference_url": "/metadata/skills/rivetkit/reference/actors/destroy.md" + }, + { + "name": "self-hosting/docker-compose", + "title": "Docker Compose", + "description": "Deploy Rivet Engine with docker-compose for multi-container setups.", + "canonical_url": "https://rivet.dev/docs/self-hosting/docker-compose", + "reference_url": "/metadata/skills/rivetkit/reference/self-hosting/docker-compose.md" + }, + { + "name": "self-hosting/docker-container", + "title": "Docker Container", + "description": "Run Rivet Engine in a single Docker container.", + "canonical_url": "https://rivet.dev/docs/self-hosting/docker-container", + "reference_url": "/metadata/skills/rivetkit/reference/self-hosting/docker-container.md" + }, + { + "name": "general/docs-for-llms", + "title": "Documentation for LLMs & AI", + "description": "Rivet provides optimized documentation formats specifically designed for Large Language Models (LLMs) and AI integration tools.", + "canonical_url": "https://rivet.dev/docs/general/docs-for-llms", + "reference_url": "/metadata/skills/rivetkit/reference/general/docs-for-llms.md" + }, + { + "name": "general/edge", + "title": "Edge Networking", + "description": "Actors automatically run near your users on your provider's global network.", + "canonical_url": "https://rivet.dev/docs/general/edge", + "reference_url": "/metadata/skills/rivetkit/reference/general/edge.md" + }, + { + "name": "actors/quickstart/effect", + "title": "Effect.ts Quickstart (Beta)", + "description": "Build a Rivet Actor with the Effect SDK", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/effect", + "reference_url": "/metadata/skills/rivetkit/reference/actors/quickstart/effect.md" + }, + { + "name": "general/endpoints", + "title": "Endpoints", + "description": "Configure how your backend connects to Rivet and how clients reach your actors.", + "canonical_url": "https://rivet.dev/docs/general/endpoints", + "reference_url": "/metadata/skills/rivetkit/reference/general/endpoints.md" + }, + { + "name": "general/environment-variables", + "title": "Environment Variables", + "description": "This page documents all environment variables that configure RivetKit behavior.", + "canonical_url": "https://rivet.dev/docs/general/environment-variables", + "reference_url": "/metadata/skills/rivetkit/reference/general/environment-variables.md" + }, + { + "name": "actors/errors", + "title": "Errors", + "description": "Rivet provides robust error handling with security built in by default. Errors are handled differently based on whether they should be exposed to clients or kept private.", + "canonical_url": "https://rivet.dev/docs/actors/errors", + "reference_url": "/metadata/skills/rivetkit/reference/actors/errors.md" + }, + { + "name": "actors/fetch-and-websocket-handler", + "title": "Fetch and WebSocket Handler", + "description": "These docs have moved to [Low-Level WebSocket Handler](/docs/actors/websocket-handler) and [Low-Level Request Handler](/docs/actors/request-handler).", + "canonical_url": "https://rivet.dev/docs/actors/fetch-and-websocket-handler", + "reference_url": "/metadata/skills/rivetkit/reference/actors/fetch-and-websocket-handler.md" + }, + { + "name": "self-hosting/filesystem", + "title": "File System", + "description": "The file system backend stores all data on the local disk. This is suitable for single-node deployments, development, and testing.", + "canonical_url": "https://rivet.dev/docs/self-hosting/filesystem", + "reference_url": "/metadata/skills/rivetkit/reference/self-hosting/filesystem.md" + }, + { + "name": "self-hosting/foundationdb", + "title": "FoundationDB (Enterprise)", + "description": "FoundationDB is the recommended storage backend for scalable production Rivet deployments.", + "canonical_url": "https://rivet.dev/docs/self-hosting/foundationdb", + "reference_url": "/metadata/skills/rivetkit/reference/self-hosting/foundationdb.md" + }, + { + "name": "actors/helper-types", + "title": "Helper Types", + "description": "This page has moved to [Types](/docs/actors/types).", + "canonical_url": "https://rivet.dev/docs/actors/helper-types", + "reference_url": "/metadata/skills/rivetkit/reference/actors/helper-types.md" + }, + { + "name": "general/http-server", + "title": "HTTP Server", + "description": "Different ways to run your RivetKit HTTP server.", + "canonical_url": "https://rivet.dev/docs/general/http-server", + "reference_url": "/metadata/skills/rivetkit/reference/general/http-server.md" + }, + { + "name": "actors/appearance", + "title": "Icons & Names", + "description": "Customize actors with display names and icons for the Rivet inspector and dashboard.", + "canonical_url": "https://rivet.dev/docs/actors/appearance", + "reference_url": "/metadata/skills/rivetkit/reference/actors/appearance.md" + }, + { + "name": "actors/state", + "title": "In-Memory State", + "description": "Actors store state in memory for instant reads and writes. State can be persisted automatically or kept ephemeral.", + "canonical_url": "https://rivet.dev/docs/actors/state", + "reference_url": "/metadata/skills/rivetkit/reference/actors/state.md" + }, + { + "name": "actors/input", + "title": "Input Parameters", + "description": "Pass initialization data to actors when creating instances", + "canonical_url": "https://rivet.dev/docs/actors/input", + "reference_url": "/metadata/skills/rivetkit/reference/actors/input.md" + }, + { + "name": "self-hosting/install", + "title": "Installing Rivet Engine", + "description": "Install Rivet Engine using Docker, binaries, or a source build.", + "canonical_url": "https://rivet.dev/docs/self-hosting/install", + "reference_url": "/metadata/skills/rivetkit/reference/self-hosting/install.md" + }, + { + "name": "self-hosting/kubernetes", + "title": "Kubernetes", + "description": "Deploy production-ready Rivet Engine to Kubernetes with PostgreSQL storage.", + "canonical_url": "https://rivet.dev/docs/self-hosting/kubernetes", + "reference_url": "/metadata/skills/rivetkit/reference/self-hosting/kubernetes.md" + }, + { + "name": "actors/lifecycle", + "title": "Lifecycle", + "description": "Learn about actor lifecycle hooks for initialization, state management, and cleanup.", + "canonical_url": "https://rivet.dev/docs/actors/lifecycle", + "reference_url": "/metadata/skills/rivetkit/reference/actors/lifecycle.md" + }, + { + "name": "actors/limits", + "title": "Limits", + "description": "Limits and constraints for Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/actors/limits", + "reference_url": "/metadata/skills/rivetkit/reference/actors/limits.md" + }, + { + "name": "cookbook/live-cursors", + "title": "Live Cursors and Presence", + "description": "Live cursors and multiplayer presence with Rivet Actors: per-connection cursor state, realtime updates over events or raw WebSockets, and throttling.", + "canonical_url": "https://rivet.dev/cookbook/live-cursors", + "reference_url": "/metadata/skills/rivetkit/reference/cookbook/live-cursors.md" + }, + { + "name": "general/logging", + "title": "Logging", + "description": "Actors provide a built-in way to log complex data to the console.", + "canonical_url": "https://rivet.dev/docs/general/logging", + "reference_url": "/metadata/skills/rivetkit/reference/general/logging.md" + }, + { + "name": "actors/request-handler", + "title": "Low-Level HTTP Request Handler", + "description": "Actors can handle HTTP requests through the `onRequest` handler.", + "canonical_url": "https://rivet.dev/docs/actors/request-handler", + "reference_url": "/metadata/skills/rivetkit/reference/actors/request-handler.md" + }, + { + "name": "actors/kv", + "title": "Low-Level KV Storage", + "description": "Use the built-in key-value store on ActorContext for durable string and binary data alongside actor state.", + "canonical_url": "https://rivet.dev/docs/actors/kv", + "reference_url": "/metadata/skills/rivetkit/reference/actors/kv.md" + }, + { + "name": "actors/websocket-handler", + "title": "Low-Level WebSocket Handler", + "description": "Actors can handle WebSocket connections through the `onWebSocket` handler.", + "canonical_url": "https://rivet.dev/docs/actors/websocket-handler", + "reference_url": "/metadata/skills/rivetkit/reference/actors/websocket-handler.md" + }, + { + "name": "actors/metadata", + "title": "Metadata", + "description": "Metadata provides information about the currently running actor.", + "canonical_url": "https://rivet.dev/docs/actors/metadata", + "reference_url": "/metadata/skills/rivetkit/reference/actors/metadata.md" + }, + { + "name": "self-hosting/multi-region", + "title": "Multi-Region", + "description": "Rivet Engine supports scaling transparently across multiple regions.", + "canonical_url": "https://rivet.dev/docs/self-hosting/multi-region", + "reference_url": "/metadata/skills/rivetkit/reference/self-hosting/multi-region.md" + }, + { + "name": "cookbook/multiplayer-game", + "title": "Multiplayer Game", + "description": "Pragmatic patterns for building multiplayer games: matchmaking, tick loops, realtime state, interest management, and validation.", + "canonical_url": "https://rivet.dev/cookbook/multiplayer-game", + "reference_url": "/metadata/skills/rivetkit/reference/cookbook/multiplayer-game.md" + }, + { + "name": "actors/quickstart/next-js", + "title": "Next.js Quickstart", + "description": "Get started with Rivet Actors in Next.js", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/next-js", + "reference_url": "/metadata/skills/rivetkit/reference/actors/quickstart/next-js.md" + }, + { + "name": "clients/javascript", + "title": "Node.js & Bun", + "description": "Connect JavaScript apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/javascript", + "reference_url": "/metadata/skills/rivetkit/reference/clients/javascript.md" + }, + { + "name": "actors/quickstart/backend", + "title": "Node.js & Bun Quickstart", + "description": "Get started with Rivet Actors in Node.js and Bun", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/backend", + "reference_url": "/metadata/skills/rivetkit/reference/actors/quickstart/backend.md" + }, + { + "name": "general/pool-configuration", + "title": "Pool Configuration", + "description": "Reference for runner pool configuration, including drain behavior, actor eviction rate limiting, and serverless-specific options.", + "canonical_url": "https://rivet.dev/docs/general/pool-configuration", + "reference_url": "/metadata/skills/rivetkit/reference/general/pool-configuration.md" + }, + { + "name": "self-hosting/postgres", + "title": "PostgreSQL", + "description": "Configure PostgreSQL for self-hosted Rivet deployments.", + "canonical_url": "https://rivet.dev/docs/self-hosting/postgres", + "reference_url": "/metadata/skills/rivetkit/reference/self-hosting/postgres.md" + }, + { + "name": "general/production-checklist", + "title": "Production Checklist", + "description": "Checklist for deploying Rivet Actors to production.", + "canonical_url": "https://rivet.dev/docs/general/production-checklist", + "reference_url": "/metadata/skills/rivetkit/reference/general/production-checklist.md" + }, + { + "name": "self-hosting/production-checklist", + "title": "Production Checklist", + "description": "Checklist for deploying a self-hosted Rivet Engine to production.", + "canonical_url": "https://rivet.dev/docs/self-hosting/production-checklist", + "reference_url": "/metadata/skills/rivetkit/reference/self-hosting/production-checklist.md" + }, + { + "name": "actors/queues", + "title": "Queues & Run Loops", + "description": "Use actor-local durable queues for serial run loops and request/response workflows.", + "canonical_url": "https://rivet.dev/docs/actors/queues", + "reference_url": "/metadata/skills/rivetkit/reference/actors/queues.md" + }, + { + "name": "self-hosting/railway", + "title": "Railway Deployment", + "description": "Railway provides a simple platform for deploying Rivet Engine with automatic scaling and managed infrastructure.", + "canonical_url": "https://rivet.dev/docs/self-hosting/railway", + "reference_url": "/metadata/skills/rivetkit/reference/self-hosting/railway.md" + }, + { + "name": "clients/react", + "title": "React", + "description": "Connect React apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/react", + "reference_url": "/metadata/skills/rivetkit/reference/clients/react.md" + }, + { + "name": "actors/quickstart/react", + "title": "React Quickstart", + "description": "Build realtime React applications with Rivet Actors", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/react", + "reference_url": "/metadata/skills/rivetkit/reference/actors/quickstart/react.md" + }, + { + "name": "actors/events", + "title": "Realtime", + "description": "Events enable realtime communication from actors to clients. While clients use actions to send data to actors, events allow actors to push updates to connected clients instantly.", + "canonical_url": "https://rivet.dev/docs/actors/events", + "reference_url": "/metadata/skills/rivetkit/reference/actors/events.md" + }, + { + "name": "general/registry-configuration", + "title": "Registry Configuration", + "description": "This page documents the configuration options available when setting up a RivetKit registry. The registry configuration is passed to the `setup()` function.", + "canonical_url": "https://rivet.dev/docs/general/registry-configuration", + "reference_url": "/metadata/skills/rivetkit/reference/general/registry-configuration.md" + }, + { + "name": "self-hosting/render", + "title": "Render Deployment", + "description": "Deploy Rivet Engine to Render with managed PostgreSQL and automatic HTTPS, using the experimental PostgreSQL backend.", + "canonical_url": "https://rivet.dev/docs/self-hosting/render", + "reference_url": "/metadata/skills/rivetkit/reference/self-hosting/render.md" + }, + { + "name": "general/runtime-modes", + "title": "Runtime Modes", + "description": "RivetKit supports two runtime modes for running your actors:", + "canonical_url": "https://rivet.dev/docs/general/runtime-modes", + "reference_url": "/metadata/skills/rivetkit/reference/general/runtime-modes.md" + }, + { + "name": "clients/rust", + "title": "Rust (Beta)", + "description": "Connect Rust apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/rust", + "reference_url": "/metadata/skills/rivetkit/reference/clients/rust.md" + }, + { + "name": "actors/quickstart/rust", + "title": "Rust Quickstart (Beta)", + "description": "Build a Rivet Actor in Rust", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/rust", + "reference_url": "/metadata/skills/rivetkit/reference/actors/quickstart/rust.md" + }, + { + "name": "actors/scaling", + "title": "Scaling & Concurrency", + "description": "This page has moved to [design patterns](/docs/actors/design-patterns).", + "canonical_url": "https://rivet.dev/docs/actors/scaling", + "reference_url": "/metadata/skills/rivetkit/reference/actors/scaling.md" + }, + { + "name": "actors/sharing-and-joining-state", + "title": "Sharing and Joining State", + "description": "This page has moved to [design patterns](/docs/actors/design-patterns).", + "canonical_url": "https://rivet.dev/docs/actors/sharing-and-joining-state", + "reference_url": "/metadata/skills/rivetkit/reference/actors/sharing-and-joining-state.md" + }, + { + "name": "actors/sqlite", + "title": "SQLite", + "description": "Use embedded SQLite in Rivet Actors with raw SQL queries.", + "canonical_url": "https://rivet.dev/docs/actors/sqlite", + "reference_url": "/metadata/skills/rivetkit/reference/actors/sqlite.md" + }, + { + "name": "actors/sqlite-drizzle", + "title": "SQLite + Drizzle", + "description": "Use Drizzle ORM with embedded SQLite in Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/actors/sqlite-drizzle", + "reference_url": "/metadata/skills/rivetkit/reference/actors/sqlite-drizzle.md" + }, + { + "name": "actors/quickstart/supabase", + "title": "Supabase Functions Quickstart", + "description": "Set up a Rivet project locally targeting Supabase Edge Functions.", + "canonical_url": "https://rivet.dev/docs/actors/quickstart/supabase", + "reference_url": "/metadata/skills/rivetkit/reference/actors/quickstart/supabase.md" + }, + { + "name": "clients/swift", + "title": "Swift", + "description": "Connect Swift apps to Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/swift", + "reference_url": "/metadata/skills/rivetkit/reference/clients/swift.md" + }, + { + "name": "clients/swiftui", + "title": "SwiftUI", + "description": "Build SwiftUI apps with Rivet Actors.", + "canonical_url": "https://rivet.dev/docs/clients/swiftui", + "reference_url": "/metadata/skills/rivetkit/reference/clients/swiftui.md" + }, + { + "name": "actors/testing", + "title": "Testing", + "description": "Rivet provides a straightforward testing framework to build reliable and maintainable applications. This guide covers how to write effective tests for your actor-based services.", + "canonical_url": "https://rivet.dev/docs/actors/testing", + "reference_url": "/metadata/skills/rivetkit/reference/actors/testing.md" + }, + { + "name": "self-hosting/tls", + "title": "TLS & Certificates", + "description": "How Rivet validates TLS root certificates.", + "canonical_url": "https://rivet.dev/docs/self-hosting/tls", + "reference_url": "/metadata/skills/rivetkit/reference/self-hosting/tls.md" + }, + { + "name": "actors/troubleshooting", + "title": "Troubleshooting", + "description": "Common issues with Rivet Actors and how to resolve them.", + "canonical_url": "https://rivet.dev/docs/actors/troubleshooting", + "reference_url": "/metadata/skills/rivetkit/reference/actors/troubleshooting.md" + }, + { + "name": "actors/types", + "title": "Types", + "description": "TypeScript types for working with Rivet Actors. This page covers context types used in lifecycle hooks and actions, as well as helper types for extracting types from actor definitions.", + "canonical_url": "https://rivet.dev/docs/actors/types", + "reference_url": "/metadata/skills/rivetkit/reference/actors/types.md" + }, + { + "name": "actors/http-api", + "title": "Vanilla HTTP API", + "description": "Use the low-level HTTP handler to send and receive requests from actors.", + "canonical_url": "https://rivet.dev/docs/actors/http-api", + "reference_url": "/metadata/skills/rivetkit/reference/actors/http-api.md" + }, + { + "name": "actors/versions", + "title": "Versions & Upgrades", + "description": "When you deploy new code, Rivet ensures actors are upgraded seamlessly without downtime.", + "canonical_url": "https://rivet.dev/docs/actors/versions", + "reference_url": "/metadata/skills/rivetkit/reference/actors/versions.md" + }, + { + "name": "general/wasm-vs-native-sdk", + "title": "WASM vs Native SDK", + "description": "RivetKit runs your actors on a native or a WebAssembly runtime depending on your platform.", + "canonical_url": "https://rivet.dev/docs/general/wasm-vs-native-sdk", + "reference_url": "/metadata/skills/rivetkit/reference/general/wasm-vs-native-sdk.md" + }, + { + "name": "actors/workflows", + "title": "Workflows", + "description": "Build durable, replayable run loops in Rivet Actors with steps, queue waits, timers, and rollback.", + "canonical_url": "https://rivet.dev/docs/actors/workflows", + "reference_url": "/metadata/skills/rivetkit/reference/actors/workflows.md" + } + ] +} \ No newline at end of file diff --git a/.agents/skills/rivetkit/openapi.json b/.agents/skills/rivetkit/openapi.json new file mode 100644 index 0000000..ca482f7 --- /dev/null +++ b/.agents/skills/rivetkit/openapi.json @@ -0,0 +1,1311 @@ +{ + "openapi": "3.0.0", + "info": { + "version": "2.2.0", + "title": "RivetKit API" + }, + "components": { + "schemas": {}, + "parameters": {} + }, + "paths": { + "/actors": { + "get": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": false, + "name": "name", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "actor_ids", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "key", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "actors": { + "type": "array", + "items": { + "type": "object", + "properties": { + "actor_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "namespace_id": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "create_ts": { + "type": "number" + }, + "connectable_ts": { + "type": "number", + "nullable": true + }, + "destroy_ts": { + "type": "number", + "nullable": true + }, + "sleep_ts": { + "type": "number", + "nullable": true + }, + "start_ts": { + "type": "number", + "nullable": true + }, + "error": { + "nullable": true + } + }, + "required": [ + "actor_id", + "name", + "key", + "namespace_id", + "runner_name_selector", + "create_ts" + ] + } + } + }, + "required": [ + "actors" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + }, + "put": { + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "datacenter": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "crash_policy": { + "type": "string" + }, + "input": { + "type": "string", + "nullable": true + } + }, + "required": [ + "name", + "key", + "runner_name_selector", + "crash_policy" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "actor": { + "type": "object", + "properties": { + "actor_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "namespace_id": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "create_ts": { + "type": "number" + }, + "connectable_ts": { + "type": "number", + "nullable": true + }, + "destroy_ts": { + "type": "number", + "nullable": true + }, + "sleep_ts": { + "type": "number", + "nullable": true + }, + "start_ts": { + "type": "number", + "nullable": true + }, + "error": { + "nullable": true + } + }, + "required": [ + "actor_id", + "name", + "key", + "namespace_id", + "runner_name_selector", + "create_ts" + ] + }, + "created": { + "type": "boolean" + } + }, + "required": [ + "actor", + "created" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + }, + "post": { + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "datacenter": { + "type": "string" + }, + "name": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "crash_policy": { + "type": "string" + }, + "key": { + "type": "string", + "nullable": true + }, + "input": { + "type": "string", + "nullable": true + } + }, + "required": [ + "name", + "runner_name_selector", + "crash_policy" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "actor": { + "type": "object", + "properties": { + "actor_id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "key": { + "type": "string" + }, + "namespace_id": { + "type": "string" + }, + "runner_name_selector": { + "type": "string" + }, + "create_ts": { + "type": "number" + }, + "connectable_ts": { + "type": "number", + "nullable": true + }, + "destroy_ts": { + "type": "number", + "nullable": true + }, + "sleep_ts": { + "type": "number", + "nullable": true + }, + "start_ts": { + "type": "number", + "nullable": true + }, + "error": { + "nullable": true + } + }, + "required": [ + "actor_id", + "name", + "key", + "namespace_id", + "runner_name_selector", + "create_ts" + ] + } + }, + "required": [ + "actor" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/actors/names": { + "get": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "namespace", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "names": { + "type": "object", + "additionalProperties": { + "type": "object", + "properties": { + "metadata": { + "type": "object", + "additionalProperties": { + "nullable": true + } + } + }, + "required": [ + "metadata" + ] + } + } + }, + "required": [ + "names" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/actors/{actor_id}/kv/keys/{key}": { + "get": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "actor_id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "key", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "value": { + "type": "string", + "nullable": true + } + }, + "required": [ + "value" + ] + } + } + } + }, + "400": { + "description": "User error" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/gateway/{actorId}/health": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + } + ], + "responses": { + "200": { + "description": "Health check", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + } + } + } + }, + "/gateway/{actorId}/action/{action}": { + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "action", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The name of the action to execute" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "args": {} + }, + "required": [ + "args" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Action executed successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "output": {} + }, + "required": [ + "output" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Invalid action" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/gateway/{actorId}/request/{path}": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "put": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "delete": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "patch": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "head": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + }, + "options": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The HTTP path to forward to the actor" + } + ], + "responses": { + "200": { + "description": "Response from actor's raw HTTP handler" + } + } + } + }, + "/gateway/{actorId}/inspector/state": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Current actor state", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": {} + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + }, + "patch": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": {} + }, + "required": [ + "state" + ] + } + } + } + }, + "responses": { + "200": { + "description": "State updated", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "ok": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/connections": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Current actor connections", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "connections": { + "type": "array", + "items": { + "type": "object" + } + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/rpcs": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Available actor actions/RPCs", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "rpcs": { + "type": "object" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/action/{name}": { + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The name of the action to execute" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "args": { + "type": "array", + "items": {} + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Action executed successfully", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "output": {} + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/queue": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 50 + }, + "description": "Maximum number of queue messages to return" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Queue status", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "size": { + "type": "integer" + }, + "maxSize": { + "type": "integer" + }, + "truncated": { + "type": "boolean" + }, + "messages": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "createdAtMs": { + "type": "integer" + } + } + } + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/traces": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "startMs", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 0 + }, + "description": "Start of time range in epoch milliseconds" + }, + { + "name": "endMs", + "in": "query", + "required": false, + "schema": { + "type": "integer" + }, + "description": "End of time range in epoch milliseconds. Defaults to now." + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 1000 + }, + "description": "Maximum number of spans to return" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Trace spans in OTLP JSON format", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "otlp": { + "type": "object" + }, + "clamped": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/workflow-history": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Workflow history and status", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "history": {}, + "isWorkflowEnabled": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/workflow/replay": { + "post": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "entryId": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Workflow history after scheduling a replay", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "history": {}, + "isWorkflowEnabled": { + "type": "boolean" + } + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/gateway/{actorId}/inspector/summary": { + "get": { + "parameters": [ + { + "name": "actorId", + "in": "path", + "required": true, + "schema": { + "type": "string" + }, + "description": "The ID of the actor to target" + }, + { + "name": "Authorization", + "in": "header", + "required": false, + "schema": { + "type": "string" + }, + "description": "Bearer token for inspector authentication. Required in production, optional in development." + } + ], + "responses": { + "200": { + "description": "Full actor inspector summary", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": {}, + "connections": { + "type": "array", + "items": { + "type": "object" + } + }, + "rpcs": { + "type": "object" + }, + "queueSize": { + "type": "integer" + }, + "isStateEnabled": { + "type": "boolean" + }, + "isDatabaseEnabled": { + "type": "boolean" + }, + "isWorkflowEnabled": { + "type": "boolean" + }, + "workflowHistory": {} + } + } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + } + } +} \ No newline at end of file diff --git a/.agents/skills/rivetkit/reference/actors/access-control.md b/.agents/skills/rivetkit/reference/actors/access-control.md new file mode 100644 index 0000000..02dc4e8 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/access-control.md @@ -0,0 +1,48 @@ +# Access Control + +> Source: `src/content/docs/actors/access-control.mdx` +> Canonical URL: https://rivet.dev/docs/actors/access-control +> Description: Authorize actions, queue publishes, and event subscriptions with explicit hooks. + +--- +Use access control to decide what authenticated clients are allowed to do. + +This is authorization, not authentication: + +- Use [authentication](/docs/actors/authentication) to identify who is calling. +- Use access-control rules to decide what they can do after connecting. + +## Permission Surfaces + +RivetKit authorization is explicit per surface: + +- `onBeforeConnect` rejects unauthenticated or malformed connections. +- Action handlers (`actions.*`) enforce action permissions. +- `queues..canPublish` allows or denies inbound queue publishes. +- `events..canSubscribe` allows or denies event subscriptions. + +## Fail By Default + +Use deny-by-default rules everywhere: + +1. Keep `onBeforeConnect` strict and reject invalid credentials. +2. In each action, explicitly allow expected roles and throw `forbidden` otherwise. +3. In `canPublish` and `canSubscribe`, return `true` only for allowed roles and end with `return false`. + +## Return Value Contract + +`canPublish` and `canSubscribe` must return a boolean: + +- `true`: allow +- `false`: deny with `forbidden` + +Returning `undefined`, `null`, or any non-boolean throws an internal error. + +## Notes + +- `canPublish` only applies to queue names defined in `queues`. +- Incoming queue messages for undefined queues are ignored and the publish succeeds as completed. +- `canSubscribe` only applies to event names defined in `events`. +- Broadcasting an event not defined in `events` still publishes to subscribers. + +_Source doc path: /docs/actors/access-control_ diff --git a/.agents/skills/rivetkit/reference/actors/actions.md b/.agents/skills/rivetkit/reference/actors/actions.md new file mode 100644 index 0000000..d00324e --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/actions.md @@ -0,0 +1,98 @@ +# Actions + +> Source: `src/content/docs/actors/actions.mdx` +> Canonical URL: https://rivet.dev/docs/actors/actions +> Description: Actions are how your backend, frontend, or other actors can communicate with actors. + +--- +Actions are very lightweight. They can be called thousands of times per second safely. Actions are executed via HTTP requests or via WebSockets if [using `.connect()`](/docs/actors/connections). + +For advanced use cases that require direct access to HTTP requests or WebSocket connections, see [raw HTTP and WebSocket handling](/docs/actors/fetch-and-websocket-handler). + +By default, actions run in parallel. If you need advanced control over concurrency, use [queues](/docs/actors/queues). + +## Writing Actions + +Actions are defined in the `actions` object when creating an actor: + +Each action receives a context object (commonly named `c`) as its first parameter, which provides access to state, connections, and other utilities. Additional parameters follow after that. + +## Calling Actions + +Actions can be called in different ways depending on your use case: + +### Frontend (createClient) + +Learn more about [communicating with actors from the frontend](/docs/actors/communicating-between-actors). + +### Backend (registry.handler) + +Learn more about [communicating with actors from the backend](/docs/actors/communicating-between-actors). + +### Actor-to-Actor (c.client()) + +Learn more about [communicating between actors](/docs/actors/communicating-between-actors). + +Calling actions from the client are async and require an `await`, even if the action itself is not async. + +### Type Safety + +The actor client includes type safety out of the box. When you use `createClient()`, TypeScript automatically infers action parameter and return types: + +## Error Handling + +Actors provide robust error handling out of the box for actions. + +### User Errors + +`UserError` can be used to return rich error data to the client. You can provide: + +- A human-readable message +- A machine-readable code that's useful for matching errors in a try-catch (optional) +- A metadata object for providing richer error context (optional) + +For example: + +### Internal Errors + +All other errors will return an error with the code `internal_error` to the client. This helps keep your application secure, as errors can sometimes expose sensitive information. + +## Schema Validation + +If passing data to an actor from the frontend, use a library like [Zod](https://zod.dev/) to validate input data. + +For example, to validate action parameters: + +## Streaming Data + +Actions have a single return value. To stream realtime data in response to an action, use [events](/docs/actors/events). + +## Canceling Long-Running Actions + +For operations that should be cancelable on-demand, create your own `AbortController`. Chain it with `c.abortSignal` so actor shutdown also cancels the operation. + +See [Actor Shutdown Abort Signal](/docs/actors/lifecycle#actor-shutdown-abort-signal) for automatically canceling operations when the actor stops. + +## Using `ActionContext` Externally + +When writing complex logic for actions, you may want to extract parts of your implementation into separate helper functions. When doing this, you'll need a way to properly type the context parameter. + +Rivet provides the `ActionContextOf` utility type for exactly this purpose: + +See [types](/docs/actors/types) for more details on using `ActionContextOf` and other utility types. + +## Debugging + +- `GET /inspector/rpcs` lists all available actions on an actor. +- `POST /inspector/action/:name` executes an action with JSON args and returns output. +- In non-dev mode, inspector endpoints require authorization. + +## API Reference + +- [`Actions`](/typedoc/interfaces/rivetkit.mod.Actions.html) - Interface for defining actions +- [`ActionContext`](/typedoc/interfaces/rivetkit.mod.ActionContext.html) - Context available in action handlers +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining actors with actions +- [`ActorHandle`](/typedoc/types/rivetkit.client_mod.ActorHandle.html) - Handle for calling actions from client +- [`ActorActionFunction`](/typedoc/types/rivetkit.client_mod.ActorActionFunction.html) - Type for action functions + +_Source doc path: /docs/actors/actions_ diff --git a/.agents/skills/rivetkit/reference/actors/actor-runtime-socket.md b/.agents/skills/rivetkit/reference/actors/actor-runtime-socket.md new file mode 100644 index 0000000..2f736d5 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/actor-runtime-socket.md @@ -0,0 +1,54 @@ +# Actor Runtime Socket + +> Source: `src/content/docs/actors/actor-runtime-socket.mdx` +> Canonical URL: https://rivet.dev/docs/actors/actor-runtime-socket +> Description: Connect trusted local tools to a running Rivet Actor over an experimental actor-local protocol. + +--- +> **Experimental:** The Actor Runtime Socket protocol and API may change between releases. It is available only in the Unix native runtime and must be enabled per actor. + +The **Actor Runtime Socket** is a generic, actor-local protocol for trusted tools running in the same application environment as a Rivet Actor. SQLite is its first capability; Unix domain sockets are its current transport. + +Each running actor generation lazily creates its own socket. The socket is removed when that generation sleeps, stops, or is destroyed, so clients must request the current path again after the actor wakes or restarts. + +## Enable the socket + +Enable the feature under the actor's `options`, then provision it from the actor context: + +```ts @nocheck +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +export const example = actor({ + options: { + enableActorRuntimeSocket: true, + }, + db: db({ + onMigrate: async (db) => { + await db.execute("CREATE TABLE IF NOT EXISTS items (value TEXT)"); + }, + }), + run: async (c) => { + const { path } = await c.actorRuntimeSocket(); + // Give `path` only to trusted, application-local tooling. + }, +}); +``` + +Provisioning fails unless the actor has an enabled LocalNative SQLite database. The per-process socket directory uses mode `0700`, and each actor socket uses mode `0600`. + +## Protocol + +Unix `SOCK_STREAM` provides a reliable local byte stream but does not preserve message boundaries. Every frame is therefore a four-byte big-endian payload length followed by a versioned BARE (`vbare`) payload. The embedded protocol version is a two-byte little-endian prefix. Clients begin with `ClientHello`; the server returns `HelloOk` with the maximum frame size or rejects an unsupported version. + +The current protocol supports: + +- multi-statement SQLite scripts with `SqliteExec`; +- single-statement parameterized queries with `SqliteQuery`; +- transactions spanning requests with `SqliteBegin`, `SqliteCommit`, and `SqliteRollback`. + +A transaction is identified by a client-chosen `leaseKey` scoped to one connection. Other actor SQL and other socket transactions wait in FIFO order while it runs. Transactions default to a 60-second safety timeout; `SqliteBegin.timeoutMs` may override it. If the deadline fires, RivetKit rolls the transaction back and later requests for that key receive `LeaseExpired`. + +The socket is an application-local integration boundary, not a network authentication boundary. It intentionally has no bearer token. Clients must still honor framing and response limits, and should reconnect using a newly provisioned path after actor generation changes. + +_Source doc path: /docs/actors/actor-runtime-socket_ diff --git a/.agents/skills/rivetkit/reference/actors/appearance.md b/.agents/skills/rivetkit/reference/actors/appearance.md new file mode 100644 index 0000000..f60b1a1 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/appearance.md @@ -0,0 +1,50 @@ +# Icons & Names + +> Source: `src/content/docs/actors/appearance.mdx` +> Canonical URL: https://rivet.dev/docs/actors/appearance +> Description: Customize actors with display names and icons for the Rivet inspector and dashboard. + +--- +# Icons & Names + +Actors can be customized with a display name and icon that appear in the Rivet inspector & dashboard. This helps identify actors at a glance when managing your application. + +## Configuration + +Set the `name` and `icon` properties in your actor's `options`: + +## Icon Formats + +The `icon` property accepts two formats: + +### Emoji + +Use any emoji character directly: + +### FontAwesome Icons + +Use [FontAwesome](https://fontawesome.com/search) icon names without the "fa" prefix: + +## Default Behavior + +If no `icon` is specified, actors display the default actor icon. If no `name` is specified, the actor's registry key (e.g., `chatRoom`, `gameServer`) is displayed instead. + +## Examples + +Here are some common patterns: + +## Advanced: Run Handler Metadata + +For library developers creating reusable run handlers, you can bundle icon and name metadata directly with the `run` property. This allows libraries to provide sensible defaults without requiring users to configure them manually. + +Instead of returning a function from your run handler factory, return an object with `name`, `icon`, and `run`: + +Users can then use this directly: + +This run-handler metadata is currently applied through the registry and serverless metadata paths. The native runtime and inspector config read the actor's `options.name` and `options.icon` directly, so set those explicitly if you need the name or icon to appear everywhere. + +Actor-level `options.name` and `options.icon` always take precedence, allowing users to override library defaults: + +The built-in `workflow()` helper uses this pattern to automatically display the workflow icon for workflow-based actors. + +_Source doc path: /docs/actors/appearance_ diff --git a/.agents/skills/rivetkit/reference/actors/authentication.md b/.agents/skills/rivetkit/reference/actors/authentication.md new file mode 100644 index 0000000..c456dde --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/authentication.md @@ -0,0 +1,105 @@ +# Authentication + +> Source: `src/content/docs/actors/authentication.mdx` +> Canonical URL: https://rivet.dev/docs/actors/authentication +> Description: Secure your actors with authentication and authorization. + +--- +## Do You Need Authentication? + +### Rivet Cloud + + Actors are private by default on Rivet Cloud. Only requests with the publishable token can interact with actors. + + - **Backend-only actors**: If your publishable token is only included in your backend, then authentication is not necessary. + - **Frontend-accessible actors**: If your publishable token is included in your frontend, then implementing authentication is recommended. + +### Self-Hosted + + Actors are public by default on self-hosted Rivet. Anyone can access them without a token. + + - **Only accessible within private network**: If Rivet is only accessible within your private network, then authentication is not necessary. + - **Rivet exposed to the public internet**: If Rivet is configured to accept traffic from the public internet, then implementing authentication is recommended. + +## Authentication Connections + +Authentication is configured through either: + +- `onBeforeConnect` for simple pass/fail validation +- `createConnState` when you need to access user data in your actions via `c.conn.state` + +## Access Control + +After a connection is authenticated, use [Access Control](/docs/actors/access-control) to enforce authorization: + +- Check permissions in action handlers. +- Use `queues..canPublish` to gate inbound queue publishes. +- Use `events..canSubscribe` to gate event subscriptions. + +### `onBeforeConnect` + +The `onBeforeConnect` hook validates credentials before allowing a connection. Throw an error to reject the connection. + +### `createConnState` + +Use `createConnState` to extract user data from credentials and store it in connection state. This data is accessible in actions via `c.conn.state`. Like `onBeforeConnect`, throwing an error will reject the connection. See [connections](/docs/actors/connections) for more details. + +## Available Auth Data + +Authentication hooks have access to several properties: + +| Property | Description | +|----------|-------------| +| `params` | Custom data passed by the client when connecting (see [connection params](/docs/actors/connections#extracting-data-from-connection-params)) | +| `c.request` | The underlying HTTP request object | +| `c.request.headers` | Request headers for tokens, API keys (does not work for `.connect()`) | +| `c.state` | Actor state for authorization decisions (see [state](/docs/actors/state)) | +| `c.key` | The actor's key (see [keys](/docs/actors/keys)) | + +It's recommended to use `params` instead of `c.request.headers` whenever possible since it works for both HTTP & WebSocket connections. + +## Client Usage + +### Passing Credentials + +Pass authentication data when connecting. Use `getParams` when you need a fresh JWT for every connection or reconnect: + +### Handling Errors + +Authentication errors use the same system as regular errors. See [errors](/docs/actors/errors) for more details. + +## Examples + +### JWT + +Validate JSON Web Tokens and extract user claims: + +### External Auth Provider + +Validate credentials against an external authentication service: + +### Using `c.state` In Authorization + +Access actor state via `c.state` and the actor's key via `c.key` to make authorization decisions: + +### Role-Based Access Control + +Create helper functions for common authorization patterns: + +### Rate Limiting + +Use `c.vars` to track connection attempts and rate limit by user: + +The limits in this example are [ephemeral](/docs/actors/state#ephemeral-variables). If you wish to persist rate limits, you can optionally replace `vars` with `state`. + +### Caching Tokens + +Cache validated tokens in `c.vars` to avoid redundant validation on repeated connections. See [ephemeral variables](/docs/actors/state#ephemeral-variables) for more details. + +## API Reference + +- [`AuthIntent`](/typedoc/types/rivetkit.mod.AuthIntent.html) - Authentication intent type +- [`OnBeforeConnectContext`](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html) - Context for auth checks +- [`OnConnectContext`](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html) - Context after connection + +_Source doc path: /docs/actors/authentication_ diff --git a/.agents/skills/rivetkit/reference/actors/communicating-between-actors.md b/.agents/skills/rivetkit/reference/actors/communicating-between-actors.md new file mode 100644 index 0000000..8aeaf39 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/communicating-between-actors.md @@ -0,0 +1,42 @@ +# Communicating Between Actors + +> Source: `src/content/docs/actors/communicating-between-actors.mdx` +> Canonical URL: https://rivet.dev/docs/actors/communicating-between-actors +> Description: Learn how actors can call other actors and share data + +--- +Actors can communicate with each other using the server-side actor client, enabling complex workflows and data sharing between different actor instances. + +We recommend reading the [clients documentation](/docs/clients) first. This guide focuses specifically on communication between actors. + +## Using the Server-Side Actor Client + +The server-side actor client allows actors to call other actors within the same registry. Access it via `c.client()` in your actor context: + +If two actors call each other and their return types are inferred from the other actor's response, you may hit circular type errors (`TS2322`, `TS2722`, or `c.state` becoming `unknown`). Fix this by writing explicit return types on those actions. + +## Use Cases and Patterns + +### Actor Orchestration + +Use a coordinator actor to manage complex workflows: + +### Data Aggregation + +Collect data from multiple actors: + +### Event-Driven Architecture + +Use connections to listen for events from other actors: + +### Batch Operations + +Process multiple items in parallel: + +## API Reference + +- [`ActorHandle`](/typedoc/types/rivetkit.client_mod.ActorHandle.html) - Handle for calling other actors +- [`Client`](/typedoc/types/rivetkit.mod.Client.html) - Client type for actor communication +- [`ActorAccessor`](/typedoc/interfaces/rivetkit.client_mod.ActorAccessor.html) - Accessor for getting actor handles + +_Source doc path: /docs/actors/communicating-between-actors_ diff --git a/.agents/skills/rivetkit/reference/actors/connections.md b/.agents/skills/rivetkit/reference/actors/connections.md new file mode 100644 index 0000000..10ef081 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/connections.md @@ -0,0 +1,119 @@ +# Connections + +> Source: `src/content/docs/actors/connections.mdx` +> Canonical URL: https://rivet.dev/docs/actors/connections +> Description: Connections represent client connections to your actor. They provide a way to handle client authentication, manage connection-specific data, and control the connection lifecycle. + +--- +For documentation on connecting to actors from clients, see the [Clients documentation](/docs/clients). For worked presence and chat patterns, see the cookbook: [Live Cursors and Presence](/cookbook/live-cursors/) and [Chat Room](/cookbook/chat-room/). + +## Parameters + +When clients connect to an actor, they can pass connection parameters that are handled during the connection process. Use `params` for static values, or `getParams` when you need fresh connection data each time a connection opens. + +For example: + +## Connection State + +There are two ways to define an actor's connection state: + + +### connState + + Define connection state as a constant value: + + + + This value will be cloned for every new connection using `structuredClone`. + + + +### createConnState + + Create connection state dynamically with a function called for each connection: + + + + +## Connection Lifecycle + +Each client connection goes through a series of lifecycle hooks that allow you to validate, initialize, and clean up connection-specific resources. + +**On Connect** (per client) + +- `onBeforeConnect` +- `createConnState` +- `onConnect` + +Pending connections are not visible in `c.conns` while `onBeforeConnect` or `createConnState` is running. RivetKit adds the connection to `c.conns` after those hooks succeed and before `onConnect` runs. + +**On Disconnect** (per client) + +- `onDisconnect` + +### `createConnState` and `connState` + +[API Reference](/typedoc/interfaces/rivetkit.mod.CreateConnStateContext.html) + +There are two ways to define the initial state for connections: +1. `connState`: Define a constant object that will be used as the initial state for all connections +2. `createConnState`: A function that dynamically creates initial connection state based on connection parameters. Can be async. + +Connections are not visible in `c.conns` until `createConnState` completes successfully. + +### `onBeforeConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html) + +The `onBeforeConnect` hook is called whenever a new client connects to the actor. Can be async. Clients can pass parameters when connecting, accessible via `params`. This hook is used for connection validation and can throw errors to reject connections. + +The `onBeforeConnect` hook does NOT return connection state - it's used solely for validation. + +Connections are not visible in `c.conns` while `onBeforeConnect` is running. + +Connections cannot interact with the actor until this method completes successfully. Throwing an error will abort the connection. This can be used for authentication, see [Authentication](/docs/actors/authentication) for details. + +### `onConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html) + +Executed after the client has successfully connected. Can be async. Receives the connection object as a second parameter. + +By the time `onConnect` runs, the connection is visible in `c.conns`. + +Messages will not be processed for this actor until this hook succeeds. Errors thrown from this hook will cause the client to disconnect. + +### `onDisconnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Called when a client disconnects from the actor. Can be async. Receives the connection object as a second parameter. Use this to clean up any connection-specific resources. + +## Connection List + +All active connections can be accessed through the context object's `conns` property. This is a `Map` of all current connections, keyed by connection ID. + +This is frequently used with `conn.send(name, event)` to send messages directly to clients. To send an event to all connections at once, use `c.broadcast()` instead. See [Events](/docs/actors/events) for more details on broadcasting. + +For example: + +`conn.send()` has no effect on [low-level WebSocket connections](/docs/actors/websocket-handler). For low-level WebSockets, use the WebSocket API directly (e.g., `websocket.send()`). + +## Disconnecting clients + +Connections can be disconnected from within an action: + +If you need to wait for the disconnection to complete, you can use `await`: + +This ensures the underlying network connections close cleanly before continuing. + +## API Reference + +- [`Conn`](/typedoc/interfaces/rivetkit.mod.Conn.html) - Connection interface +- [`ConnInitContext`](/typedoc/interfaces/rivetkit.mod.ConnInitContext.html) - Connection initialization context +- [`CreateConnStateContext`](/typedoc/interfaces/rivetkit.mod.CreateConnStateContext.html) - Context for creating connection state +- [`OnBeforeConnectContext`](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html) - Pre-connection lifecycle hook context +- [`OnConnectContext`](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html) - Post-connection lifecycle hook context +- [`ActorConn`](/typedoc/types/rivetkit.client_mod.ActorConn.html) - Typed connection from client side + +_Source doc path: /docs/actors/connections_ diff --git a/.agents/skills/rivetkit/reference/actors/debugging.md b/.agents/skills/rivetkit/reference/actors/debugging.md new file mode 100644 index 0000000..409b381 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/debugging.md @@ -0,0 +1,644 @@ +# Debugging + +> Source: `src/content/docs/actors/debugging.mdx` +> Canonical URL: https://rivet.dev/docs/actors/debugging +> Description: Inspect and debug running Rivet Actors, runners, and provider configs using management, runner, and actor inspector HTTP APIs. + +--- +## Connecting to Rivet + +All debugging endpoints in this guide are available both locally and in production. In local development, the base URL is `http://localhost:6420` with no authentication. In production (Rivet Cloud or self-hosted), you connect to your Rivet Engine endpoint with a token. + +### Setup + +All examples in this guide use these shell variables. Extract them from your `RIVET_ENDPOINT` (`https://:@`): + +```bash +# From RIVET_ENDPOINT=https://my-namespace:sk_abc123@api.rivet.dev +export RIVET_API="https://api.rivet.dev" +export RIVET_NAMESPACE="my-namespace" +export RIVET_TOKEN="sk_abc123" + +# For local development: +# export RIVET_API="http://localhost:6420" +``` + +Rivet Cloud issues two token types: `sk_` (secret key, server-side only) and `pk_` (public key, client-safe). For debugging, always use `sk_`. See [Endpoints](/docs/general/endpoints) for more details. + +## Management API + +The management API runs on the manager base path (default root path) and is used to list, create, and look up actors. + +### Authentication + +| Environment | Authentication | +|---|---| +| **Local development** | No authentication required. All endpoints are accessible without tokens. | +| **Self-hosted engine** | Set `RIVET_TOKEN` to enable authenticated access to restricted endpoints like KV. | +| **Rivet Cloud** | Authentication is enforced by your deployment entrypoint. For manager KV access, use the bearer token header below when enabled. | + +Restricted endpoints (like KV reads) require the `Authorization: Bearer` header when `RIVET_TOKEN` is configured: + +```bash +curl "$RIVET_API/actors/{actor_id}/kv/keys/{base64_key}" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +### List Actors + +```bash +# List all actors with a given name +curl "$RIVET_API/actors?name=my-actor&namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" + +# Look up one actor by key (name is required when key is provided) +curl "$RIVET_API/actors?name=my-actor&key=%5B%22my-key%22%5D&namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" + +# List actors by IDs (comma-separated) +curl "$RIVET_API/actors?actor_ids=id1,id2&namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Rules: + +- `key` requires `name`. +- `actor_ids` cannot be combined with `name` or `key`. + +Returns: + +```json +{ + "actors": [ + { + "actor_id": "abc123", + "name": "my-actor", + "key": "[\"default\"]", + "namespace_id": "default", + "create_ts": 1706000000000 + } + ] +} +``` + +### Create Actor + +`POST /actors` creates a new actor. + +```bash +curl -X POST "$RIVET_API/actors?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H 'Content-Type: application/json' \ + -d '{ + "name": "my-actor", + "runner_name_selector": "default", + "crash_policy": "restart" + }' +``` + +### Create or Get Actor + +`PUT /actors` creates an actor if it does not exist, otherwise returns the existing one. + +```bash +curl -X PUT "$RIVET_API/actors?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H 'Content-Type: application/json' \ + -d '{ + "name": "my-actor", + "key": "[\"default\"]", + "runner_name_selector": "default", + "crash_policy": "restart" + }' +``` + +Returns the actor object with its `actor_id`. + +### List Actor Names + +```bash +curl "$RIVET_API/actors/names?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns all registered actor names and their metadata. + +### Read Actor KV + +Requires authentication (see above). + +```bash +curl "$RIVET_API/actors/{actor_id}/kv/keys/{base64_key}" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns the value stored at the given key in the actor KV compatibility snapshot. After an actor has migrated to SQLite-backed runtime storage, this endpoint is stale for user KV and internal runtime records; it continues to expose the frozen pre-migration KV data. The inspector token key is the exception and remains mirrored for dashboard compatibility. + +See the [OpenAPI spec](https://github.com/rivet-dev/rivet/tree/main/rivetkit-openapi) for the full schema of all management endpoints. + +## Runner API + +Use the runner endpoints to debug scheduler capacity and provider configuration (for example serverless URL, headers, and limits) through the Rivet API. + +### List Runner Names + +```bash +curl "$RIVET_API/runners/names?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns the runner pools available in the namespace: + +```json +{ + "names": ["default", "gpu-workers"], + "pagination": { "cursor": null } +} +``` + +### List Runners in a Pool + +```bash +curl "$RIVET_API/runners?namespace=$RIVET_NAMESPACE&name=default&include_stopped=true&limit=100" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Useful fields when debugging: + +- `remaining_slots` / `total_slots` for capacity. +- `drain_ts` and `stop_ts` for shutdown behavior. +- `last_ping_ts` and `last_connected_ts` for connectivity. + +### Inspect Provider Config (Runner Config) + +```bash +curl "$RIVET_API/runner-configs?namespace=$RIVET_NAMESPACE&runner_name=default" \ + -H "Authorization: Bearer $RIVET_TOKEN" +``` + +Returns the configured provider settings per datacenter and the latest pool error (if any): + +```json +{ + "runner_configs": { + "default": { + "datacenters": { + "dc-1": { + "serverless": { + "url": "https://your-deployment.example.com/rivet", + "headers": { "Authorization": "Bearer token" }, + "request_lifespan": 55, + "slots_per_runner": 1, + "max_runners": 10 + }, + "runner_pool_error": null + } + } + } + }, + "pagination": { "cursor": null } +} +``` + +`runner_pool_error` mirrors actor scheduling errors such as `serverless_http_error`, `serverless_connection_error`, and `serverless_stream_ended_early`. + +### Check Serverless Provider Health + +Use this to test whether Rivet can reach your serverless provider URL and read runner metadata: + +```bash +curl -X POST "$RIVET_API/runner-configs/serverless-health-check?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "url": "https://your-deployment.example.com/rivet", + "headers": { + "Authorization": "Bearer token" + } + }' +``` + +Possible responses: + +```json +{ "success": { "version": "1.2.3" } } +``` + +```json +{ + "failure": { + "error": { + "message": "non-success status from metadata endpoint", + "details": "received status 503" + } + } +} +``` + +### Refresh Provider Metadata + +If you deploy new actor code or routes and metadata has not updated yet, force a refresh: + +```bash +curl -X POST "$RIVET_API/runner-configs/default/refresh-metadata?namespace=$RIVET_NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{}' +``` + +## Actor API + +All actor-level endpoints are accessed through the gateway. The gateway routes requests to the correct actor instance using the actor ID in the URL path: + +``` +{RIVET_API}/gateway/{actor_id}/{path} +``` + +The gateway only accepts actor IDs, not names. Use `GET /actors?name=...` from the management API to look up actor IDs first. + +### Authentication + +Standard actor endpoints (health, actions, requests) and inspector endpoints have separate authentication requirements. + +#### Standard Endpoints + +| Environment | Authentication | +|---|---| +| **Local development** | No authentication required. | +| **Self-hosted engine** | The Rivet Engine handles authentication at the gateway level. | +| **Rivet Cloud** | Authentication is handled by the Rivet Cloud platform at the gateway level. | + +#### Inspector Endpoints + +Each actor generates a unique inspector token on first start and persists it in internal SQLite storage. It is also mirrored to legacy KV key `0x03` (base64 `Aw==`) for dashboard compatibility. Pass it as a bearer token in the `Authorization` header. + +Inspector endpoints always require the actor's inspector token, including in local development. There is no local-development bypass. + +| Environment | Authentication | +|---|---| +| **Local development** | Bearer the actor's inspector token in the `Authorization` header. Fetch it through the management KV endpoint (see below). | +| **Self-hosted engine** | Bearer the actor's inspector token in the `Authorization` header. The Rivet dashboard fetches it automatically; for direct API access, fetch it through the management KV endpoint (see below). | +| **Rivet Cloud** | Bearer the actor's inspector token in the `Authorization` header. The Rivet dashboard fetches it automatically; for direct API access, fetch it through the management KV endpoint (see below). | + +```bash +curl "$RIVET_API/gateway/{actor_id}/inspector/summary" \ + -H 'Authorization: Bearer YOUR_INSPECTOR_TOKEN' +``` + +#### Retrieving the Inspector Token + +Each actor generates a unique inspector token on first start and persists it in internal SQLite storage. The token is also mirrored to the legacy KV key below so the Rivet dashboard can continue to retrieve it through the management KV endpoint. This applies in every environment, including local development. + +The inspector token is stored at internal KV key `0x03` (base64: `Aw==`). The response value is also base64-encoded. + +```bash +# Fetch the inspector token for a specific actor +ACTOR_ID="your-actor-id" + +RESPONSE=$(curl -s "$RIVET_API/actors/$ACTOR_ID/kv/keys/Aw==" \ + -H "Authorization: Bearer $RIVET_TOKEN") + +# Extract and decode the base64 value +INSPECTOR_TOKEN=$(echo "$RESPONSE" | jq -r '.value' | base64 -d) + +# Use it to call inspector endpoints +curl "$RIVET_API/gateway/$ACTOR_ID/inspector/summary" \ + -H "Authorization: Bearer $INSPECTOR_TOKEN" +``` + +### Standard Actor Endpoints + +These are the built-in actor endpoints available through the gateway: + +```bash +# Health check +curl $RIVET_API/gateway/{actor_id}/health + +# Metadata +curl $RIVET_API/gateway/{actor_id}/metadata + +# Call an action +curl -X POST $RIVET_API/gateway/{actor_id}/action/myAction \ + -H 'Content-Type: application/json' \ + -d '{"args": [1, 2, 3]}' + +# Send queue message (queue name in path) +curl -X POST $RIVET_API/gateway/{actor_id}/queue/jobs \ + -H 'Content-Type: application/json' \ + -d '{"body":{"id":"job-1"}}' + +# Send queue message and wait for completion (optional timeout in ms) +curl -X POST $RIVET_API/gateway/{actor_id}/queue/jobs \ + -H 'Content-Type: application/json' \ + -d '{"body":{"id":"job-1"},"wait":true,"timeout":5000}' + +# Forward an HTTP request to the actor's onRequest handler +curl $RIVET_API/gateway/{actor_id}/request/my/custom/path +``` + +Queue send responses always include a `status` field: + +```json +{ "status": "completed" } +``` + +The `response` field is only present when the queue handler returns a value: + +```json +{ "status": "completed", "response": { "result": "ok" } } +``` + +If `wait: true` and the timeout is reached, `status` is `"timedOut"`. + +### Inspector Endpoints + +The inspector HTTP API exposes JSON endpoints for querying and modifying actor internals at runtime. These are designed for agent-based debugging and tooling. + +Every inspector endpoint requires the actor's inspector token as a bearer token, including in local development. The examples below omit the `Authorization` header for brevity, but you must add `-H "Authorization: Bearer $INSPECTOR_TOKEN"` to each request. See [Retrieving the Inspector Token](#retrieving-the-inspector-token) above. + +#### Get State + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/state +``` + +Returns the actor's current persisted state: + +```json +{ + "state": { "count": 42, "users": [] }, + "isStateEnabled": true +} +``` + +#### Set State + +```bash +curl -X PATCH $RIVET_API/gateway/{actor_id}/inspector/state \ + -H 'Content-Type: application/json' \ + -d '{"state": {"count": 0, "users": []}}' +``` + +Returns: + +```json +{ "ok": true } +``` + +#### Get Connections + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/connections +``` + +Returns all active connections with their params, state, and metadata: + +```json +{ + "connections": [ + { + "type": "websocket", + "id": "conn-id", + "details": { + "type": "websocket", + "params": {}, + "stateEnabled": true, + "state": {}, + "subscriptions": 2, + "isHibernatable": true + } + } + ] +} +``` + +#### Get RPCs + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/rpcs +``` + +Returns a list of available actions: + +```json +{ "rpcs": ["increment", "getCount"] } +``` + +#### Execute Action + +```bash +curl -X POST $RIVET_API/gateway/{actor_id}/inspector/action/increment \ + -H 'Content-Type: application/json' \ + -d '{"args": [5]}' +``` + +Returns: + +```json +{ "output": 47 } +``` + +#### Get Queue Status + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/queue?limit=10 +``` + +Returns queue status with messages: + +```json +{ + "size": 3, + "maxSize": 1000, + "truncated": false, + "messages": [ + { "id": 1, "name": "process", "createdAtMs": 1706000000000 } + ] +} +``` + +#### Get Workflow History + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/workflow-history +``` + +Returns: + +```json +{ + "history": null, + "isWorkflowEnabled": false +} +``` + +#### Get Database Schema + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/database/schema +``` + +Returns discovered SQLite tables and views when the actor has `c.db` enabled: + +```json +{ + "schema": { + "tables": [ + { + "table": { "schema": "main", "name": "test_data", "type": "table" }, + "columns": [ + { "cid": 0, "name": "id", "type": "", "notnull": 0, "dflt_value": null, "pk": 0 } + ], + "foreignKeys": [], + "records": 2 + } + ] + } +} +``` + +#### Get Database Rows + +```bash +curl "$RIVET_API/gateway/{actor_id}/inspector/database/rows?table=test_data&limit=100&offset=0" +``` + +Returns paged rows for a specific SQLite table or view: + +```json +{ + "rows": [ + { + "id": 1, + "value": "Alice", + "payload": "", + "created_at": 1706000000000 + } + ] +} +``` + +#### Execute SQLite + +Run manual SQL against an actor's SQLite database. This supports both read-only queries and mutations. + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/database/execute \ + -H 'Content-Type: application/json' \ + -d '{ + "sql": "SELECT id, value FROM test_data WHERE value = ? ORDER BY id DESC", + "args": ["alpha"] + }' +``` + +Returns: + +```json +{ + "rows": [ + { "id": 2, "value": "alpha" } + ] +} +``` + +You can also use named SQLite bindings through a `properties` object: + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/database/execute \ + -H 'Content-Type: application/json' \ + -d '{ + "sql": "SELECT id, value FROM test_data WHERE value = :value ORDER BY id DESC", + "properties": { + "value": "alpha" + } + }' +``` + +For mutations, use `RETURNING` if you want rows back. Otherwise the statement still runs and `rows` is empty: + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/database/execute \ + -H 'Content-Type: application/json' \ + -d '{ + "sql": "INSERT INTO test_data (value, created_at) VALUES (?, ?) RETURNING id, value", + "args": ["beta", 1706000000000] + }' +``` + +For workflow-enabled actors, `history` is a JSON object with `nameRegistry`, `entries`, and `entryMetadata`. Step outputs, loop state, and message payloads are decoded from CBOR into normal JSON values. + +#### Replay Workflow From Step + +Reset a workflow to a specific step and restart execution immediately. Omitting `entryId` replays the workflow from the beginning. + +If the workflow is still running when you call replay, the endpoint rejects the request with `409 Conflict` and an `actor/workflow_in_flight` error instead of cancelling the live run for you. + +```bash +curl -X POST http://localhost:6420/gateway/{actor_id}/inspector/workflow/replay \ + -H 'Content-Type: application/json' \ + -d '{"entryId":"workflow-step-id"}' +``` + +Returns the same JSON shape as `/inspector/workflow-history`: + +```json +{ + "history": { + "nameRegistry": ["step-one", "step-two"], + "entries": [], + "entryMetadata": {} + }, + "isWorkflowEnabled": true +} +``` + +While a workflow is in flight, the response shape is: + +```json +{ + "group": "actor", + "code": "workflow_in_flight", + "message": "Workflow replay is unavailable while the workflow is currently in flight.", + "metadata": null +} +``` + +#### Summary + +Get a full snapshot of the actor in a single request: + +```bash +curl $RIVET_API/gateway/{actor_id}/inspector/summary +``` + +Returns: + +```json +{ + "state": { "count": 42 }, + "connections": [], + "rpcs": ["increment", "getCount"], + "queueSize": 0, + "isStateEnabled": true, + "isDatabaseEnabled": false, + "isWorkflowEnabled": false, + "workflowHistory": null +} +``` + +When workflow history is present in `/inspector/summary`, `workflowHistory` is returned as the same decoded JSON shape as `/inspector/workflow-history`. + +### Polling + +Inspector endpoints are safe to poll. For live monitoring, poll at 1-5 second intervals. The `/inspector/summary` endpoint is useful for periodic snapshots since it returns all data in a single request. + +## OpenAPI Spec + +An OpenAPI specification covering many of the management and actor endpoints is available: + +- In the repository at [`rivetkit-openapi/openapi.json`](https://github.com/rivet-dev/rivet/tree/main/rivetkit-openapi) +- Served at `/doc` on the manager when running locally + +The checked-in spec does not yet list every endpoint documented on this page (for example the actor metadata and queue routes and the inspector database routes), so treat this page as the authoritative reference where they differ. + +_Source doc path: /docs/actors/debugging_ diff --git a/.agents/skills/rivetkit/reference/actors/design-patterns.md b/.agents/skills/rivetkit/reference/actors/design-patterns.md new file mode 100644 index 0000000..77ecb40 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/design-patterns.md @@ -0,0 +1,163 @@ +# Design Patterns + +> Source: `src/content/docs/actors/design-patterns.mdx` +> Canonical URL: https://rivet.dev/docs/actors/design-patterns +> Description: Common patterns and anti-patterns for building scalable actor systems. + +--- +## How Actors Scale + +Actors are inherently scalable because of how they're designed: + +- **Isolated state:** Each actor manages its own private data. No shared state means no conflicts and no locks, so actors run concurrently without coordination. +- **Actor-to-actor communication:** Actors interact through [actions](/docs/actors/actions) and [events](/docs/actors/events), so they don't need to coordinate access to shared data. This makes it easy to distribute them across machines. +- **Small, focused units:** Each actor handles a limited scope (a single user, document, or chat room), so load naturally spreads across many actors rather than concentrating in one place. +- **Horizontal scaling:** Adding more machines automatically distributes actors across them. + +These properties form the foundation for the patterns described below. + +## Actor Per Entity + +The core pattern is creating one actor per entity in your system. Each actor represents a single user, document, chat room, or other distinct object. This keeps actors small, independent, and easy to scale. + +**Good examples** + +- `User`: Manages user profile, preferences, and authentication +- `Document`: Handles document content, metadata, and versioning +- `ChatRoom`: Manages participants and message history + +**Bad examples** + +- `Application`: Too broad, handles everything +- `DocumentWordCount`: Too granular, should be part of Document actor + +## Coordinator & Data Actors + +Actors scale by splitting state into isolated entities. However, it's common to need to track and coordinate actors in a central place. This is where coordinator actors come in. + +**Data actors** handle the main logic in your application. Examples: chat rooms, user sessions, game lobbies. + +**Coordinator actors** track other actors. Think of them as an index of data actors. Examples: a list of chat rooms, a list of active users, a list of game lobbies. + +**Example: Chat Room Coordinator** + +### Actor + +### Client + +## Sharding + +Sharding splits a single actor's workload across multiple actors based on a key. Use this when one actor can't handle all the load or data for an entity. + +**How it works:** +- Partition data using a shard key (user ID, region, time bucket, or random) +- Requests are routed to shards based on the key +- Shards operate independently without coordination + +**Example: Sharding by Time** + +### Actor + +### Client + +**Example: Random Sharding** + +### Actor + +### Client + +Choose shard keys that distribute load evenly. Note that cross-shard queries require coordination. + +## Fan-In & Fan-Out + +Fan-in and fan-out are patterns for distributing work and aggregating results. + +**Fan-Out**: One actor spawns work across multiple actors. Use for parallel processing or broadcasting updates. + +**Fan-In**: Multiple actors send results to one aggregator. Use for collecting results or reducing data. + +**Example: Map-Reduce** + +### Actor + +### Client + +## Integrating With External Databases & APIs + +Actors can integrate with external resources like databases or external APIs. + +### Loading State + +Load external data during actor initialization using `createVars`. This keeps your actor's persisted state clean while caching expensive lookups. + +Use this when: + +- Fetching user profiles, configs, or permissions from a database +- Loading data that changes externally and shouldn't be persisted +- Caching expensive API calls or computations + +**Example: Loading User Profile** + +### Actor + +### Client + +### Syncing State Changes + +Use `onStateChange` to automatically sync actor state changes to external resources. This hook runs after state changes are flushed, which is coalesced to once per event loop tick rather than once per individual field mutation. + +Use this when: + +- You need to mirror actor state in an external database +- Triggering external side effects when state changes +- Keeping external systems in sync with actor state + +**Example: Syncing to Database** + +### Actor + +### Client + +`onStateChange` is called once per flush with the final coalesced state, ensuring external resources stay in sync. In the `updateEmail` example above, the two synchronous assignments produce a single `onStateChange` call. + +Do not mutate `c.state` inside `onStateChange`; re-entrant state mutation is rejected. + +## Anti-Patterns + +### "God" Actor + +Avoid creating a single actor that handles everything. This defeats the purpose of the actor model and creates a bottleneck. + +**Problem:** +```ts +import { actor } from "rivetkit"; + +// Bad: one actor doing everything +const app = actor({ + state: { users: {}, orders: {}, inventory: {}, analytics: {} }, + actions: { + createUser: (c, user) => { /* ... */ }, + processOrder: (c, order) => { /* ... */ }, + updateInventory: (c, item) => { /* ... */ }, + trackEvent: (c, event) => { /* ... */ }, + }, +}); +``` + +**Solution:** Split into focused actors per entity (User, Order, Inventory, Analytics). + +### Actor-Per-Request + +Actors are designed to maintain state across multiple requests. Creating a new actor for each request wastes resources and loses the benefits of persistent state. + +**Problem:** + +**Solution:** Use actors for entities that persist (users, sessions, documents), not for one-off operations. For stateless request handling, use regular functions. + +## API Reference + +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for pattern examples +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - Context usage patterns +- [`ActionContext`](/typedoc/interfaces/rivetkit.mod.ActionContext.html) - Action patterns + +_Source doc path: /docs/actors/design-patterns_ diff --git a/.agents/skills/rivetkit/reference/actors/destroy.md b/.agents/skills/rivetkit/reference/actors/destroy.md new file mode 100644 index 0000000..87e1b76 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/destroy.md @@ -0,0 +1,71 @@ +# Destroying Actors + +> Source: `src/content/docs/actors/destroy.mdx` +> Canonical URL: https://rivet.dev/docs/actors/destroy +> Description: Actors can be permanently destroyed. Common use cases include: + +--- +- User account deletion +- Ending a user session +- Closing a room or game +- Cleaning up temporary resources +- GDPR/compliance data removal + +Actors sleep when idle, so destruction is only needed to permanently remove data — not to save compute. + +## Destroying An Actor + +### Destroy via Action + +To destroy an actor, use `c.destroy()` like this: + +### Destroy via HTTP + +Send a DELETE request to destroy an actor. This requires a token for authentication: + +- **Rivet Cloud**: Use the service key (`sk_*`) from your `RIVET_ENDPOINT` URL. Find this in the dashboard under **Settings > Advanced > Backend Configuration** (e.g. the `sk_...` portion of `https://default:sk_abc123@api.rivet.dev`). +- **Self-hosted**: Use an admin token. + +```typescript +const actorId = "your-actor-id"; +const namespace = "default"; +const token = "your-token"; + +await fetch(`https://api.rivet.dev/actors/${actorId}?namespace=${namespace}`, { + method: "DELETE", + headers: { + Authorization: `Bearer ${token}`, + }, +}); +``` + +```bash +curl -X DELETE "https://api.rivet.dev/actors/{actorId}?namespace={namespace}" \ + -H "Authorization: Bearer {token}" +``` + +To find the actor ID, you can list actors first: + +```bash +curl "https://api.rivet.dev/actors?namespace={namespace}" \ + -H "Authorization: Bearer {token}" +``` + +### Destroy via Dashboard + +To destroy an actor via the dashboard, navigate to the actor and press the red "X" in the top right. + +## Lifecycle Hook + +Once destroyed, the `onDestroy` hook will be called. This can be used to clean up resources related to the actor. For example: + +## Accessing Actor After Destroy + +Once an actor is destroyed, any subsequent requests to it will fail with an `actor.not_found` error (`{ group: "actor", code: "not_found" }`). The actor's state is permanently deleted. + +## API Reference + +- [`ActorHandle`](/typedoc/types/rivetkit.client_mod.ActorHandle.html) - Has destroy methods +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - Context during destruction + +_Source doc path: /docs/actors/destroy_ diff --git a/.agents/skills/rivetkit/reference/actors/errors.md b/.agents/skills/rivetkit/reference/actors/errors.md new file mode 100644 index 0000000..af24c4c --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/errors.md @@ -0,0 +1,81 @@ +# Errors + +> Source: `src/content/docs/actors/errors.mdx` +> Canonical URL: https://rivet.dev/docs/actors/errors +> Description: Rivet provides robust error handling with security built in by default. Errors are handled differently based on whether they should be exposed to clients or kept private. + +--- +There are two types of errors: + +- **UserError**: Thrown from actors and safely returned to clients with full details +- **Internal errors**: All other errors that are converted to a generic error message for security + +## Throwing and Catching Errors + +`UserError` lets you throw custom errors that will be safely returned to the client. + +Throw a `UserError` with just a message: + +### Actor + +### Client (Connection) + +### Client (Stateless) + +## Error Codes + +Use error codes for explicit error matching in try-catch blocks: + +### Actor + +### Client (Connection) + +### Client (Stateless) + +## Errors With Metadata + +Include metadata to provide additional context for rich error handling: + +### Actor + +### Client (Connection) + +### Client (Stateless) + +## Internal Errors + +All errors that are not UserError instances are automatically converted to a generic "internal error" response. This prevents accidentally leaking sensitive information like stack traces, database details, or internal system information. + +### Actor + +### Client (Connection) + +### Client (Stateless) + +### Server-Side Logging + +**All internal errors are logged server-side with full details.** When an internal error occurs, the complete error message, stack trace, and context are written to your server logs. This is where you should look first when debugging internal errors in production. + +The client receives only a generic "Internal error" message for security, but you can find the full error details in your server logs including: + +- Complete error message +- Stack trace +- Request context (actor ID, action name, connection ID, etc.) +- Timestamp + +**Always check your server logs to see the actual error details when debugging internal errors.** + +### Exposing Errors to Clients (Development Only) + +**Warning:** Only enable error exposure in development environments. In production, this will leak sensitive internal details to clients. + +For faster debugging during development, you can expose internal error details to clients by setting `RIVET_EXPOSE_ERRORS=1`. + +With error exposure enabled, clients will see the full error message instead of the generic "Internal error" response: + +## API Reference + +- [`UserError`](/typedoc/classes/rivetkit.actor_errors.UserError.html) - User-facing error class +- [`ActorError`](/typedoc/classes/rivetkit.client_mod.ActorError.html) - Errors received by the client + +_Source doc path: /docs/actors/errors_ diff --git a/.agents/skills/rivetkit/reference/actors/events.md b/.agents/skills/rivetkit/reference/actors/events.md new file mode 100644 index 0000000..ec4a7d5 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/events.md @@ -0,0 +1,145 @@ +# Realtime + +> Source: `src/content/docs/actors/events.mdx` +> Canonical URL: https://rivet.dev/docs/actors/events +> Description: Events enable realtime communication from actors to clients. While clients use actions to send data to actors, events allow actors to push updates to connected clients instantly. + +--- +Events can be sent to clients connected using `.connect()`. They have no effect on [low-level WebSocket connections](/docs/actors/websocket-handler). + +For worked realtime patterns, see the cookbook: [Live Cursors and Presence](/cookbook/live-cursors/) and [Chat Room](/cookbook/chat-room/). + +## Publishing Events from Actors + +### Broadcasting to All Clients + +Define event names and payload types with `events` and `event()`, then use `c.broadcast(eventName, ...args)` to send events to all connected clients: + +### Sending to Specific Connections + +Send events to individual connections using `conn.send(eventName, ...args)`: + +Send events to all connections except the sender: + +## Subscribing to Events from Clients + +Clients must establish a connection to receive events from actors. Use `.connect()` to create a persistent connection, then listen for events. + +### Basic Event Subscription + +Use `connection.on(eventName, callback)` to listen for events: + +```tsx React @nocheck +import { useState } from "react"; +import { useActor } from "./rivetkit"; + +function ChatRoom() { + const [messages, setMessages] = useState>([]); + + const chatRoom = useActor({ + name: "chatRoom", + key: ["general"] + }); + + // Listen for events + chatRoom.useEvent("messageReceived", (message) => { + setMessages(prev => [...prev, message]); + }); + + // ...rest of component... +} +``` + +### One-time Event Listeners + +Use `connection.once(eventName, callback)` for events that should only trigger once: + +```tsx React @nocheck +import { useState, useEffect } from "react"; +import { useActor } from "./rivetkit"; + +function GameLobby() { + const [gameStarted, setGameStarted] = useState(false); + + const gameRoom = useActor({ + name: "gameRoom", + key: ["room-456"], + params: { + playerId: "player-789", + role: "player" + } + }); + + // Listen for game start (only once) + useEffect(() => { + if (!gameRoom.connection) return; + + const handleGameStart = () => { + console.log('Game has started!'); + setGameStarted(true); + }; + + gameRoom.connection.once('gameStarted', handleGameStart); + }, [gameRoom.connection]); + + // ...rest of component... +} +``` + +### Removing Event Listeners + +Use the callback returned from `.on()` to remove event listeners: + +```tsx React @nocheck +import { useState, useEffect } from "react"; +import { useActor } from "./rivetkit"; + +function ConditionalListener() { + const [isListening, setIsListening] = useState(false); + const [messages, setMessages] = useState([]); + + const chatRoom = useActor({ + name: "chatRoom", + key: ["general"] + }); + + useEffect(() => { + if (!chatRoom.connection || !isListening) return; + + // Add listener + const unsubscribe = chatRoom.connection.on('messageReceived', (message) => { + setMessages(prev => [...prev, message.text]); + }); + + // Cleanup - remove listener when component unmounts or listening stops + return () => { + unsubscribe(); + }; + }, [chatRoom.connection, isListening]); + + // ...rest of component... +} +``` + +## Debugging + +- `GET /inspector/connections` shows active connections and connection metadata. +- Use this to confirm clients are connected before expecting broadcasts. +- `GET /inspector/summary` provides connections, RPCs, and queue size in one response. +- In non-dev mode, inspector endpoints require authorization. + +## More About Connections + +For more details on actor connections, including connection lifecycle, authentication, and advanced connection patterns, see the [Connections documentation](/docs/actors/connections). + +## API Reference + +- [`RivetEvent`](/typedoc/interfaces/rivetkit.mod.RivetEvent.html) - Base event interface +- [`RivetMessageEvent`](/typedoc/interfaces/rivetkit.mod.RivetMessageEvent.html) - Message event type +- [`RivetCloseEvent`](/typedoc/interfaces/rivetkit.mod.RivetCloseEvent.html) - Close event type +- [`UniversalEvent`](/typedoc/interfaces/rivetkit.mod.UniversalEvent.html) - Universal event type +- [`UniversalMessageEvent`](/typedoc/interfaces/rivetkit.mod.UniversalMessageEvent.html) - Universal message event +- [`UniversalErrorEvent`](/typedoc/interfaces/rivetkit.mod.UniversalErrorEvent.html) - Universal error event +- [`EventUnsubscribe`](/typedoc/types/rivetkit.client_mod.EventUnsubscribe.html) - Unsubscribe function type + +_Source doc path: /docs/actors/events_ diff --git a/.agents/skills/rivetkit/reference/actors/fetch-and-websocket-handler.md b/.agents/skills/rivetkit/reference/actors/fetch-and-websocket-handler.md new file mode 100644 index 0000000..b8b0509 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/fetch-and-websocket-handler.md @@ -0,0 +1,10 @@ +# Fetch and WebSocket Handler + +> Source: `src/content/docs/actors/fetch-and-websocket-handler.mdx` +> Canonical URL: https://rivet.dev/docs/actors/fetch-and-websocket-handler +> Description: These docs have moved to [Low-Level WebSocket Handler](/docs/actors/websocket-handler) and [Low-Level Request Handler](/docs/actors/request-handler). + +--- + + +_Source doc path: /docs/actors/fetch-and-websocket-handler_ diff --git a/.agents/skills/rivetkit/reference/actors/helper-types.md b/.agents/skills/rivetkit/reference/actors/helper-types.md new file mode 100644 index 0000000..55555c7 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/helper-types.md @@ -0,0 +1,10 @@ +# Helper Types + +> Source: `src/content/docs/actors/helper-types.mdx` +> Canonical URL: https://rivet.dev/docs/actors/helper-types +> Description: This page has moved to [Types](/docs/actors/types). + +--- + + +_Source doc path: /docs/actors/helper-types_ diff --git a/.agents/skills/rivetkit/reference/actors/http-api.md b/.agents/skills/rivetkit/reference/actors/http-api.md new file mode 100644 index 0000000..1d8d5be --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/http-api.md @@ -0,0 +1,10 @@ +# Vanilla HTTP API + +> Source: `src/content/docs/actors/http-api.mdx` +> Canonical URL: https://rivet.dev/docs/actors/http-api +> Description: Use the low-level HTTP handler to send and receive requests from actors. + +--- +TODO + +_Source doc path: /docs/actors/http-api_ diff --git a/.agents/skills/rivetkit/reference/actors/input.md b/.agents/skills/rivetkit/reference/actors/input.md new file mode 100644 index 0000000..c5c5dde --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/input.md @@ -0,0 +1,51 @@ +# Input Parameters + +> Source: `src/content/docs/actors/input.mdx` +> Canonical URL: https://rivet.dev/docs/actors/input +> Description: Pass initialization data to actors when creating instances + +--- +Actors can receive input parameters when created, allowing for flexible initialization and configuration. Input is passed during actor creation and is available in lifecycle hooks. + +## Passing Input to Actors + +Input is provided when creating actor instances using the `input` property: + +## Accessing Input in Lifecycle Hooks + +Input is available as the second argument to the `createState` and `onCreate` lifecycle hooks: + +## Input Validation + +You can validate input parameters in the `createState` or `onCreate` hooks: + +## Input vs Connection Parameters + +Input parameters are different from connection parameters: + +- **Input**: + - Passed when creating the actor instance + - Use for actor-wide configuration + - Available in lifecycle hooks +- **Connection parameters**: + - Passed when connecting to an existing actor + - Used for connection-specific configuration + - Available in connection hooks + +## Input Best Practices + +### Use Type Safety + +Define input types to ensure type safety: + +### Store Input in State + +Input is only available in `createState` and `onCreate` lifecycle hooks. If you need to access input data later (in actions, timers, or other hooks), store it in the actor's state during creation. This is the recommended pattern because input shapes can evolve over time, and persisting input in state ensures you always have access to the values the actor was created with: + +## API Reference + +- [`CreateOptions`](/typedoc/interfaces/rivetkit.client_mod.CreateOptions.html) - Options for creating actors +- [`CreateRequest`](/typedoc/types/rivetkit.client_mod.CreateRequest.html) - Request type for creation +- [`ActorDefinition`](/typedoc/classes/rivetkit.mod.ActorDefinition.html) - Actor definition returned by `actor()` + +_Source doc path: /docs/actors/input_ diff --git a/.agents/skills/rivetkit/reference/actors/inspector-tabs.md b/.agents/skills/rivetkit/reference/actors/inspector-tabs.md new file mode 100644 index 0000000..34de206 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/inspector-tabs.md @@ -0,0 +1,251 @@ +# Custom Inspector Tabs + +> Source: `src/content/docs/actors/inspector-tabs.mdx` +> Canonical URL: https://rivet.dev/docs/actors/inspector-tabs +> Description: Ship your own UI tabs alongside a Rivet Actor — embedded directly in the dashboard inspector. + +--- +Custom inspector tabs let you embed your own UI directly in the Rivet +dashboard, next to the built-in tabs. Declare a tab on your actor, point +it at a folder of static files, and the dashboard picks it up +automatically. + +Common uses: + +- Domain-specific debugging panels (queue depth, connection maps, log + filters). +- Operational tools (admin buttons, drain controls, snapshot uploaders). +- Any author-defined view that ships with your actor. + +A runnable example lives at +[`examples/inspector-tabs`](https://github.com/rivet-dev/rivet/tree/main/examples/inspector-tabs). + +## Quickstart + +Declare a tab on your actor: + +Drop an `index.html` in the `source` directory: + +```html + + + + + + + +

Counter: …

+ + + +``` + +Open the dashboard and the "Counter" tab appears alongside the built-ins. + +## Configuration + +Each entry in `inspector.tabs[]` is either a **custom tab** or a +**hide modifier** for a built-in. + +### Custom tab + +```ts @nocheck +{ + id: string, // URL-safe id: /^[A-Za-z0-9_-]+$/ + label: string, // Shown in the tab strip + source: string, // Directory of static assets + icon?: string, // Optional icon id +} +``` + +- **`id`** — used as the URL segment and tab-strip key. Cannot collide + with a built-in id (`workflow`, `database`, `state`, `queue`, + `connections`, `console`). +- **`source`** — directory of static files. The bytes you put there are + the bytes the browser sees. Point it at a Vite/webpack `dist/` and + any framework works (React, Vue, Svelte, vanilla — all fine). +- **`icon`** — one of `workflow`, `database`, `state`, `queue`, `plug`, + `terminal`, `tag`, `logs`. Anything else falls back to a neutral icon. + +### Hide a built-in tab + +```ts @nocheck +{ + id: "workflow" | "database" | "state" | "queue" | "connections" | "console", + hidden: true, +} +``` + +Use this to clean up the strip when the actor doesn't use a given +subsystem — e.g. a counter actor with no queues: + +```ts +inspector: { tabs: [{ id: "queue", hidden: true }] } +``` + +Misconfigurations (missing directory, duplicate id, invalid characters, +empty label) throw at registry construction, so problems show up +immediately. + +## Talking to the dashboard + +The tab loads in an iframe and communicates with the dashboard via +`postMessage`. The contract is small. + +### From the dashboard + +The dashboard sends an `init` message on load and again whenever the +inspector token rotates. Always overwrite the cached token when it +arrives. + +```ts @nocheck +{ + type: "init", + v: 1, + actorId: string, + authToken: string, // Per-actor inspector bearer token + theme?: "light" | "dark", + activeTab?: string, // For multi-view tabs +} +``` + +Multi-view tabs can read the optional `activeTab` field on `init` to +seed their initial sub-view. The dashboard does not send a separate +message when the user switches custom tabs — it navigates the iframe +`src` instead, so the tab reloads and receives a fresh `init`. + +### From the tab + +Send `ready` once your message listener is registered: + +```ts @nocheck +{ type: "ready", v: 1 } +``` + +If a fetch returns 401, the token has rotated. Ask the dashboard for a +fresh one and wait for the next `init` — don't retry with the stale +token: + +```ts @nocheck +{ type: "token-refresh-needed", v: 1 } +``` + +### Security check + +Always reject messages whose `event.origin` doesn't match the +`?shellOrigin=` URL parameter. Without this check, any page that frames +your tab could forge an `init` and feed you a fake token. + +### TypeScript types + +If you build the tab with TypeScript, the message and response types +are exported as types-only: + +## Reading state and calling actions + +The tab can hit any inspector endpoint with the supplied bearer token. +Use relative paths so the tab doesn't need to know the engine origin or +actor id: + +```js +fetch("../../state", { headers: { Authorization: `Bearer ${token}` } }); +fetch("../../action/increment", { method: "POST", headers: { ... }, body: ... }); +fetch("../../rpcs", { headers: { Authorization: `Bearer ${token}` } }); +fetch("../../connections", { headers: { Authorization: `Bearer ${token}` } }); +fetch("../../queue", { headers: { Authorization: `Bearer ${token}` } }); +``` + +The action body shape is `{ args: [...] }` — the array is passed as +positional arguments to the action. + +Full endpoint reference: +[Debugging → Inspector Endpoints](/docs/actors/debugging#inspector-endpoints). + +For high-frequency UIs, prefer the inspector WebSocket +(`/inspector/connect`) over polling. + +## Styling + +A shared stylesheet matching the dashboard's design tokens is served at +`../../tab.css`: + +```html + +``` + +It defines `--rivet-*` tokens for colors, spacing, radius, and +typography, plus sensible defaults so a bare tab looks at home without +custom CSS: + +```css +.my-card { + background: var(--rivet-card); + color: var(--rivet-foreground); + border: 1px solid var(--rivet-border); + border-radius: var(--rivet-radius-md); + padding: var(--rivet-space-4); +} +``` + +Toggle dark mode by adding the `dark` class to `` — the dashboard +sends the active theme in the `init` message. + +Color tokens come in both pre-wrapped (`--rivet-card`) and raw HSL +(`--rivet-card-raw`) forms, so you can compose with alpha: + +```css +.overlay { background: hsl(var(--rivet-background-raw) / 0.6); } +``` + +You're free to skip the stylesheet entirely and bring your own. + +## Security + +The tab runs in an iframe at the engine origin and can call any +inspector endpoint with the supplied token. Treat the bundle like any +author code that ships with your actor: + +- **Don't inline secrets.** The bundle is fetchable by anyone who can + reach the actor. +- **Always validate `event.origin`.** Reject inbound messages from + anywhere other than the dashboard origin. +- **Never retry silently on 401.** Post `token-refresh-needed` and wait + for a fresh `init`. + +## See also + +- [Debugging](/docs/actors/debugging) — full inspector HTTP API +- [Actions](/docs/actors/actions) — actions your tab can invoke +- [State](/docs/actors/state) — state your tab can read +- [`examples/inspector-tabs`](https://github.com/rivet-dev/rivet/tree/main/examples/inspector-tabs) — runnable example + +_Source doc path: /docs/actors/inspector-tabs_ diff --git a/.agents/skills/rivetkit/reference/actors/keys.md b/.agents/skills/rivetkit/reference/actors/keys.md new file mode 100644 index 0000000..b8f1614 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/keys.md @@ -0,0 +1,51 @@ +# Actor Keys + +> Source: `src/content/docs/actors/keys.mdx` +> Canonical URL: https://rivet.dev/docs/actors/keys +> Description: Actor keys uniquely identify actor instances within each actor type. Keys are used for addressing which specific actor to communicate with. + +--- +## Key Format + +Actor keys can be either a string or an array of strings: + +### Compound Keys & User Data + +Array keys are useful when you need compound keys with user-provided data. Using arrays makes adding user data safe by preventing key injection attacks: + +This allows you to create hierarchical addressing schemes and organize actors by multiple dimensions. + +Don't build keys using string interpolation like `"foo:${userId}:bar"` when `userId` contains user data. If a user provides a value containing the delimiter (`:` in this example), it can break your key structure and cause key injection attacks. + +### Omitting Keys + +You can create actors without specifying a key in situations where there is a singleton actor (i.e. only one actor of a given type). For example: + +This pattern should be avoided, since a singleton actor usually means you have a single actor serving all traffic & your application will not scale. See [scaling documentation](/docs/actors/scaling) for more information. + +### Key Uniqueness + +Keys are unique within each actor name. Different actor types can use the same key: + +## Accessing Keys in Metadata + +Access the actor's key within the actor using the [metadata](/docs/actors/metadata) API: + +## Configuration Examples + +### Simple Configuration with Keys + +Use keys to provide basic actor configuration: + +### Complex Configuration with Input + +For more complex configuration, use [input parameters](/docs/actors/input): + +## API Reference + +- [`ActorKey`](/typedoc/types/rivetkit.mod.ActorKey.html) - Key type for actors +- [`ActorQuery`](/typedoc/types/rivetkit.mod.ActorQuery.html) - Query type using keys +- [`GetOptions`](/typedoc/interfaces/rivetkit.client_mod.GetOptions.html) - Options for getting by key +- [`QueryOptions`](/typedoc/interfaces/rivetkit.client_mod.QueryOptions.html) - Options for querying + +_Source doc path: /docs/actors/keys_ diff --git a/.agents/skills/rivetkit/reference/actors/kv.md b/.agents/skills/rivetkit/reference/actors/kv.md new file mode 100644 index 0000000..384769b --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/kv.md @@ -0,0 +1,44 @@ +# Low-Level KV Storage + +> Source: `src/content/docs/actors/kv.mdx` +> Canonical URL: https://rivet.dev/docs/actors/kv +> Description: Use the built-in key-value store on ActorContext for durable string and binary data alongside actor state. + +--- +KV is deprecated. It is a low-level escape hatch kept for backward compatibility. For new actors, prefer [in-memory state](/docs/actors/state) for small serializable values or [SQLite](/docs/actors/sqlite) for larger or queryable data. + +Every Rivet Actor includes a lightweight key-value store on `c.kv`. It is useful for dynamic keys, blobs, or data that does not fit well in structured state. + +If your data has a known schema, prefer [state](/docs/actors/state). KV is best for flexible or user-defined keys. + +## Basic Usage + +Keys and values default to `text`, so you can use strings without extra options. + +## Value Types + +You can store binary values by passing `Uint8Array` or `ArrayBuffer`. Use `type` on both reads and writes to get the right value type: `binary` for `Uint8Array` and `arrayBuffer` for `ArrayBuffer`. + +TypeScript returns a concrete type based on the option you pass in: + +## Key Types + +Keys accept either `string` or `Uint8Array`. String keys are encoded as UTF-8 by default. + +When listing by prefix, you can control how keys are decoded with `keyType`. Returned keys have the prefix removed. + +If you use binary keys, set `keyType: "binary"` so the returned keys stay as `Uint8Array`. + +## Range Operations + +Use `listRange(start, end)` to read an arbitrary half-open range `[start, end)`. Use `deleteRange(start, end)` to clear that same range efficiently. + +## Batch Operations + +KV supports batch operations for efficiency. `batchPut` and `batchGet` work on raw `Uint8Array` keys and values, so encode strings before passing them in. + +## API Reference + +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - `c.kv` is available on the context + +_Source doc path: /docs/actors/kv_ diff --git a/.agents/skills/rivetkit/reference/actors/lifecycle.md b/.agents/skills/rivetkit/reference/actors/lifecycle.md new file mode 100644 index 0000000..89955bb --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/lifecycle.md @@ -0,0 +1,388 @@ +# Lifecycle + +> Source: `src/content/docs/actors/lifecycle.mdx` +> Canonical URL: https://rivet.dev/docs/actors/lifecycle +> Description: Learn about actor lifecycle hooks for initialization, state management, and cleanup. + +--- +# Lifecycle + +Actors follow a well-defined lifecycle with hooks at each stage. Understanding these hooks is essential for proper initialization, state management, and cleanup. + +## Lifecycle + +Actors transition through several states during their lifetime. Each transition triggers specific hooks that let you initialize resources, manage connections, and clean up state. + +``` +Loading ──Start──▶ Ready ──spawn driver──▶ Started + │ + ┌────────────────────────────────────────┤ + │ │ + │ idle timer + can_sleep │ Destroy command + ▼ ▼ + SleepGrace ─── grace window closes ──▶ Destroying + │ │ + ▼ │ + SleepFinalize ──── stop sequence ───────────┤ + ▼ + Terminated +``` + +**On Create** (runs once per actor) + +1. `onMigrate` +2. `createState` +3. `onCreate` +4. `createVars` +5. `onWake` +6. `run` (background, does not block) + +**On Destroy** + +1. `onDestroy` + +**On Wake** (after sleep, restart, or crash) + +1. `onMigrate` +2. `createVars` +3. `onWake` +4. `run` (background, does not block) + +**On Sleep** (after idle period) + +1. Wait for `run` to complete (with timeout) +2. `onSleep` + +**On Connect** (per client) + +1. `onBeforeConnect` +2. `createConnState` +3. `onConnect` + +**On Disconnect** (per client) + +1. `onDisconnect` + +**On Inbound Action Invoke** (per action call) + +1. Action handler executes + +**On Inbound Queue Publish** (per `handle.send(...)`) + +1. `queues..canPublish` (if defined) +2. Queue message is enqueued + +**On Event Subscription Request** (per subscribe request) + +1. `events..canSubscribe` (if defined) +2. Subscription is applied + +## Lifecycle Hooks + +Actor lifecycle hooks are defined as functions in the actor configuration. + +### `state` + +The `state` constant defines the initial state of the actor. See [state documentation](/docs/actors/state) for more information. + +### `onMigrate` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onMigrate` hook runs on every actor start, before `createState`, `onCreate`, `createVars`, and `onWake`. Can be async. It runs early so that database migrations are applied before any other lifecycle hook accesses the database. The second parameter is `true` when the actor is being created for the first time. + +### `createState` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `createState` function dynamically initializes state based on input. Called only once when the actor is first created. Can be async. See [state documentation](/docs/actors/state) for more information. + +### `vars` + +The `vars` constant defines ephemeral variables for the actor. These variables are not persisted and are useful for storing runtime-only data. The value for `vars` must be clonable via `structuredClone`. See [ephemeral variables documentation](/docs/actors/state#ephemeral-variables) for more information. + +### `createVars` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `createVars` function dynamically initializes ephemeral variables. Can be async. Use this when you need to initialize values at runtime. See [ephemeral variables documentation](/docs/actors/state#ephemeral-variables) for more information. + +### `onCreate` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onCreate` hook is called when the actor is first created. Can be async. Use this hook for initialization logic that doesn't affect the initial state. + +### `onDestroy` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onDestroy` hook is called when the actor is being permanently destroyed. Can be async. Use this for final cleanup operations like closing external connections, releasing resources, or performing any last-minute state persistence. + +The actor is still fully functional when `onDestroy` runs. You can access the database, broadcast events, call `waitUntil`, send queue messages, and use `schedule.after`. State mutations made during `onDestroy` are persisted before the actor is torn down. + +### `onWake` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +This hook is called any time the actor is started (e.g. after restarting, upgrading code, or crashing). Can be async. + +This is called after the actor has been initialized but before any connections are accepted. + +Use this hook to set up any resources or start any background tasks, such as `setInterval`. + +### `onSleep` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +This hook is called when the actor is going to sleep. Can be async. Use this to clean up resources, close connections, or perform any shutdown operations. + +The actor is still fully functional when `onSleep` runs. You can access the database, broadcast events, call `waitUntil`, send queue messages, and use `schedule.after`. State mutations made during `onSleep` are persisted before the actor finishes sleeping. + +This hook may not always be called in situations like crashes or forced terminations. Don't rely on it for critical cleanup operations. + +Not supported on Cloudflare Workers. + +### `run` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `run` hook is called after the actor starts and runs in the background without blocking actor startup. This is ideal for long-running background tasks like: + +- Reading from message queues in a loop +- Tick loops for periodic work +- Custom workflow logic +- Background processing + +The handler exposes `c.aborted` for loop checks and `c.abortSignal` for canceling operations when the actor is stopping. You should always check or listen for shutdown to exit gracefully. + +**Important behavior:** +- The actor may go to sleep at any time during the `run` handler. Wrap work that must keep the actor awake with `c.keepAwake(promise)` to block idle sleep until the promise settles. +- If the `run` handler exits (returns), the actor follows its normal idle sleep timeout once it becomes idle +- If the `run` handler throws an error, the actor logs the error and then follows its normal idle sleep timeout once it becomes idle +- On shutdown, `c.abortSignal` fires so the `run` handler can exit within the graceful shutdown window. + +Finite `run` handlers leave the actor alive after they finish. If you want a one shot task to clean itself up when it is done, call `c.destroy()` before returning. + +### `onStateChange` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Called whenever the actor's state changes. Cannot be async. This is often used to broadcast state updates. + +Do not mutate `c.state` inside `onStateChange`; re-entrant state mutation is rejected. + +### `createConnState` and `connState` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +There are two ways to define the initial state for connections: +1. `connState`: Define a constant object that will be used as the initial state for all connections +2. `createConnState`: A function that dynamically creates initial connection state based on connection parameters. Can be async. + +### `onBeforeConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.BeforeConnectContext.html) + +The `onBeforeConnect` hook is called whenever a new client connects to the actor. Can be async. Clients can pass parameters when connecting, accessible via `params`. This hook is used for connection validation and can throw errors to reject connections. + +The `onBeforeConnect` hook does NOT return connection state - it's used solely for validation. + +Connections cannot interact with the actor until this method completes successfully. Throwing an error will abort the connection. This can be used for authentication - see [Authentication](/docs/actors/authentication) for details. + +### `onConnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ConnectContext.html) + +Executed after the client has successfully connected. Can be async. Receives the connection object as a second parameter. + +Messages will not be processed for this actor until this hook succeeds. Errors thrown from this hook will cause the client to disconnect. + +### `canPublish` and `canSubscribe` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Use schema-level hooks to authorize queue publishes and event subscriptions. Both hooks can be async and must return booleans: + +- `queues..canPublish` runs before inbound queue publishes. +- `events..canSubscribe` runs before inbound event subscription requests. + +For actions, enforce authorization directly inside each action handler. + +Use deny-by-default rules for each hook and return `false` unless explicitly allowed. See [Access Control](/docs/actors/access-control) for full guidance. + +### `onDisconnect` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +Called when a client disconnects from the actor. Can be async. Receives the connection object as a second parameter. Use this to clean up any connection-specific resources. + +### `onRequest` + +[API Reference](/typedoc/interfaces/rivetkit.mod.RequestContext.html) + +The `onRequest` hook handles HTTP requests sent to your actor at `/actors/{actorName}/http/*` endpoints. Can be async. It receives the request context and a standard `Request` object, and should return a `Response` object. + +See [Request Handler](/docs/actors/request-handler) for more details. + +### `onWebSocket` + +[API Reference](/typedoc/interfaces/rivetkit.mod.WebSocketContext.html) + +The `onWebSocket` hook handles WebSocket connections to your actor. Can be async. It receives the actor context and a `WebSocket` object. Use this to set up WebSocket event listeners and handle real-time communication. + +See [WebSocket Handler](/docs/actors/websocket-handler) for more details. + +### `onBeforeActionResponse` + +[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) + +The `onBeforeActionResponse` hook is called before sending an action response to the client. Can be async. Use this hook to modify or transform the output of an action before it's sent to the client. This is useful for formatting responses, adding metadata, or applying transformations to the output. + +## Sleeping + +Actors automatically sleep after a period of inactivity to free up resources. When a request arrives for a sleeping actor, it wakes up, restores its state, and handles the request. + +### When Actors Sleep + +#### Idle Timeout + +An actor is considered idle and eligible to sleep when **all** of the following are true: + +- No active HTTP requests +- No active connections (unless they are hibernatable WebSockets) +- No active `run` handler (unless it is waiting on a queue) +- No outstanding `c.keepAwake(promise)` promises +- No pending disconnect callbacks +- No async `onWebSocket` event handlers (eg `open`, `message`, `close`) still running + +Once the actor becomes idle, the sleep timer starts. After `sleepTimeout` (default 30 seconds) of continuous inactivity, the actor begins the sleep process. Any activity resets the timer. + +Outbound requests (e.g. `fetch` calls) do not count as activity and will not keep the actor awake. Wrap them with `c.waitUntil()` if they must complete before the actor sleeps. + +#### Upgrades & Eviction + +The platform may force an actor to migrate to a new machine during version upgrades or when a serverless request is about to timeout. The same [shutdown sequence](#shutdown-sequence) runs, then the actor is rescheduled on a new machine and wakes up with its persisted state. + +Use `onSleep`, `waitUntil`, or `keepAwake` to control the length of the grace period before the actor moves to another machine. + +### Manual Lifecycle Controls + +You can also trigger lifecycle transitions from the Rivet Cloud API. These endpoints are useful for operational workflows, debugging, and forcing an actor to move through the same sleep or reschedule path that the platform would normally trigger. + +```bash +curl -X POST \ + "https://cloud-api.rivet.dev/actors/$ACTOR_ID/sleep?namespace=$NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{}' +``` + +```bash +curl -X POST \ + "https://cloud-api.rivet.dev/actors/$ACTOR_ID/reschedule?namespace=$NAMESPACE" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{}' +``` + +`/sleep` asks the actor to enter the normal sleep shutdown sequence. `/reschedule` asks the platform to allocate the actor again, which is useful after crashes or when you need to force a fresh placement. Both endpoints require the actor ID and namespace. + +### Skip Ready Wait + +The gateway normally holds requests until the actor is ready. The actor is not ready during startup (before `onWake` finishes) or during the sleep grace period (while `onSleep` and `waitUntil` are running). Probes and readiness checks can opt out with `skipReadyWait` to reach the actor's `onRequest` or `onWebSocket` handler in either window. + +See [Skip Ready Wait](/docs/clients/javascript#skip-ready-wait) on the JavaScript client page for usage. + +### Keeping the Actor Awake + +RivetKit gives you two primitives for holding the actor awake across background work. Both take a `Promise` and differ in how they interact with idle sleep and the grace period. + +| Method | Accepts | Blocks idle sleep | Blocks grace finalize | Use case | +| --- | --- | --- | --- | --- | +| `c.keepAwake(promise)` | `Promise` (returns same promise) | Yes | Yes | Critical work that must keep the actor running end to end (for example a turn in a game, an ongoing tool call). | +| `c.waitUntil(promise)` | `Promise` (returns void) | No | Yes | Best-effort finalization work that may complete during the grace window (for example analytics flushes, cleanup writes). | + +`c.keepAwake(promise)` is the preferred primitive for long-running work the actor should not sleep through. It holds a keep-awake counter until the promise settles, which blocks both idle sleep and the grace finalize step. The promise is returned unchanged, so you can `await` it if you need the value. + +`setPreventSleep(enabled)` is deprecated and now a no-op. Wrap the work you want to keep alive with `c.keepAwake(promise)` instead. + +### On Sleep Hook + +The [`onSleep`](#onsleep) hook runs during shutdown for cleanup like clearing intervals or closing connections. It is best-effort and will not run if the actor crashes. + +### Wait Before Sleep + +`c.waitUntil(promise)` registers a background promise that must resolve before the actor finishes sleeping. Use this to flush data or finish in-flight work during shutdown without blocking the main execution flow. + +The actor waits up to `sleepGracePeriod` for graceful sleep work during the [shutdown sequence](#shutdown-sequence). That single budget covers `onSleep`, `waitUntil`, `keepAwake`, async raw WebSocket handlers such as `message` and `close`. By default, this graceful sleep window is 15 seconds total. If the timeout is exceeded, the actor proceeds with sleep anyway. + +### Sleep Timeouts + +| Option | Default | Description | +|--------|---------|-------------| +| `sleepTimeout` | 30 seconds | Time of inactivity before the actor begins sleeping. | +| `sleepGracePeriod` | 15 seconds | Total graceful shutdown window for hooks, `waitUntil`, `keepAwake`, async raw WebSocket handlers, and disconnects. | + +Rivet enforces a hard limit of **30 minutes** for the entire stop process. These can be configured in the [options](#options). + +### WebSocket Hibernation + +WebSocket connections are preserved across sleep cycles by default and transparently migrated to the new actor instance. Client stays connected and sees no interruption. Actor migration is very fast, realtime workloads are not interrupted. + +### Shutdown Sequence + +When an actor sleeps or is destroyed, it enters the graceful shutdown window: + +1. `c.abortSignal` fires and `c.aborted` becomes `true`. New connections and dispatch are rejected. Alarm timeouts are cancelled. On sleep, scheduled events are persisted and will be re-armed when the actor wakes. +2. `onSleep` or `onDestroy` and `onDisconnect` for each closing connection run during the same window. User `waitUntil` promises and async raw WebSocket handlers are drained. Hibernatable WebSocket connections are preserved on sleep and closed on destroy. +3. Once graceful work has completed, state is saved and final cleanup runs. + +The entire window is bounded by `sleepGracePeriod` on both sleep and destroy. Defaults to 15 seconds. If the window is exceeded, the actor proceeds to state save anyway. + +#### Graceful shutdown window + +During steps 1 through 6, the actor is still fully functional. Database access, `broadcast`, `waitUntil`, `queue.send`, and `schedule.after` all work. State mutations are persisted at step 7. Actions invoked by pre-existing connections or lifecycle hooks continue to execute normally. + +New connections and raw WebSocket upgrades are rejected as soon as the shutdown sequence begins. New requests that arrive during shutdown are held until the actor wakes up again. The caller does not need to retry. + +If `schedule.after` is called during shutdown, the event is persisted so it survives the sleep/wake cycle, but no local timeout is scheduled. The event will fire after the actor wakes. + +In-flight actions are **not** waited on during shutdown. If an action must complete before the actor stops, wrap the critical work with `c.waitUntil()`. + +## Options + +The `options` object allows you to configure various timeouts and behaviors for your actor. + +| Option | Default | Description | +|--------|---------|-------------| +| `createVarsTimeout` | 5000ms | Timeout for `createVars` function | +| `createConnStateTimeout` | 5000ms | Timeout for `createConnState` function | +| `onConnectTimeout` | 5000ms | Timeout for `onConnect` hook | +| `sleepGracePeriod` | 15000ms | Total graceful shutdown window for both sleep and destroy | +| `stateSaveInterval` | 1000ms | Interval for persisting state | +| `actionTimeout` | 60000ms | Timeout for action execution | +| `connectionLivenessTimeout` | 2500ms | Timeout for connection liveness check | +| `connectionLivenessInterval` | 5000ms | Interval for connection liveness check | +| `sleepTimeout` | 30000ms | Time before actor sleeps due to inactivity | +| `canHibernateWebSocket` | false | Whether WebSockets can hibernate (experimental) | + +## Advanced + +### Actor Shutdown Abort Signal + +The `c.abortSignal` provides an `AbortSignal` that fires when the actor is stopping, and `c.aborted` is the shorthand boolean for loop checks. Use these to cancel ongoing operations when the actor sleeps or is destroyed. + +The abort signal fires at the very start of the [shutdown sequence](#shutdown-sequence), before `onSleep` or `onDestroy` runs. This means `c.aborted` is already `true` inside those lifecycle hooks. The signal fires early so that the `run` handler can exit promptly, but the actor remains fully functional throughout the graceful shutdown window. + +See [Canceling Long-Running Actions](/docs/actors/actions#canceling-long-running-actions) for manually canceling operations on-demand. + +### Using `ActorContext` Type Externally + +When extracting logic from lifecycle hooks or actions into external functions, you'll often need to define the type of the context parameter. Rivet provides helper types that make it easy to extract and pass these context types to external functions. + +See [Types](/docs/actors/types) for more details on using `ActorContextOf`. + +## Full Example + +_Source doc path: /docs/actors/lifecycle_ diff --git a/.agents/skills/rivetkit/reference/actors/limits.md b/.agents/skills/rivetkit/reference/actors/limits.md new file mode 100644 index 0000000..57d7194 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/limits.md @@ -0,0 +1,169 @@ +# Limits + +> Source: `src/content/docs/actors/limits.mdx` +> Canonical URL: https://rivet.dev/docs/actors/limits +> Description: Limits and constraints for Rivet Actors. + +--- +This page documents the limits for Rivet Actors. + +There are two types of limits: + +- **Soft Limit**: Application-level limit, configurable in RivetKit. These cannot exceed the hard limit. +- **Hard Limit**: Infrastructure-level limit that cannot be configured. + +Soft limits are configured in two places. Registry-level WebSocket message-size limits are passed to `setup`: + +Per-actor limits such as queue sizes and lifecycle timeouts are passed to `actor(...)` via `options`: + +## Limits + +### WebSocket + +These limits affect actions that use `.connect()` and [low-level WebSockets](/docs/actors/websocket-handler). + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max incoming message size | 64 KiB | 32 MiB | Maximum size of incoming WebSocket messages. Soft limit configurable via `maxIncomingMessageSize`; hard limit configurable in self-hosted engine config via `guard.websocket_max_message_size`. | +| Max outgoing message size | 1 MiB | 32 MiB | Maximum size of outgoing WebSocket messages. Soft limit configurable via `maxOutgoingMessageSize`; hard limit configurable in self-hosted engine config via `guard.websocket_max_message_size`. | +| Max WebSocket frame size | — | 32 MiB | Maximum size of a single WebSocket frame accepted by Rivet's transport edge. Configurable in self-hosted engine config via `guard.websocket_max_frame_size`. This is not configurable by browser clients and is not negotiated during the WebSocket handshake. | +| WebSocket open timeout | — | 15 seconds | Time allowed for WebSocket connection to be established, including `onBeforeConnect` and `createConnState` hooks. Connection is closed if exceeded. | +| Message ack timeout | — | 30 seconds | Time allowed for message acknowledgment before connection is closed. Only relevant in the case of a network issue and does not affect your application. | + +### Hibernating WebSocket + +Hibernating WebSockets allow actors to sleep while keeping client connections alive. All WebSocket limits above also apply to hibernating WebSockets. See [WebSocket Hibernation](/docs/actors/websocket-handler#web-socket-hibernation) for details. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max pending buffer size | — | 128 MiB | Total size of all buffered messages per connection while actor is sleeping. | +| Max pending message count | — | 65,535 | Maximum number of buffered messages per connection while actor is sleeping. | +| Hibernation timeout | — | 90 seconds | Maximum time an actor has to wake up before the client is disconnected. Only relevant if something is wrong with starting actors. | + +### HTTP + +These limits affect actions that do not use `.connect()` and [low-level HTTP requests](/docs/actors/request-handler). + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max request body size | — | 20 MiB | Maximum size of HTTP request bodies. | +| Max response body size | — | 20 MiB | Maximum size of HTTP response bodies. | +| Request timeout | 60 seconds | — | Maximum time for an `onRequest` handler to complete. Defaults to `actionTimeout`; configure with `actionTimeout`. | + +### Networking + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Connection ping timeout | — | 30 seconds | Connection is closed if a ping is not acknowledged within this time. Applies to both HTTP and WebSocket. Only relevant in the case of a network issue and does not affect your application. | + +### Queue + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max queue size | 1,000 messages | — | Maximum number of messages in the queue before new messages are rejected. Configurable via `maxQueueSize`. | +| Max queue message size | 64 KiB | 128 KiB (effective) | Maximum size of each individual queue message. Configurable via `maxQueueMessageSize`. Actual payload is slightly lower after queue serialization overhead. | + +### Actor KV Storage + +These limits apply to the low-level KV storage interface powering Rivet Actors. They likely do not affect your application, but are documented for completeness. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max key size | — | 2 KiB | Maximum size of a single key. | +| Max value size | — | 128 KiB | Maximum size of a single value. | +| Max keys per operation | — | 128 | Maximum number of keys in a single batch get/put/delete operation. Does not apply to range operations (`listRange`, `deleteRange`). | +| Max batch put payload size | — | 976 KiB | Maximum total size of all key-value pairs in a single batch put operation. | +| Max storage size per actor | — | 10 GiB | Maximum total KV storage size for a single actor. | +| List default limit | — | 16,384 | Default maximum number of keys returned by a list operation. | + +### Actor SQLite Storage + +These limits apply to the [SQLite database](/docs/actors/state#sqlite-database) available via `this.sql`. SQLite data is stored through the KV layer, so the storage limit is shared with KV storage. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max storage size per actor | — | 10 GiB | Maximum total storage size for a single actor. This limit is shared with KV storage. | +| Max dirty data per commit | — | 1,310,720 bytes | Maximum raw SQLite page data that can be written in a single commit. This is 320 dirty pages at 4 KiB per page. | +| Transaction deadline | 60 seconds | — | Safety backstop for `db.transaction()`. Configure per transaction with `{ timeout: milliseconds }`; there is no product-level maximum. | +| Transaction coordinator queue | — | 128 operations | Maximum admitted SQLite operations waiting behind an active coordinated transaction. Additional operations fail with `sqlite.transaction_queue_full`. | + +SQLite commit deltas are compressed and split into internal chunks before storage, but all chunks for one commit are published atomically. The commit limit is therefore based on raw dirty page bytes before compression, not the compressed delta size. + +Avoid `VACUUM` inside actor databases. It rewrites the database in one transaction and can exceed the dirty-page commit limit even when ordinary incremental writes fit. + +### Actor Runtime Socket + +The experimental [Actor Runtime Socket](/docs/actors/actor-runtime-socket) negotiates its active frame limit during the handshake. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Frame payload size | 32 MiB | — | Default maximum request or response payload. Self-hosted native runtimes can configure `RIVET_ACTOR_RUNTIME_SOCKET_MAX_FRAME_BYTES`; oversized responses return `ResponseTooLarge`. | + +### KV Preloading + +When an actor starts, the engine can pre-fetch KV data declared in the actor name metadata and deliver it alongside the start command. This removes round-trips to storage during actor startup. RivetKit emits the preload manifest from its own key layout and exposes per-actor overrides via `options`. Operators can still enforce a global cap in the [engine config](/docs/self-hosting/configuration) with `pegboard.preload_max_total_bytes`. In serverless mode, this data is serialized into the `/api/rivet/start` request body along with actor config and protocol metadata, so the accepted body size must be larger than the preload budget. RivetKit defaults `serverless.maxStartPayloadBytes` to 16 MiB to leave margin for the default 1 MiB preload budget and larger SQLite startup page preloads. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max total preload size | 1 MiB | — | Maximum total size of all preloaded KV data sent with the start command. Configurable via `pegboard.preload_max_total_bytes`. Setting to 0 disables all preloading. | +| Max workflow preload size | 128 KiB | — | Default maximum size of preloaded workflow data for RivetKit actors. Configurable per actor via `options.preloadMaxWorkflowBytes`. Setting to 0 disables workflow preloading for that actor. | +| Max connections preload size | 64 KiB | — | Default maximum size of preloaded connection data for RivetKit actors. Configurable per actor via `options.preloadMaxConnectionsBytes`. Setting to 0 disables connections preloading for that actor. | + +### Actor Input + +See [Actor Input](/docs/actors/input) for details. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Max actor input size | — | 4 MiB | Maximum size of the input passed when creating an actor. | +| Max connection params size | — | 4 KiB | Maximum size of connection parameters passed when connecting to an actor. | +| Max actor key component size | — | 128 bytes | Maximum size of each component in an actor key array. | +| Max actor key total size | — | 1,024 bytes | Maximum total size of the serialized actor key string. | +| Max actor name length | — | 64 characters | Maximum length for actor and project identifiers. | + +### Rate Limiting + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Rate limit | — | 1200 requests/minute | Default rate limit per actor per IP address with a 1 minute time bucket. | +| Max in-flight requests | — | 32 | Default maximum concurrent requests to an actor per IP address. | + +### Timeouts + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Action timeout | 60 seconds | — | Timeout for RPC actions. Configurable via `actionTimeout`. | +| On request timeout | 60 seconds | — | Timeout for raw `onRequest` handlers. Defaults to `actionTimeout`; configure with `actionTimeout`. | +| On before connect timeout | 5 seconds | — | Timeout for the `onBeforeConnect` hook. Configurable via `onBeforeConnectTimeout`. | +| Create vars timeout | 5 seconds | — | Timeout for `createVars` hook. Configurable via `createVarsTimeout`. | +| Create conn state timeout | 5 seconds | — | Timeout for `createConnState` hook. Configurable via `createConnStateTimeout`. | +| On connect timeout | 5 seconds | — | Timeout for `onConnect` hook. Configurable via `onConnectTimeout`. | +| On migrate timeout | 30 seconds | — | Timeout for `onMigrate` hook. Configurable via `onMigrateTimeout`. | +| Sleep grace period | 15 seconds | — | Total graceful shutdown budget for both sleep and destroy. Covers `onSleep`/`onDestroy`, run handler shutdown, `waitUntil`, `keepAwake`, async raw WebSocket handlers, and connection cleanup. Configurable via `sleepGracePeriod`. | +| Sleep timeout | 30 seconds | — | Time of inactivity before actor hibernates. Configurable via `sleepTimeout`. | +| State save interval | 1 second | — | Interval between automatic state saves. Configurable via `stateSaveInterval`. | +| Connection liveness timeout | 2.5 seconds | — | Time a stateful connection can miss liveness checks before RivetKit treats it as unhealthy. Configurable via `connectionLivenessTimeout`. | +| Connection liveness interval | 5 seconds | — | Interval between stateful connection liveness checks. Configurable via `connectionLivenessInterval`. | + +### Serverless Shutdown + +These timeouts control how actors are shut down when a serverless request reaches its lifespan limit. See [Shutdown Sequence](/docs/general/runtime-modes#shutdown-sequence) for details. + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Request lifespan | 3600 seconds (60 min) | — | Total lifespan of a serverless request before drain begins. Configurable via `requestLifespan` in [`configurePool`](/docs/general/registry-configuration). | +| Runner config drain grace period | — | 30 minutes | Time a serverless runner reserves for actors to stop gracefully. Configurable via `drainGracePeriod` in [`configurePool`](/docs/general/registry-configuration). | +| Engine serverless drain fallback | — | 10 seconds | Engine-level fallback used when no per-runner config applies. Configurable via [engine config](/docs/self-hosting/configuration) (`pegboard.serverless_drain_grace_period`). | + +### Actor Lifecycle + +| Name | Soft Limit | Hard Limit | Description | +|------|------------|------------|-------------| +| Actor start threshold | — | 30 seconds | Maximum time for an actor to start before it is considered lost and rescheduled. | +| Actor stop threshold | — | 30 minutes | Maximum time for an actor to stop before it is considered lost. | + +## Increasing Limits + +These limits are sane defaults designed to protect your application from exploits and accidental runaway bugs. If you have a use case that requires different limits, [contact us](https://rivet.dev/contact) to discuss your requirements. + +_Source doc path: /docs/actors/limits_ diff --git a/.agents/skills/rivetkit/reference/actors/metadata.md b/.agents/skills/rivetkit/reference/actors/metadata.md new file mode 100644 index 0000000..d3dcc24 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/metadata.md @@ -0,0 +1,39 @@ +# Metadata + +> Source: `src/content/docs/actors/metadata.mdx` +> Canonical URL: https://rivet.dev/docs/actors/metadata +> Description: Metadata provides information about the currently running actor. + +--- +## Actor ID + +Get the unique instance ID of the actor: + +## Actor Name + +Get the actor type name: + +This is useful when you need to know which actor type is running, especially if you have generic utility functions that are shared between different actor implementations. + +## Actor Key + +Get the actor key used to identify this actor instance: + +The key is used to route requests to the correct actor instance and can include parameters passed when creating the actor. + +Learn more about using keys for actor addressing and configuration in the [keys documentation](/docs/actors/keys). + +## Region + +Region can be accessed from the context object via `c.region`. + +`c.region` is only supported on Rivet at the moment. + +## Example Usage + +## API Reference + +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining metadata +- [`CreateOptions`](/typedoc/interfaces/rivetkit.client_mod.CreateOptions.html) - Options for creating an actor, including `region` and `input` + +_Source doc path: /docs/actors/metadata_ diff --git a/.agents/skills/rivetkit/reference/actors/queues.md b/.agents/skills/rivetkit/reference/actors/queues.md new file mode 100644 index 0000000..8ebeb7b --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/queues.md @@ -0,0 +1,122 @@ +# Queues & Run Loops + +> Source: `src/content/docs/actors/queues.mdx` +> Canonical URL: https://rivet.dev/docs/actors/queues +> Description: Use actor-local durable queues for serial run loops and request/response workflows. + +--- +## What are queues? + +- **Realtime**: messages are delivered to a live actor as soon as possible. +- **Durable**: messages are persisted and survive actor sleep/restart. +- **Request/response**: clients can wait for a queue completion response. +- **Scalable**: queues absorb large bursts and handle heavy backpressure safely. +- **Local per actor**: each actor instance has its own queue storage (scoped by actor key/id). + +Queues are commonly referred to as "mailboxes" in other actor frameworks. + +For a worked queue-driven pattern, see the cookbook: [AI Agent](/cookbook/ai-agent/). + +## What are queues good for? + +- Great for any task that changes actor state. +- Helps avoid race conditions by handling work in order. +- Makes complex behavior easier to organize. + +## Basic queue + +This is the default pattern. Define queue names in `queues`, process them in `run`, and publish from the client with `handle.send(...)`. + +## Completable messages + +Use this when you want explicit completion/ack semantics but do not need to return data. + +- `message.complete()` resolves a sender waiting on `wait: true` (or `enqueueAndWait`). It does not change durability: messages are removed from queue storage when they are received, not when they are completed. +- If processing fails before `message.complete()`, the message is not redelivered, and any waiting sender times out instead of receiving a completion. +- `status: "timedOut"` means sender timeout elapsed before `message.complete(...)`. + +## Request/reply pattern + +Use this when the sender needs data back from queued work. + +## Queue messages from within an actor + +Queueing is useful from inside actor logic too, not just from clients. + +- Use actions as entrypoints, then enqueue into the run loop to keep mutations serialized. +- You can also call `c.queue.send(...)` from other parts of `run` when needed. +- `c.queue.send(...)` confirms durable enqueue. It does not wait for processing to finish. + +## Defining queue schemas + +You can define queue types with `queue()` or with schema objects. Schema objects support [Standard Schema](https://standardschema.dev/) validators, including [Zod](https://zod.dev/). + +## Pull messages with `next` and `nextBatch` + +Use `next` when you want to wait for one queue message. +Use `nextBatch` when you want to wait for multiple queue messages. + +- Waits until messages are available unless timeout is hit. +- Omit `timeout` to wait indefinitely. + +## Poll messages + +Use `tryNext` when you need one non-blocking read. +Use `tryNextBatch` for non-blocking batch reads. + +- Returns immediately and never waits. + +## Abort signals + +Use `signal` when your receive loop needs external cancellation semantics in addition to actor shutdown behavior. + +## Multiple queues + +Multiple queues let you separate message flows by purpose. By default, receive calls race across all queues when `names` is not specified. In this pattern, prompt messages run through a streaming loop while stop messages act as control signals on a separate receive path. + +Use `iter({ names: ["prompt"] })` as the main stream and `next({ names: ["stop"] })` as a stop signal. + +## Sleeping behavior + +If an actor has a `run` handler, it does not sleep while that handler is actively doing work. It only can sleep when the run loop is blocked waiting for queue entries (for example inside `iter(...)` or `next(...)`). + +This means you can run normal code in `run` without worrying about sleep interrupting it mid-call. + +## Debugging + +- `GET /inspector/queue?limit=50` returns queue size and pending message metadata. +- `GET /inspector/summary` includes `queueSize` for quick queue health checks. +- `POST /queue/:name` with `wait: true` is useful to verify completable/request-response behavior. +- In non-dev mode, inspector endpoints require authorization. + +## Recommendations + +- Actions are for getting data, queue entries are for mutating data. +- Implement connection auth in `onBeforeConnect`. See [Authentication](/docs/actors/authentication). +- Route most state changes through one queue loop so ordering stays predictable. +- If you need more complex multi-step run loops, consider using workflows. +- Use `c.aborted` and `c.abortSignal` for actor shutdown. Use your own `AbortController` for earlier loop cancellation. +- Add `timeout` when callers need bounded wait behavior. +- Use `wait: true` only when the caller actually needs a response. + +## Pitfalls + +### Avoid `wait: true` between actors + +`wait: true` blocks the sender's run loop until the receiver finishes. Between actors, this adds unnecessary overhead and risks deadlocks, especially if the target actor needs to communicate back. If an actor sends a `wait: true` message to *itself*, it is a guaranteed deadlock because the run loop is already busy processing the current message. + +Reserve `wait: true` for external callers (HTTP handlers, CLI tools, client apps). For actor-to-actor communication, send a queue message to the other actor without `wait: true`, then have that actor send a queue message back when the work is done. + +## Tips + +### Message TTL + +Every queue message includes a `createdAt` timestamp. Use this to skip or discard stale messages in your run loop: + +### Delayed delivery + +Use [`c.schedule`](/docs/actors/schedule) to enqueue messages at a future time instead of processing them immediately: + +See [Schedule](/docs/actors/schedule) for the full scheduling API. + +_Source doc path: /docs/actors/queues_ diff --git a/.agents/skills/rivetkit/reference/actors/quickstart/backend.md b/.agents/skills/rivetkit/reference/actors/quickstart/backend.md new file mode 100644 index 0000000..86cbdf2 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/quickstart/backend.md @@ -0,0 +1,64 @@ +# Node.js & Bun Quickstart + +> Source: `src/content/docs/actors/quickstart/backend.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/backend +> Description: Get started with Rivet Actors in Node.js and Bun + +--- +Prefer to start from a complete project? See the runnable [`hello-world`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world) example. + +## Steps + +### Add Rivet Skill to Coding Agent (Optional) + +If you're using an AI coding assistant (like Claude Code, Cursor, Windsurf, etc.), add Rivet skills for enhanced development assistance: + +```sh +npx skills add rivet-dev/skills +``` + +### Install Rivet + +```sh +npm install rivetkit +``` + +### Create Actors and Start Server + +Create a file with your actors, set up the registry, and start the server: + +### Run Server + +```sh Node.js +npx tsx --watch index.ts +``` + +```sh Bun +bun --watch index.ts +``` + +```sh Deno +deno run --allow-net --allow-read --allow-env --watch index.ts +``` + +Your server is now running on `http://localhost:6420`. Clients connect directly to the Rivet Engine on this port. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend: + +### TypeScript + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### React + +See the [React documentation](/docs/clients/react) for more information. + +### Deploy + +## Configuration Options + +_Source doc path: /docs/actors/quickstart/backend_ diff --git a/.agents/skills/rivetkit/reference/actors/quickstart/cloudflare.md b/.agents/skills/rivetkit/reference/actors/quickstart/cloudflare.md new file mode 100644 index 0000000..e39cbe4 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/quickstart/cloudflare.md @@ -0,0 +1,165 @@ +# Cloudflare Workers Quickstart + +> Source: `src/content/docs/actors/quickstart/cloudflare.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/cloudflare +> Description: Set up a Rivet project locally targeting Cloudflare Workers. + +--- +Set up a Rivet project locally that runs on Cloudflare Workers. The `@rivetkit/cloudflare-workers` package wires the WebAssembly runtime for you. + +Prefer to start from a complete project? See the runnable [`hello-world-cloudflare-workers`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-cloudflare-workers) example (with [Hono](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-cloudflare-workers-hono) and [raw router](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-cloudflare-workers-raw) variants). + +## Steps + +### Install Packages + +```sh +npm install rivetkit @rivetkit/cloudflare-workers +npm install --save-dev wrangler +``` + +### Configure Wrangler + +```toml wrangler.toml +name = "rivetkit-cloudflare" +main = "src/index.ts" +compatibility_date = "2025-04-01" +compatibility_flags = ["nodejs_compat"] +``` + +The `nodejs_compat` flag is required so the runtime can read its connection config from `process.env`. + +### Create the Worker + +`createHandler` serves the Rivet manager API on `/api/rivet`. Pick how you want to handle your own routes: + +- **Default**: Rivet handles everything. +- **Hono**: Mount a [Hono](https://hono.dev) app for your routes (`npm install hono`). +- **Raw**: Provide a `fetch` and route requests yourself. + +```ts Default @nocheck +import { actor } from "rivetkit"; +import { createHandler } from "@rivetkit/cloudflare-workers"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +export default createHandler({ use: { counter } }); +``` + +```ts Hono @nocheck +import { actor } from "rivetkit"; +import { createClient } from "rivetkit/client"; +import { createHandler, setup } from "@rivetkit/cloudflare-workers"; +import { Hono } from "hono"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +// `setup` returns a typed registry, so the client below is fully typed. +const registry = setup({ use: { counter } }); + +const app = new Hono(); + +app.get("/", (c) => c.text("Hello from Hono + Rivet Actors!")); + +app.post("/increment/:name", async (c) => { + // `createClient` reads RIVET_ENDPOINT from the environment (passed by `rivet + // dev`, or set as a Worker secret in production). + const client = createClient(); + const count = await client.counter.getOrCreate(c.req.param("name")).increment(1); + return c.json({ count }); +}); + +// Rivet keeps `/api/rivet`; Hono handles everything else. +export default createHandler(registry, { fetch: app.fetch }); +``` + +```ts Raw @nocheck +import { actor } from "rivetkit"; +import { createClient } from "rivetkit/client"; +import { createHandler, setup } from "@rivetkit/cloudflare-workers"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +// `setup` returns a typed registry, so the client below is fully typed. +const registry = setup({ use: { counter } }); + +// Rivet keeps `/api/rivet`; your `fetch` handles everything else. +export default createHandler(registry, { + fetch: async (request: Request) => { + const url = new URL(request.url); + + if (url.pathname === "/") { + return new Response("Hello from a raw Rivet Worker router!"); + } + + const increment = url.pathname.match(/^\/increment\/(.+)$/); + if (request.method === "POST" && increment) { + // `createClient` reads RIVET_ENDPOINT from the environment (passed by + // `rivet dev`, or set as a Worker secret in production). + const client = createClient(); + const count = await client.counter.getOrCreate(increment[1]).increment(1); + return Response.json({ count }); + } + + return new Response("Not found", { status: 404 }); + }, +}); +``` + +### Run Locally + +Start Rivet. The CLI runs the local engine and spawns `wrangler dev` for you: + +```sh +npx @rivetkit/cli dev --provider cloudflare +``` + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend. It connects directly to the local engine on `http://localhost:6420`: + +### TypeScript + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### React + +See the [React documentation](/docs/clients/react) for more information. + +### Deploy + +Ready to ship? See [Deploying to Cloudflare Workers](/docs/deploy/cloudflare). + +## Related + +- [Quickstart](/docs/actors/quickstart) +- [Deploying to Cloudflare Workers](/docs/deploy/cloudflare) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/actors/quickstart/cloudflare_ diff --git a/.agents/skills/rivetkit/reference/actors/quickstart/effect.md b/.agents/skills/rivetkit/reference/actors/quickstart/effect.md new file mode 100644 index 0000000..fc252e9 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/quickstart/effect.md @@ -0,0 +1,239 @@ +# Effect.ts Quickstart (Beta) + +> Source: `src/content/docs/actors/quickstart/effect.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/effect +> Description: Build a Rivet Actor with the Effect SDK + +--- +Effect support is in beta. The `@rivetkit/effect` API may change between releases. See the [`hello-world-effect`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-effect) and [`chat-room-effect`](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room-effect) examples for complete runnable projects. + +## Steps + +### Install Rivet + +Add `rivetkit`, the Effect SDK, and its Effect peers: + +```sh +npm install rivetkit @rivetkit/effect effect @effect/platform-node +``` + +### Define Your Actor + +Split each actor into a public contract and a server-only implementation so the contract can be imported from client code without leaking server details. + +The contract declares the actor and its actions. Actions are standalone values with explicit [`effect/Schema`](https://effect.website/docs/schema/introduction/) payloads and successes, validated end to end: + +```ts src/actors/counter/api.ts @nocheck +import { Action, Actor } from "@rivetkit/effect"; +import { Schema } from "effect"; + +export const Increment = Action.make("Increment", { + payload: { amount: Schema.Number }, + success: Schema.Number, +}); + +export const GetCount = Action.make("GetCount", { + success: Schema.Number, +}); + +export const Counter = Actor.make("Counter", { + actions: [Increment, GetCount], +}); +``` + +The implementation registers the actor with `.toLayer`. The wake function runs once when the actor awakes and returns the action handlers. Persisted state is accessed through a `SubscriptionRef`-like `State` API: + +```ts src/actors/counter/live.ts @nocheck +import { Actor, State } from "@rivetkit/effect"; +import { Effect, Schema } from "effect"; +import { Counter } from "./api.ts"; + +export const CounterLive = Counter.toLayer( + Effect.fnUntraced(function* ({ rawRivetkitContext, state }) { + return Counter.of({ + Increment: Effect.fnUntraced(function* ({ payload }) { + const next = yield* State.updateAndGet(state, (current) => ({ + count: current.count + payload.amount, + })).pipe(Effect.orDie); + + // Broadcast the new value to every connected client. + rawRivetkitContext.broadcast("newCount", next.count); + + return next.count; + }), + GetCount: () => + State.get(state).pipe( + Effect.map((current) => current.count), + Effect.orDie, + ), + }); + }), + { + state: { + schema: Schema.Struct({ count: Schema.Number }), + initialValue: () => ({ count: 0 }), + }, + name: "Counter", + icon: "calculator", + }, +); +``` + +### Serve The Registry + +Compose the actor layers and serve them with `Registry.serve`. `Registry.layer()` reads engine config from the environment, and the actor layer is provided a `Client` so actors can call other actors: + +```ts src/main.ts @nocheck +import { NodeRuntime } from "@effect/platform-node"; +import { Client, Registry } from "@rivetkit/effect"; +import { Layer } from "effect"; +import { CounterLive } from "./actors/counter/live.ts"; + +const endpoint = process.env.RIVET_ENDPOINT ?? "http://127.0.0.1:6420"; + +const ActorsLayer = CounterLive.pipe(Layer.provide(Client.layer({ endpoint }))); + +const MainLayer = Registry.serve(ActorsLayer).pipe(Layer.provide(Registry.layer())); + +// Keeps the layer alive. Tears down on SIGINT/SIGTERM. +Layer.launch(MainLayer).pipe(NodeRuntime.runMain); +``` + +### Run The Server + +Set `RIVET_RUN_ENGINE=1` to spawn a local Rivet Engine alongside the server. The engine binary is downloaded and cached the first time you run, so there is nothing else to install: + +```sh +RIVET_RUN_ENGINE=1 npx tsx --watch src/main.ts +``` + +Your server now connects to the Rivet Engine on `http://localhost:6420`. Clients connect directly to the engine on this port. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +To point at a remote engine instead, set `RIVET_ENDPOINT=https://...` and omit `RIVET_RUN_ENGINE`. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend: + +### Effect + +The Effect client imports the same actor contract from your registry. `Counter.client` yields a typed accessor backed by the client layer: + +```ts src/client.ts @nocheck +import { NodeRuntime } from "@effect/platform-node"; +import { Client } from "@rivetkit/effect"; +import { Effect } from "effect"; +import { Counter } from "./actors/counter/api.ts"; + +const program = Effect.gen(function* () { + const counter = (yield* Counter.client).getOrCreate("my-counter"); + + const count = yield* counter.Increment({ amount: 3 }); + yield* Effect.log(`New count: ${count}`); + + const total = yield* counter.GetCount(); + yield* Effect.log(`Total: ${total}`); +}); + +const ClientLayer = Client.layer({ endpoint: "http://localhost:6420" }); + +program.pipe(Effect.provide(ClientLayer), NodeRuntime.runMain); +``` + +With the server still running, start the client in another terminal: + +```sh +npx tsx src/client.ts +``` + +See the [`chat-room-effect`](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room-effect) example for a larger project with typed errors and actor-to-actor calls. + +### TypeScript + +A plain RivetKit client can call your Effect actor by name through the same engine. Actor and action names are resolved at runtime, so the client is untyped here: + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient("http://localhost:6420"); + +const counter = client.Counter.getOrCreate(["my-counter"]); + +const count = await counter.Increment({ amount: 3 }); +console.log("New count:", count); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### Deploy + +## Feature Support + +The Effect SDK wraps the most common actor features with typed, schema-validated APIs. Everything else is still fully usable through the raw RivetKit context (see [Raw Escape Hatch](#raw-escape-hatch) below), so no feature is off limits, it just isn't typed yet. + +| Feature | Effect-native API | Access | +| --- | --- | --- | +| Actor contract & actions | `Actor.make`, `Action.make` | Typed | +| Persisted state | `State.get` / `set` / `update` / `updateAndGet` / `changes` | Typed | +| Typed client | `Actor.client`, `Client.layer` | Typed | +| Typed errors | `RivetError` | Typed | +| Logging | `RivetLogger` | Typed | +| Sleep request | `Actor.Sleep` | Typed | +| Actor address (`actorId` / `name` / `key`) | `Actor.CurrentAddress` | Typed | +| Registry serve / test / web handler | `Registry` | Typed | +| [Events & broadcast](/docs/actors/events) | Not yet wrapped | `rawRivetkitContext.broadcast(...)` | +| [Schedule](/docs/actors/schedule) | Not yet wrapped | `rawRivetkitContext.schedule.*` | +| [Embedded SQLite](/docs/actors/sqlite) | Not yet wrapped | `rawRivetkitContext.db.execute(...)` | +| [Destroy](/docs/actors/lifecycle) | Not yet wrapped | `rawRivetkitContext.destroy()` | +| Queues, connections, vars, alarms | Not yet wrapped | `rawRivetkitContext.*` | +| Lifecycle hooks (`onSleep` / `onDestroy`) | Not yet wrapped | `rawRivetkitContext.*` | +| Raw HTTP / WebSocket handlers | Not yet wrapped | `rawRivetkitContext.*` | + +### Raw Escape Hatch + +Every wake function receives `rawRivetkitContext`, the underlying RivetKit [actor context](/docs/actors). Reach for it to use any feature that does not have a typed wrapper yet. The typed `state` argument and the raw context point at the same actor, so you can mix both: + +```ts src/actors/counter/live.ts @nocheck +export const CounterLive = Counter.toLayer( + Effect.fnUntraced(function* ({ rawRivetkitContext, state }) { + return Counter.of({ + Increment: Effect.fnUntraced(function* ({ payload }) { + // Typed state wrapper + const next = yield* State.updateAndGet(state, (current) => ({ + count: current.count + payload.amount, + })).pipe(Effect.orDie); + + // Untyped features run through the raw context + rawRivetkitContext.broadcast("newCount", next.count); + rawRivetkitContext.schedule.after(1_000, "tick", {}); + + return next.count; + }), + }); + }), + { + state: { + schema: Schema.Struct({ count: Schema.Number }), + initialValue: () => ({ count: 0 }), + }, + name: "Counter", + }, +); +``` + +Calls through `rawRivetkitContext` are not validated by `effect/Schema` and their payloads are typed as they are in the base RivetKit API. + +## Next Steps + + +- [Actions](/docs/actors/actions) — Define the RPC surface clients call on your actor. + + +- [State](/docs/actors/state) — Persist and load actor state across sleeps and restarts. + + +- [Events](/docs/actors/events) — Broadcast realtime updates to connected clients. + +_Source doc path: /docs/actors/quickstart/effect_ diff --git a/.agents/skills/rivetkit/reference/actors/quickstart/next-js.md b/.agents/skills/rivetkit/reference/actors/quickstart/next-js.md new file mode 100644 index 0000000..f621606 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/quickstart/next-js.md @@ -0,0 +1,117 @@ +# Next.js Quickstart + +> Source: `src/content/docs/actors/quickstart/next-js.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/next-js +> Description: Get started with Rivet Actors in Next.js + +--- +### Add Rivet Skill to Coding Agent (Optional) + +If you're using an AI coding assistant (like Claude Code, Cursor, Windsurf, etc.), add Rivet skills for enhanced development assistance: + +```sh +npx skills add rivet-dev/skills +``` + +### Create a Next.js App + +```sh +npx create-next-app@latest my-app +cd my-app +``` + +### Install RivetKit + +### Create an Actor + +Create a file at `src/rivet/registry.ts` with a simple counter actor: + +### Setup Rivet API route + +Create a file at `src/app/api/rivet/[...all]/route.ts` to setup the API routes: + +```ts src/app/api/rivet/[...all]/route.ts @nocheck +import { toNextHandler } from "@rivetkit/next-js"; +import { registry } from "@/rivet/registry"; + +export const maxDuration = 300; + +export const { GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS } = toNextHandler(registry); +``` + +### Use the Actor in a component + +Create a Counter component and add it to your page: + +```tsx src/components/Counter.tsx @nocheck +"use client"; + +import { createRivetKit } from "@rivetkit/next-js/client"; +import type { registry } from "@/rivet/registry"; +import { useState } from "react"; + +export const { useActor } = createRivetKit({ + endpoint: + process.env.NEXT_PUBLIC_RIVET_ENDPOINT ?? "http://localhost:3000/api/rivet", + namespace: process.env.NEXT_PUBLIC_RIVET_NAMESPACE, + token: process.env.NEXT_PUBLIC_RIVET_TOKEN, +}); + +export function Counter() { + const [count, setCount] = useState(0); + + // Get or create a counter actor for the key "my-counter" + const counter = useActor({ + name: "counter", + key: ["my-counter"] + }); + + // Listen to realtime events + counter.useEvent("newCount", (x: number) => setCount(x)); + + const increment = async () => { + // Call actions + await counter.connection?.increment(1); + }; + + return ( +
+

Count: {count}

+ +
+ ); +} +``` + +```tsx src/app/page.tsx @nocheck +import { Counter } from "@/components/Counter"; + +export default function Home() { + return ( +
+

My App

+ +
+ ); +} +``` + +For information about the Next.js client API, see the [React Client API Reference](/docs/clients/react). + +### Run Locally + +Start the Next.js dev server. Rivet auto-starts a local engine alongside it: + +```sh +npm run dev +``` + +Open `http://localhost:3000` in your browser to use the app. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Deploy to Vercel + +See the [Vercel deployment guide](/docs/deploy/vercel) for detailed instructions on deploying your Rivet app to Vercel. + +_Source doc path: /docs/actors/quickstart/next-js_ diff --git a/.agents/skills/rivetkit/reference/actors/quickstart/react.md b/.agents/skills/rivetkit/reference/actors/quickstart/react.md new file mode 100644 index 0000000..8722fed --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/quickstart/react.md @@ -0,0 +1,82 @@ +# React Quickstart + +> Source: `src/content/docs/actors/quickstart/react.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/react +> Description: Build realtime React applications with Rivet Actors + +--- +## Steps + +### Add Rivet Skill to Coding Agent (Optional) + +If you're using an AI coding assistant (like Claude Code, Cursor, Windsurf, etc.), add Rivet skills for enhanced development assistance: + +```sh +npx skills add rivet-dev/skills +``` + +### Install Dependencies + +```sh +npm install rivetkit @rivetkit/react +``` + +### Create Backend Actor and Start Server + +Create your actor registry on the backend and start the server: + +### Create React Frontend + +Set up your React application: + +For detailed information about the React client API, see the [React Client API Reference](/docs/clients/react). + +### Setup Vite Configuration + +Configure Vite for development: + +```ts vite.config.ts @nocheck +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [react()], + server: { + port: 5173, + }, +}) +``` + +### Run Your Application + +Start both the backend and frontend: + +**Terminal 1**: Start the backend + +```sh Node.js +npx tsx --watch backend/index.ts +``` + +```sh Bun +bun --watch backend/index.ts +``` + +```sh Deno +deno run --allow-net --allow-read --allow-env --watch backend/index.ts +``` + +**Terminal 2**: Start the frontend + +```sh Frontend +npx vite +``` + +Open `http://localhost:5173` in your browser. Try opening multiple tabs to see realtime sync in action. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Deploy + +## Configuration Options + +_Source doc path: /docs/actors/quickstart/react_ diff --git a/.agents/skills/rivetkit/reference/actors/quickstart/rust.md b/.agents/skills/rivetkit/reference/actors/quickstart/rust.md new file mode 100644 index 0000000..1e55471 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/quickstart/rust.md @@ -0,0 +1,249 @@ +# Rust Quickstart (Beta) + +> Source: `src/content/docs/actors/quickstart/rust.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/rust +> Description: Build a Rivet Actor in Rust + +--- +Rust support is in beta. The supported public Rust API is `rivetkit` and `rivetkit-client`; lower-level crates are internal implementation details and do not carry a stability guarantee. See the full API reference on [docs.rs/rivetkit](https://docs.rs/rivetkit), or the runnable [`hello-world-rust`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-rust) example. + +## Steps + +### Add Rivet + +Add the `rivetkit` crate and its companions: + +```sh +cargo add rivetkit anyhow async-trait +cargo add serde --features derive +cargo add tokio --features full +``` + +### Define Your Actor + +Put the actor in `src/lib.rs` so both your server and your client can share the same types. An actor is a type that implements `Actor`, plus one `Handles` implementation for each action. Persisted state lives in `type State`; ephemeral runtime state is just fields on your actor struct. + +```rust src/lib.rs +use std::{future::Future, pin::Pin, sync::Arc}; + +use async_trait::async_trait; +use rivetkit::prelude::*; +use serde::{Deserialize, Serialize}; + +type BoxFuture = Pin> + Send>>; + +pub struct Counter; + +#[derive(Default, Serialize, Deserialize)] +pub struct CounterState { + pub count: i64, +} + +#[derive(Serialize, Deserialize)] +pub struct Increment { + pub amount: i64, +} + +impl Action for Increment { + type Output = i64; + + const NAME: &'static str = "increment"; +} + +#[derive(Serialize, Deserialize)] +pub struct NewCount { + pub count: i64, +} + +impl Event for NewCount { + const NAME: &'static str = "newCount"; +} + +#[async_trait] +impl Actor for Counter { + type State = CounterState; + type Input = (); + type Actions = (Increment,); + type Events = (NewCount,); + type Queue = (); + type ConnParams = (); + type ConnState = (); + type Action = action::Raw; + + async fn create_state(_ctx: &Ctx, _input: Self::Input) -> Result { + Ok(CounterState::default()) + } + + async fn create(_ctx: &Ctx) -> Result { + Ok(Self) + } +} + +impl Handles for Counter { + type Future = BoxFuture; + + fn handle(self: Arc, ctx: Ctx, action: Increment) -> Self::Future { + Box::pin(async move { + let count = { + let mut state = ctx.state_mut(); + state.count += action.amount; + state.count + }; + ctx.emit(NewCount { count })?; + Ok(count) + }) + } +} + +pub fn registry() -> Registry { + let mut registry = Registry::new(); + registry.register_actor::("counter"); + registry +} +``` + +### Serve The Registry + +Your `src/main.rs` just starts the registry from the library: + +```rust src/main.rs +#[tokio::main] +async fn main() -> anyhow::Result<()> { + counter::registry().start().await +} +``` + +Replace `counter` with your crate name (the package `name` in `Cargo.toml`, with dashes as underscores). + +### Run The Server + +The Rust runtime connects to the Rivet Engine. Setting `RIVETKIT_ENGINE_AUTO_DOWNLOAD=1` lets the runtime download and cache a matching engine binary the first time you run, so there is nothing else to install: + +```sh +RIVETKIT_ENGINE_AUTO_DOWNLOAD=1 cargo run +``` + +Your server now connects to the Rivet Engine on `http://localhost:6420`. Clients connect directly to the engine on this port. + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +Already have an engine binary? Set `RIVET_ENGINE_BINARY_PATH=/path/to/rivet-engine` to point at it instead. If you are working inside the [Rivet monorepo](https://github.com/rivet-dev/rivet), a local `cargo build -p rivet-engine` is discovered automatically from `target/debug`. + +### Connect To The Rivet Actor + +This code can run either in your frontend or within your backend: + +### Rust + +Add a `src/bin/client.rs` that imports the same actor types from your library. There is no need to redefine the actor on the client. + +```rust src/bin/client.rs +use counter::{Counter, Increment, NewCount}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + let count = counter.send(Increment { amount: 3 }).await?; + println!("New count: {count}"); + + let connection = counter.connect(); + connection + .on::(|event| println!("Count changed: {}", event.count)) + .await; + connection.send(Increment { amount: 1 }).await?; + + Ok(()) +} +``` + +With the server still running, start the client in another terminal: + +```sh +cargo run --bin client +``` + +See the [`hello-world-rust`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-rust) example for a complete runnable counter. + +### TypeScript + +A TypeScript client can call your Rust actor by name through the same engine. Actor and action names are resolved at runtime, so the client is untyped here: + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient("http://localhost:6420"); + +const counter = client.counter.getOrCreate(["my-counter"]); + +const counterConnection = counter.connect(); +counterConnection.on("newCount", (event) => { + console.log("Event count:", event.count); +}); + +const count = await counterConnection.increment(3); +console.log("New count:", count); + +await counterConnection.increment(1); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### React + +```tsx Counter.tsx @nocheck +import { createRivetKit } from "@rivetkit/react"; +import { useState } from "react"; + +const { useActor } = createRivetKit("http://localhost:6420"); + +function Counter() { + const [count, setCount] = useState(0); + + const counter = useActor({ + name: "counter", + key: ["my-counter"], + }); + + const increment = async () => { + await counter.connection?.increment(1); + }; + + counter.useEvent("newCount", (event) => { + setCount(event.count); + }); + + return ( +
+

Count: {count}

+ +
+ ); +} +``` + +See the [React documentation](/docs/clients/react) for more information. + +### Deploy + +## Next Steps + + +- [API Reference](https://docs.rs/rivetkit) — Full `rivetkit` crate documentation on docs.rs. + + +- [Actions](/docs/actors/actions) — Define the RPC surface clients call on your actor. + + +- [State](/docs/actors/state) — Persist and load actor state across sleeps and restarts. + + +- [Events](/docs/actors/events) — Broadcast realtime updates to connected clients. + +_Source doc path: /docs/actors/quickstart/rust_ diff --git a/.agents/skills/rivetkit/reference/actors/quickstart/supabase.md b/.agents/skills/rivetkit/reference/actors/quickstart/supabase.md new file mode 100644 index 0000000..20b59d0 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/quickstart/supabase.md @@ -0,0 +1,109 @@ +# Supabase Functions Quickstart + +> Source: `src/content/docs/actors/quickstart/supabase.mdx` +> Canonical URL: https://rivet.dev/docs/actors/quickstart/supabase +> Description: Set up a Rivet project locally targeting Supabase Edge Functions. + +--- +Set up a Rivet project locally that runs on Supabase Edge Functions. The `@rivetkit/supabase` package wires the WebAssembly runtime for you. + +Prefer to start from a complete project? See the runnable [`hello-world-supabase-functions`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-supabase-functions) example. + +## Steps + +### Prerequisites + +- [Node.js](https://nodejs.org/) +- [Supabase CLI](https://supabase.com/docs/guides/cli) +- Docker, for Supabase's local Edge Runtime + +The CLI runs the local Rivet engine as a bundled native binary, so Docker is only needed for Supabase itself. A Supabase project is only needed to deploy. + +### Create the Function + +```sh +npx supabase functions new rivet +``` + +Add the packages used by the function: + +```sh +npm install rivetkit @rivetkit/supabase +``` + +### Configure the Function + +Call `serve` from `@rivetkit/supabase`. It loads the WebAssembly runtime and serves the Rivet handler. + +```ts supabase/functions/rivet/index.ts @nocheck +import { actor } from "rivetkit"; +import { serve, setup } from "@rivetkit/supabase"; + +const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, amount = 1) => { + c.state.count += amount; + return c.state.count; + }, + }, +}); + +// `setup` returns a typed registry, so a client can type itself with +// `typeof registry`. +export const registry = setup({ use: { counter } }); + +await serve(registry); +``` + +Add a `deno.json` next to the function so the deploy bundles only the WebAssembly runtime. It points `rivetkit` at the pre-bundled `@rivetkit/supabase`, keeping the deploy small. Without it, the deploy pulls Rivet's native engine and 413s. + +```json supabase/functions/rivet/deno.json +{ + "imports": { + "rivetkit": "npm:@rivetkit/supabase", + "@rivetkit/supabase": "npm:@rivetkit/supabase" + } +} +``` + +Your function code keeps importing from `rivetkit` as usual. The import map only changes how Deno resolves it at bundle time. + +### Run Locally + +Start Rivet. The CLI runs the local engine, spawns `supabase functions serve` for you, and populates the connection values: + +```sh +npx @rivetkit/cli dev --provider supabase +``` + +Visit [http://localhost:6420](http://localhost:6420) in your browser (or point your AI agent at it) to open the Rivet developer tools and inspect your actors live. + +### Call the Actor + +Connect to your actor from a client. This connects directly to the local engine on `http://localhost:6420`: + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./supabase/functions/rivet/index"; + +const client = createClient("http://localhost:6420"); + +const counter = client.counter.getOrCreate(["my-counter"]); +const count = await counter.increment(3); +console.log("New count:", count); +``` + +See the [JavaScript client documentation](/docs/clients/javascript) for more information. + +### Deploy + +Ready to ship? See [Deploying to Supabase Functions](/docs/deploy/supabase). + +## Related + +- [Quickstart](/docs/actors/quickstart) +- [Deploying to Supabase Functions](/docs/deploy/supabase) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/actors/quickstart/supabase_ diff --git a/.agents/skills/rivetkit/reference/actors/request-handler.md b/.agents/skills/rivetkit/reference/actors/request-handler.md new file mode 100644 index 0000000..0536b9c --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/request-handler.md @@ -0,0 +1,79 @@ +# Low-Level HTTP Request Handler + +> Source: `src/content/docs/actors/request-handler.mdx` +> Canonical URL: https://rivet.dev/docs/actors/request-handler +> Description: Actors can handle HTTP requests through the `onRequest` handler. + +--- +For most use cases, [actions](/docs/actors/actions) provide high-level API powered by HTTP that's easier to work with than low-level HTTP. However, low-level handlers are required when implementing custom use cases or integrating external libraries that need direct access to the underlying HTTP `Request`/`Response` objects or WebSocket connections. + +## Handling HTTP Requests + +The `onRequest` handler processes HTTP requests sent to your actor. It receives the actor context and a standard `Request` object and returns a `Response` object. + +### Raw HTTP + +### Hono + +See also the [raw fetch handler example](https://github.com/rivet-dev/rivet/tree/main/examples/raw-fetch-handler). + +## Sending Requests To Actors + +### Via RivetKit Client + +Use the `.fetch()` method on an actor handle to send HTTP requests to the actor's `onRequest` handler. This can be executed from either your frontend or backend. + +### Via getGatewayUrl + +Use `.getGatewayUrl()` to get the raw gateway URL for the actor. This is useful when you need to use the URL with external tools or custom HTTP clients. + +### Via HTTP API + +This handler can be accessed with raw HTTP using `https://api.rivet.dev/gateway/{actorId}/request/{...path}`. + +For example, to call `POST /increment` on the counter actor above: + +```bash +curl -X POST "https://api.rivet.dev/gateway/{actorId}/request/increment" \ + -H "x-rivet-token: {token}" +``` + +The request is routed to the actor's `onRequest` handler where: + +- `request.method` is `"POST"` +- `request.url` ends with `/increment` (the path after `/request/`) +- Headers, body, and other request properties are passed through unchanged + +See the [HTTP API reference](/docs/actors/http-api) for more information on HTTP routing and authentication. + +### Via Proxying Requests + +You can proxy HTTP requests from your own server to actor handlers using the RivetKit client. This is useful when you need to add custom authentication, rate limiting, or request transformation before forwarding to actors. + +## Connection & Lifecycle Hooks + +`onRequest` will trigger the `onBeforeConnect`, `onConnect`, and `onDisconnect` hooks. Read more about [lifecycle hooks](/docs/actors/lifecycle). + +Requests in flight will be listed in `c.conns`. Read more about [connections](/docs/actors/connections). + +## WinterTC Compliance + +The `onRequest` handler is WinterTC compliant and will work with existing libraries using the standard `Request` and `Response` types. + +## Limitations + +- Does not support streaming responses & server-sent events at the moment. See the [tracking issue](https://github.com/rivet-dev/rivet/issues/3529). +- `OPTIONS` requests currently are handled by Rivet and are not passed to `onRequest` + +## Advanced + +### Skip Ready Wait + +Requests are normally held at the gateway until the actor is ready. Pass `skipReadyWait: true` on `handle.fetch()` to deliver immediately, including while the actor is still starting or in the [sleep grace period](/docs/actors/lifecycle#shutdown-sequence). See [Skip Ready Wait](/docs/clients/javascript#skip-ready-wait) for details. + +## API Reference + +- [`RequestContext`](/typedoc/interfaces/rivetkit.mod.RequestContext.html) - Context for HTTP request handlers +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining request handlers + +_Source doc path: /docs/actors/request-handler_ diff --git a/.agents/skills/rivetkit/reference/actors/scaling.md b/.agents/skills/rivetkit/reference/actors/scaling.md new file mode 100644 index 0000000..b597115 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/scaling.md @@ -0,0 +1,10 @@ +# Scaling & Concurrency + +> Source: `src/content/docs/actors/scaling.mdx` +> Canonical URL: https://rivet.dev/docs/actors/scaling +> Description: This page has moved to [design patterns](/docs/actors/design-patterns). + +--- + + +_Source doc path: /docs/actors/scaling_ diff --git a/.agents/skills/rivetkit/reference/actors/schedule.md b/.agents/skills/rivetkit/reference/actors/schedule.md new file mode 100644 index 0000000..8dfdb1f --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/schedule.md @@ -0,0 +1,40 @@ +# Actor Scheduling + +> Source: `src/content/docs/actors/schedule.mdx` +> Canonical URL: https://rivet.dev/docs/actors/schedule +> Description: Schedule actor actions in the future with persistent timers that survive restarts and upgrades. + +--- +Scheduling is used to trigger events in the future. The actor scheduler is like `setTimeout`, except the timeout will persist even if the actor restarts, upgrades, or crashes. + +For a pattern guide to durable recurring jobs, see the cookbook: [Cron Jobs and Scheduled Tasks](/cookbook/cron-jobs/). + +## Use Cases + +Scheduling is helpful for long-running timeouts like month-long billing periods or account trials. + +## Scheduling + +### `c.schedule.after(duration, actionName, ...args)` + +Schedules a function to be executed after a specified duration. This function persists across actor restarts, upgrades, or crashes. + +Parameters: + +- `duration` (number): The delay in milliseconds. +- `actionName` (string): The name of the action to be executed. +- `...args` (unknown[]): Additional arguments to pass to the function. + +### `c.schedule.at(timestamp, actionName, ...args)` + +Schedules a function to be executed at a specific timestamp. This function persists across actor restarts, upgrades, or crashes. + +Parameters: + +- `timestamp` (number): The exact time in milliseconds since the Unix epoch when the function should be executed. +- `actionName` (string): The name of the action to be executed. +- `...args` (unknown[]): Additional arguments to pass to the function. + +## Full Example + +_Source doc path: /docs/actors/schedule_ diff --git a/.agents/skills/rivetkit/reference/actors/sharing-and-joining-state.md b/.agents/skills/rivetkit/reference/actors/sharing-and-joining-state.md new file mode 100644 index 0000000..1fe0683 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/sharing-and-joining-state.md @@ -0,0 +1,10 @@ +# Sharing and Joining State + +> Source: `src/content/docs/actors/sharing-and-joining-state.mdx` +> Canonical URL: https://rivet.dev/docs/actors/sharing-and-joining-state +> Description: This page has moved to [design patterns](/docs/actors/design-patterns). + +--- + + +_Source doc path: /docs/actors/sharing-and-joining-state_ diff --git a/.agents/skills/rivetkit/reference/actors/sqlite-drizzle.md b/.agents/skills/rivetkit/reference/actors/sqlite-drizzle.md new file mode 100644 index 0000000..f0184d9 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/sqlite-drizzle.md @@ -0,0 +1,248 @@ +# SQLite + Drizzle + +> Source: `src/content/docs/actors/sqlite-drizzle.mdx` +> Canonical URL: https://rivet.dev/docs/actors/sqlite-drizzle +> Description: Use Drizzle ORM with embedded SQLite in Rivet Actors. + +--- +Use Drizzle when you want typed schema, typed queries, and generated migrations on top of actor-local SQLite. + +For a high-level overview of where to store actor data, see [State & Storage](/docs/actors/state). For a worked multi-tenant pattern, see the cookbook: [Database per Tenant](/cookbook/per-tenant-database/). + +## What is Drizzle good for? + +- **Typed schema**: define tables in TypeScript and get typed query results. +- **Typed query builder**: write SQL-like queries with autocompletion. +- **Migration workflow**: generate SQL migration files from schema changes. +- **Raw SQL escape hatch**: use `c.db.execute(...)` for direct SQLite when needed. + +## Project structure + +Use one folder per actor database: + +```txt +src/ + actors/ + todo-list/ + index.ts + schema.ts + drizzle.config.ts + drizzle/ + 0000_init.sql + migrations.js + migrations.d.ts + meta/ + _journal.json +``` + +- `index.ts` is the actor implementation. +- `drizzle/` holds the SQL migrations (`*.sql`) and `meta/_journal.json` generated by `drizzle-kit`. +- `migrations.js` is a small RivetKit glue file you maintain by hand. It imports the journal and each `*.sql` file and exports a `{ journal, migrations }` object keyed by migration (for example `m0000`). Add a new entry here whenever `db:generate` produces a new migration. +- Commit the generated migration files and `migrations.js` to source control. + +## Basic setup + +```json package.json +{ + "scripts": { + "db:generate": "find src/actors -name drizzle.config.ts -exec drizzle-kit generate --config {} \\;" + }, + "dependencies": { + "rivetkit": "*", + "drizzle-orm": "^0.44.2" + }, + "devDependencies": { + "drizzle-kit": "^0.31.2" + } +} +``` + +```ts vite.config.ts @nocheck +import { defineConfig, type Plugin } from "vite"; +import { readFileSync } from "node:fs"; + +function sqlRawPlugin(): Plugin { + return { + name: "sql-raw", + transform(_code, id) { + if (id.endsWith(".sql")) { + const content = readFileSync(id, "utf-8"); + return { code: `export default ${JSON.stringify(content)};` }; + } + }, + }; +} + +export default defineConfig({ + plugins: [sqlRawPlugin()], +}); +``` + +```ts drizzle.config.ts @nocheck +import { defineConfig } from "rivetkit/db/drizzle"; + +export default defineConfig({ + schema: "./src/actors/todo-list/schema.ts", + out: "./src/actors/todo-list/drizzle", +}); +``` + +```sql 0000_init.sql +CREATE TABLE `todos` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `title` text NOT NULL, + `created_at` integer NOT NULL +); +``` + +```json _journal.json +{ + "version": "7", + "dialect": "sqlite", + "entries": [ + { + "idx": 0, + "version": "7", + "when": 1735689600000, + "tag": "0000_init", + "breakpoints": true + } + ] +} +``` + +```ts migrations.js @nocheck +import journal from "./meta/_journal.json"; +import m0000 from "./0000_init.sql"; + +export default { + journal, + migrations: { + m0000, + }, +}; +``` + +```ts index.ts @nocheck +import { actor } from "rivetkit"; +import { db } from "rivetkit/db/drizzle"; +import migrations from "./drizzle/migrations.js"; +import { schema, todos } from "./schema.ts"; + +export const todoList = actor({ + db: db({ schema, migrations }), + actions: { + addTodo: async (c, title: string) => { + const rows = await c.db + .insert(todos) + .values({ title, createdAt: Date.now() }) + .returning(); + return rows[0]; + }, + getTodos: async (c) => { + return await c.db.select().from(todos).orderBy(todos.id); + }, + getTodoCount: async (c) => { + const rows = (await c.db.execute( + "SELECT COUNT(*) AS count FROM todos", + )) as { count: number }[]; + return rows[0]?.count ?? 0; + }, + }, +}); +``` + +```ts index.ts @nocheck +import { setup } from "rivetkit"; +import { todoList } from "./todo-list/index.ts"; + +export const registry = setup({ use: { todoList } }); +registry.start(); +``` + +```ts client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); +const todoList = client.todoList.getOrCreate(["main"]); + +await todoList.addTodo("Write Drizzle docs"); + +const todos = await todoList.getTodos(); +const count = await todoList.getTodoCount(); + +console.log(todos, count); +``` + +## Queries + +### Query builder + +Use Drizzle's typed query APIs for most reads and writes. + +```ts @nocheck +import { eq } from "drizzle-orm"; + +await c.db.insert(todos).values({ title, createdAt: Date.now() }); + +const rows = await c.db + .select() + .from(todos) + .where(eq(todos.title, title)); +``` + +### Raw SQL + +`rivetkit/db/drizzle` also exposes raw SQLite access through `c.db.execute(...)`. + +```ts @nocheck +await c.db.execute( + "CREATE INDEX IF NOT EXISTS idx_todos_created_at ON todos(created_at)", +); +``` + +## Queues + +Use queues for ordered mutations and keep actions read-only. Import `queue` alongside `actor` from `rivetkit`. + +```ts @nocheck +import { actor, queue } from "rivetkit"; + +// ... + +queues: { + addTodo: queue<{ title: string }>(), +}, +run: async (c) => { + for await (const message of c.queue.iter()) { + if (message.name === "addTodo") { + await c.db.insert(todos).values({ + title: message.body.title, + createdAt: Date.now(), + }); + } + } +}, +actions: { + getTodos: async (c) => await c.db.select().from(todos), +}, +``` + +## Recommendations + +- Prefer Drizzle query APIs for app code and use raw SQL for advanced SQLite features. +- Keep one `drizzle.config.ts` per actor folder. +- Re-run `db:generate` after schema changes and commit generated migration files. +- Use queues for writes and actions for reads. +- Keep related writes in one action or queue message to reduce interleaved query risk. + +## Read more + +- [Drizzle SQLite quickstart](https://orm.drizzle.team/docs/get-started-sqlite) +- [Drizzle `drizzle-kit generate`](https://orm.drizzle.team/docs/drizzle-kit-generate) +- [Drizzle + Cloudflare D1](https://orm.drizzle.team/docs/deploy-cloudflare-d1) +- [Drizzle + Cloudflare Durable Objects](https://orm.drizzle.team/docs/deploy-cloudflare-do) +- [Cloudflare Durable Objects SQLite storage](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/) + +_Source doc path: /docs/actors/sqlite-drizzle_ diff --git a/.agents/skills/rivetkit/reference/actors/sqlite.md b/.agents/skills/rivetkit/reference/actors/sqlite.md new file mode 100644 index 0000000..fb55998 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/sqlite.md @@ -0,0 +1,127 @@ +# SQLite + +> Source: `src/content/docs/actors/sqlite.mdx` +> Canonical URL: https://rivet.dev/docs/actors/sqlite +> Description: Use embedded SQLite in Rivet Actors with raw SQL queries. + +--- +For a high-level overview of where to store actor data, including when to use `c.state` versus SQLite, see [State & Storage](/docs/actors/state). For a worked multi-tenant pattern, see the cookbook: [Database per Tenant](/cookbook/per-tenant-database/). + +## What is SQLite? + +- **Database per actor**: each actor instance has its own SQLite database, scoped to that actor. +- **High performance**: Rivet Actors keep compute and storage together, so queries avoid network round trips to an external database. +- **Larger-than-memory storage**: SQLite stores data on disk, so you can work with datasets that do not fit in actor memory. +- **Embedded relational database**: use tables, indexes, and SQL queries directly inside actor logic. + +### SQLite features + +- **Indexes**: speed up lookups on frequently queried fields. +- **Search and filtering**: use `WHERE`, `LIKE`, and `ORDER BY` instead of manual in-memory loops. +- **Relationships**: use multiple tables and `JOIN` queries for connected data. +- **Constraints**: use primary keys, unique constraints, and foreign keys for data integrity. +- **Transactions**: apply multiple writes atomically when changes must stay consistent. + +## Raw SQL vs ORM (Drizzle) + +Rivet supports both raw SQL and [Drizzle](https://orm.drizzle.team/) for actor-local SQLite. + +Use **raw SQL** when you want direct query control and minimal abstraction. + +```ts @nocheck +await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); +const rows = await c.db.execute("SELECT id, title FROM todos ORDER BY id DESC"); +``` + +Use **Drizzle** when you want typed schema and typed query APIs. + +```ts @nocheck +await c.vars.drizzle.insert(todos).values({ title }); +const rows = await c.vars.drizzle.select().from(todos).orderBy(desc(todos.id)); +``` + +You can mix both in the same actor. + +For Drizzle setup, see [SQLite + Drizzle](/docs/actors/sqlite-drizzle). + +## Basic setup + +Define `db: db({ onMigrate })` on your actor, create your schema in `onMigrate`, and execute SQL with `c.db.execute(...)`. + +RivetKit wraps `onMigrate` in a SQLite savepoint, so migration steps are atomic. If `onMigrate` throws, all SQL run by that hook is rolled back before the actor starts. + +## Queries + +`c.db.execute(...)` returns an array of row objects for `SELECT` queries. + +```ts @nocheck +const rows = await c.db.execute( + "SELECT id, title FROM todos WHERE title LIKE ?", + `%${query}%`, +); +``` + +### Parameterized queries + +Use `?` placeholders for dynamic values and pass parameters in order after the SQL string. + +```ts @nocheck +await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); +``` + +You can also use named SQLite bindings by passing a single properties object. + +```ts @nocheck +const rows = await c.db.execute( + "SELECT id, title FROM todos WHERE title = :title", + { title: "Write SQLite docs" }, +); +``` + +### Transactions + +Use transactions when multiple writes must succeed or fail together. + +```ts @nocheck +await c.db.transaction(async (tx) => { + await tx.execute("INSERT INTO todos (title) VALUES (?)", title); + await tx.execute( + "INSERT INTO comments (todo_id, body) VALUES (last_insert_rowid(), ?)", + body, + ); +}); +``` + +RivetKit commits when the callback resolves and rolls back when it throws. Other transactions and ordinary actor SQL queue in FIFO order until the callback finishes. Transactions have a 60-second safety timeout by default; increase it for legitimately long work with `{ timeout: 120_000 }`. + +Always use the callback's `tx` value inside the transaction. Starting another transaction or using the outer `c.db` from the callback waits behind the active transaction and eventually reaches the safety timeout; the resulting error points to this possible deadlock. + +Manual `BEGIN`/`COMMIT` calls remain supported for compatibility, but cannot protect against interleaving callers. RivetKit logs a warning recommending `db.transaction()`. Set `warnOnManualTransactions: false` in `db(...)` to disable the warning; the warning itself mentions this flag. + +## Queues + +It's recommended to use queues for mutations and actions for read-only queries. This is the same code structure as the basic setup, but mutation writes are routed through queues. + +## Debugging + +- `GET /inspector/summary` includes `isDatabaseEnabled` so you can confirm SQLite is configured. +- `GET /inspector/database/schema` returns the tables and views discovered in the actor's SQLite database. +- `GET /inspector/database/rows?table=...&limit=100&offset=0` returns paged rows for a specific table or view. +- `POST /inspector/database/execute` lets you run ad-hoc SQL for debugging and data fixes with positional `args` or named `properties`. +- Keep a small read-only action for quick query verification while debugging. +- In non-dev mode, inspector endpoints require authorization. + +## Recommendations + +- Keep schema creation and migration steps in `onMigrate`; RivetKit runs them atomically inside a SQLite savepoint. +- Use `?` placeholders for dynamic values. +- Prefer queue-driven writes for ordered or background work. +- Use transactions for related multi-step mutations when atomicity matters. + +## Read more + +- [SQLite + Drizzle in Rivet Actors](/docs/actors/sqlite-drizzle) +- [SQLite docs](https://sqlite.org/docs.html) +- [SQLite SQL language reference](https://sqlite.org/lang.html) + +_Source doc path: /docs/actors/sqlite_ diff --git a/.agents/skills/rivetkit/reference/actors/state.md b/.agents/skills/rivetkit/reference/actors/state.md new file mode 100644 index 0000000..559b49c --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/state.md @@ -0,0 +1,270 @@ +# In-Memory State + +> Source: `src/content/docs/actors/state.mdx` +> Canonical URL: https://rivet.dev/docs/actors/state +> Description: Actors store state in memory for instant reads and writes. State can be persisted automatically or kept ephemeral. + +--- +## Types of State + +There are three ways to store data in an actor, depending on what it looks like and whether it needs to survive restarts. + +### Durable + +Simple, serializable data on `c.state` that is automatically persisted and restored across restarts. The default starting point. + +### Ephemeral + +Live objects on `c.vars` like database connections, API clients, and event emitters, or data loaded from an external source. Never persisted. + +```typescript @nocheck External database +import { actor } from "rivetkit"; +import { Pool } from "pg"; + +// One shared pool for the whole process, created once and reused by every actor +const pool = new Pool({ connectionString: process.env.DATABASE_URL }); + +const userActor = actor({ + state: { profile: null as Record | null }, + + // Load this actor's row from the shared pool on each start + createVars: async (c) => { + const { rows } = await pool.query("SELECT * FROM users WHERE id = $1", [c.key[0]]); + return { profile: rows[0] }; + }, + + actions: { + updateEmail: async (c, email: string) => { + await pool.query("UPDATE users SET email = $1 WHERE id = $2", [email, c.key[0]]); + } + } +}); +``` + +### SQLite + +Rivet also provides an embedded SQLite database (`c.db`) for when your data needs to be queried, requires safe schema migrations, or grows too large to hold in memory. See [SQLite](/docs/actors/sqlite). + +```typescript @nocheck Basic +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +const todoList = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS todos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL + ); + `); + }, + }), + + actions: { + add: async (c, title: string) => { + await c.db.execute("INSERT INTO todos (title) VALUES (?)", title); + }, + + list: async (c) => { + return (await c.db.execute( + "SELECT id, title FROM todos ORDER BY id DESC", + )) as { id: number; title: string }[]; + }, + }, +}); +``` + +```typescript @nocheck Load into memory +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +const counter = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS counter ( + id INTEGER PRIMARY KEY CHECK (id = 1), + count INTEGER NOT NULL + ); + `); + await db.execute("INSERT OR IGNORE INTO counter (id, count) VALUES (1, 0)"); + }, + }), + + // Load the count from SQLite into memory on every start + createVars: async (c) => { + const rows = (await c.db.execute( + "SELECT count FROM counter WHERE id = 1", + )) as { count: number }[]; + return { count: rows[0].count }; + }, + + actions: { + get: (c) => c.vars.count, + + increment: async (c) => { + // Update the in-memory value and write it back to SQLite + c.vars.count += 1; + await c.db.execute("UPDATE counter SET count = ? WHERE id = 1", c.vars.count); + return c.vars.count; + }, + }, +}); +``` + +## State Isolation + +Each actor's state is fully isolated. Other actors and clients can't touch it directly; all reads and writes go through the actor's own [Actions](/docs/actors/actions). To share state across actors, see [sharing and joining state](/docs/actors/sharing-and-joining-state). + +## Durable State + +`c.state` lives in memory and is persisted automatically, so reads and writes have no added latency while the data still survives sleeps, restarts, upgrades, and crashes. Use it for small, simple values like counters, flags, and small maps. + +`createState` runs once when the actor is first created. On later starts, state is loaded from storage instead of recreated. See [Lifecycle](/docs/actors/lifecycle). + +### When state saves + +Mutating `c.state` schedules a save automatically. Rapid mutations are batched into a single write on a throttle (`stateSaveInterval`, default 1 second). Reads never trigger a save, saves aren't tied to action or handler boundaries, and state is also flushed when the actor sleeps or shuts down. + +To force a save mid-action, call `c.saveState()`: + +- `c.saveState({ immediate: true })` writes immediately and resolves once the write completes. +- `c.saveState()` schedules a throttled save and returns right away, without waiting for the write. + +Force an immediate save before a risky side effect so a crash can't lose progress: + +### Supported types + +State must be serializable. + +- `null`, `undefined`, `boolean`, `string`, `number`, `BigInt` +- `Date`, `RegExp`, `Error` +- `ArrayBuffer` and typed arrays (`Uint8Array`, `Int8Array`, `Float32Array`, etc.) +- `Map`, `Set`, `Array` +- Plain objects + +When data grows large or needs querying, store it in [Embedded SQLite](#embedded-sqlite) instead. + +## Ephemeral State + +`c.vars` holds data that exists only while the actor runs and is never saved. Use it for live objects that can't be serialized (connections, clients, emitters) or for data loaded from an external source. Most actors use both: `state` for durable data, `vars` for live objects. + +`createVars` runs on every actor start, unlike `createState` which runs once. That makes it the place to open connections and load data each time the actor wakes. + +### Runtime objects + +Build non-serializable objects in `createVars` and use them from actions: + +### Loading from external sources + +Create the connection pool once at module scope and share it across all actors, then use `createVars` (which can be `async`) to load this actor's data from it on each start: + +```typescript @nocheck +import { actor } from "rivetkit"; +import { Pool } from "pg"; + +// One shared pool for the whole process, not one per actor +const pool = new Pool({ connectionString: process.env.DATABASE_URL }); + +const profile = actor({ + state: { cachedName: "" }, + + createVars: async (c) => { + const { rows } = await pool.query("SELECT * FROM users WHERE id = $1", [c.key[0]]); + return { user: rows[0] }; + }, + + actions: { + updateEmail: async (c, email: string) => { + await pool.query("UPDATE users SET email = $1 WHERE id = $2", [email, c.key[0]]); + } + } +}); +``` + +When the actor owns its data, prefer [durable state](#durable-state) or [SQLite](#embedded-sqlite), which need no external infrastructure. + +### Cleanup + +`vars` is dropped when the actor stops, but per-actor resources like timers, subscriptions, and dedicated connections aren't cleaned up for you. Release them in `onSleep` and `onDestroy`. A shared pool stays open for the whole process, so don't close it per actor. + +```typescript @nocheck +const poller = actor({ + state: { ticks: 0 }, + + // Per-actor timer started on each wake + createVars: (c) => ({ timer: setInterval(() => c.state.ticks++, 5000) }), + + // Clear it before the actor sleeps or is destroyed + onSleep: (c) => clearInterval(c.vars.timer), + onDestroy: (c) => clearInterval(c.vars.timer), + + actions: { /* ... */ } +}); +``` + +## Embedded SQLite + +`c.db` is a SQLite database scoped to each actor and stored on disk. Use it for queryable, relational, or larger-than-memory data. Because compute and storage live together, queries run locally with no network round trips. + +A common pattern is to treat SQLite as the source of truth and keep a working copy in `c.vars`: load rows in `createVars`, serve reads from memory, and write changes back to `c.db`. + +```typescript @nocheck +import { actor } from "rivetkit"; +import { db } from "rivetkit/db"; + +const leaderboard = actor({ + db: db({ + onMigrate: async (db) => { + await db.execute(` + CREATE TABLE IF NOT EXISTS scores ( + player TEXT PRIMARY KEY, + score INTEGER NOT NULL + ); + `); + }, + }), + + // Load the table into memory once per start + createVars: async (c) => { + const rows = (await c.db.execute("SELECT player, score FROM scores")) as { + player: string; + score: number; + }[]; + return { scores: new Map(rows.map((r) => [r.player, r.score])) }; + }, + + actions: { + top: (c) => [...c.vars.scores].sort((a, b) => b[1] - a[1]).slice(0, 10), + + record: async (c, player: string, score: number) => { + c.vars.scores.set(player, score); + // Write through to SQLite + await c.db.execute( + "INSERT INTO scores (player, score) VALUES (?, ?) ON CONFLICT(player) DO UPDATE SET score = ?", + player, score, score, + ); + }, + }, +}); +``` + +For the full query API, schema migrations, transactions, and the Drizzle ORM, see: + +- [SQLite](/docs/actors/sqlite): raw SQL against the embedded per-actor database. +- [SQLite + Drizzle](/docs/actors/sqlite-drizzle): typed schema and query APIs. + +## Debugging + +- `GET /inspector/state` returns the actor's current state and `isStateEnabled`. +- `PATCH /inspector/state` lets you set state directly while debugging. +- In non-dev mode, inspector endpoints require authorization. + +## API Reference + +- [`CreateContext`](/typedoc/types/rivetkit.mod.CreateContext.html) - Context available during actor state creation +- [`ActorContext`](/typedoc/interfaces/rivetkit.mod.ActorContext.html) - Context available throughout actor lifecycle +- [`ActorDefinition`](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html) - Interface for defining actors with state + +_Source doc path: /docs/actors/state_ diff --git a/.agents/skills/rivetkit/reference/actors/statuses.md b/.agents/skills/rivetkit/reference/actors/statuses.md new file mode 100644 index 0000000..cccf52a --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/statuses.md @@ -0,0 +1,36 @@ +# Actor Statuses + +> Source: `src/content/docs/actors/statuses.mdx` +> Canonical URL: https://rivet.dev/docs/actors/statuses +> Description: Understand the lifecycle statuses of Rivet Actors, what they mean, how they appear in the API, and how to troubleshoot common issues. + +--- +## Statuses + +These are the statuses you can see in the dashboard for each actor. + +| Status | Description | +|---|---| +| **Starting** | The actor has been created but has not yet become connectable. | +| **Running** | The actor is live and accepting connections. | +| **Destroyed** | The actor has been gracefully destroyed. | +| **Crashed** | The actor failed to start or encountered a fatal error. See [Troubleshooting](/docs/actors/troubleshooting#actor-status-is-crashed) for common failure reasons. | +| **Sleeping** | The actor has been put to sleep from inactivity. It will be woken up automatically when a new request arrives. | +| **Pending** | The actor is waiting to be allocated to a runner. This happens when no runner is available to handle the actor. See [Troubleshooting](/docs/actors/troubleshooting#actor-status-is-pending) for common causes. | +| **Crash Loop Backoff** | The actor failed to allocate and is waiting to retry with a backoff. This typically means repeated allocation failures. The backoff prevents overloading your infrastructure in the case of a widespread misconfiguration in your backend. See [Troubleshooting](/docs/actors/troubleshooting#actor-status-is-crashed) for common failure reasons. | + +## API Representation + +The actor object returned by the full engine API (used by the dashboard) includes the following timestamp fields used to derive status: + +| Field | Description | +|---|---| +| `createTs` | When the actor was first created. Always present. | +| `connectableTs` | When the actor became connectable. Null if not yet running. | +| `destroyTs` | When the actor was destroyed. | +| `sleepTs` | When the actor entered a sleeping state. | +| `pendingAllocationTs` | When the actor started waiting for an allocation. | +| `rescheduleTs` | When the actor will retry allocation after a failure. | +| `error` | Error details if the actor failed. | + +_Source doc path: /docs/actors/statuses_ diff --git a/.agents/skills/rivetkit/reference/actors/testing.md b/.agents/skills/rivetkit/reference/actors/testing.md new file mode 100644 index 0000000..5afe658 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/testing.md @@ -0,0 +1,51 @@ +# Testing + +> Source: `src/content/docs/actors/testing.mdx` +> Canonical URL: https://rivet.dev/docs/actors/testing +> Description: Rivet provides a straightforward testing framework to build reliable and maintainable applications. This guide covers how to write effective tests for your actor-based services. + +--- +## Setup + +To set up testing with Rivet: + +```bash +# Install Vitest +npm install -D vitest + +# Run tests +npm test +``` + +## Basic Testing Setup + +Rivet includes a test helper called `setupTest` that starts your registry in test mode and returns a client connected to it. This allows for fast, isolated tests without external dependencies. + +## Testing Actor State + +State persists within each test, allowing you to verify that your actor correctly maintains state between operations. + +## Testing Events + +For actors that emit events, you can verify events are correctly triggered by subscribing to them: + +## Testing Schedules + +Rivet's schedule functionality can be tested by scheduling work and waiting for it to run: + +Use a short real-time delay to wait for scheduled work to run. `setupTest` does not install fake timers, so if you want to use `vi.useFakeTimers()` you must enable it yourself and confirm it works with your selected runtime. + +## Best Practices + +1. **Isolate tests**: Each test should run independently, avoiding shared state. +2. **Test edge cases**: Verify how your actor handles invalid inputs, concurrent operations, and error conditions. +3. **Test scheduled operations**: Use short real-time delays to wait for scheduled work to run. +4. **Use realistic data**: Test with data that resembles production scenarios. + +`setupTest` starts the registry and disposes the returned client when the test finishes, so you can focus on writing effective tests for your business logic. + +## API Reference + +- [`setupTest`](/typedoc/functions/rivetkit.test_mod.setupTest.html) - Test setup helper function + +_Source doc path: /docs/actors/testing_ diff --git a/.agents/skills/rivetkit/reference/actors/troubleshooting.md b/.agents/skills/rivetkit/reference/actors/troubleshooting.md new file mode 100644 index 0000000..65b234d --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/troubleshooting.md @@ -0,0 +1,154 @@ +# Troubleshooting + +> Source: `src/content/docs/actors/troubleshooting.mdx` +> Canonical URL: https://rivet.dev/docs/actors/troubleshooting +> Description: Common issues with Rivet Actors and how to resolve them. + +--- +## Common Steps + +Before diving into specific errors, try these general troubleshooting steps: + +- Check your server logs for `level=ERROR` or `level=WARN` messages. +- Check if any of your backend processes have crashed or restarted unexpectedly. +- If you need more diagnostics, set `RIVET_LOG_LEVEL=DEBUG` for verbose logging. See [Logging](/docs/general/logging) for more options. + +## Reporting Issues + +If you're stuck, reach out on [Discord](https://rivet.dev/discord) or file an issue on [GitHub](https://github.com/rivet-dev/rivet/issues). + +When reporting, please include: + +- **Symptoms** + - Whether this is happening in local dev, deployed, or both + - The error you're seeing (screenshot or error message) + - Relevant source code related to the issue +- **What you've tried to solve it** +- **Environment** + - RivetKit version + - Runtime (Node, Bun, etc.) including version + - If applicable, provider in use (e.g. Vercel, Railway, Cloudflare) + - If applicable, HTTP router in use (e.g. Hono, Express, Elysia) + +## Actor status is crashed + +See [Actor Statuses](/docs/actors/statuses) for more about this status. + +The dashboard will show the specific failure reason. Common errors include: + +### `crashed` + +The actor's `run` handler threw an unhandled exception or exited unexpectedly. Check your actor logs for the error message and stack trace. + +### `no_capacity` + +No server was available to run your actor. The cause depends on your [runtime mode](/docs/general/runtime-modes): + +**Serverless**: + +- Your provider configuration does not have the region enabled that the actor is trying to run in. This is uncommon and usually only happens if an actor was created and then the provider config was updated to remove the region. +- There is an issue connecting to your backend. If the engine is hitting `/api/rivet/start` and failing, check your backend logs for errors. + +**Runners**: + +- You don't have enough runners online. Check your runner list in the dashboard to verify runners are visible and connected. +- Your runners are full. Each runner has a limited number of actor slots (configured via `RIVET_TOTAL_SLOTS`, default: 100,000). Check the dashboard to see if your runners have available capacity and scale up if needed. + +### `runner_no_response` + +The server running your actor did not respond in time. This can happen if your server is overloaded or experienced a network issue. Try restarting your server or checking its health. + +### `runner_connection_lost` + +The server running your actor lost its connection to Rivet. This is usually caused by a network interruption or your server restarting. + +### `runner_draining_timeout` + +Your server is shutting down and the actor did not finish in time. Consider handling graceful shutdown in your actor or increasing your shutdown timeout. + +### `concurrent_actor_limit_reached` + +The actor could not be allocated because the concurrent actor limit was reached. Reduce the number of concurrently running actors or increase your limit. + +### `no_envoys` + +No server was available to run your actor. This is equivalent to `no_capacity` on the current allocation path. See the `no_capacity` section above for the causes and fixes for your [runtime mode](/docs/general/runtime-modes). + +### `envoy_no_response` + +The server running your actor did not respond in time. This can happen if your server is overloaded or experienced a network issue. Try restarting your server or checking its health. + +### `envoy_connection_lost` + +The server running your actor lost its connection to Rivet. This is usually caused by a network interruption or your server restarting. + +### `serverless_http_error` + +Your serverless endpoint returned an HTTP error. Common causes: + +- Your backend is returning an error before the actor can start. Check your server logs. +- Your endpoint is behind authentication or a firewall that is blocking Rivet's requests. +- Your serverless function crashed during startup. Check your platform's function logs (e.g. Vercel, Cloudflare). + +### `serverless_connection_error` + +Rivet was unable to connect to your serverless endpoint. Check that: + +- Your backend is deployed and the endpoint URL is correct. +- Your server is publicly reachable from the internet. +- There are no DNS or firewall issues blocking the connection. + +### `serverless_stream_ended_early` + +The connection to your serverless endpoint was terminated before the actor finished. This usually means your serverless function hit its execution time limit. Ensure that your Rivet provider's request lifespan is configured to match the max duration of your serverless platform. + +### `serverless_invalid_sse_payload` + +Rivet received an unexpected response from your serverless endpoint. This typically means something is intercepting or modifying the request before it reaches your RivetKit handler. Check that: + +- Your server routes requests to `registry.start()`, `registry.serve()`, or `registry.handler()` correctly. +- No middleware is modifying the request or response body. + +### `internal_error` + +An unexpected error occurred within Rivet. If this persists, please [contact support](https://rivet.dev/docs). + +## Actors crashing immediately on startup + +If your actors are being created and then immediately destroyed or crashing, there is likely an error being thrown in your `createState` or `onCreate` lifecycle hooks. These hooks run during actor initialization before the actor is marked as ready. + +Check your server logs for the error message and stack trace. Common causes include: + +- An exception thrown in `createState` (e.g. invalid input, failed validation, or a runtime error when computing initial state) +- An exception thrown in `onCreate` (e.g. a failing external API call, missing configuration, or invalid setup logic) + +Fix the error in the relevant lifecycle hook and redeploy. + +## Actors not upgrading to new code + +If your actors are still running old code after deploying a new version, your [versioning](/docs/actors/versions) is likely not configured correctly. + +Without versioning, Rivet has no way to distinguish old deployments from new ones. The behavior depends on your [runtime mode](/docs/general/runtime-modes): + +- **Serverless**: Old requests may still be open from the previous deployment, so actors continue running on the old version's connection until those requests close. +- **Runners**: The old runner container is still running and will continue accepting new actors. New actors may be scheduled on the old runner instead of the new one. + +To fix this, configure a version number in your [registry configuration](/docs/general/registry-configuration). When a new version is deployed, Rivet will allocate new actors to the latest version and optionally drain old actors to migrate them. + +## Actor status is pending + +See [Actor Statuses](/docs/actors/statuses) for more about this status. + +An actor stays in "pending" status when Rivet is waiting for a server to accept it. The cause depends on your [runtime mode](/docs/general/runtime-modes): + +**Serverless**: + +- A region may have been removed from your provider configuration while an existing actor still lives in that region. The actor has no available server to start on because no provider serves that region anymore. Re-add the region to your provider config or destroy the affected actors. +- Check your backend logs for errors on the `/api/rivet/start` endpoint. + +**Runners**: + +- You don't have enough runners online. Check the dashboard to verify your runners are connected. +- Your runners may be at capacity. Check the dashboard to see if runners have available actor slots and scale up if needed. + +_Source doc path: /docs/actors/troubleshooting_ diff --git a/.agents/skills/rivetkit/reference/actors/types.md b/.agents/skills/rivetkit/reference/actors/types.md new file mode 100644 index 0000000..3e8f9b0 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/types.md @@ -0,0 +1,46 @@ +# Types + +> Source: `src/content/docs/actors/types.mdx` +> Canonical URL: https://rivet.dev/docs/actors/types +> Description: TypeScript types for working with Rivet Actors. This page covers context types used in lifecycle hooks and actions, as well as helper types for extracting types from actor definitions. + +--- +## Context Types + +Context types define what properties and methods are available in different parts of the actor lifecycle. + +### Extracting Context Types + +When writing helper functions that work with actor contexts, use context extractor types like `CreateContextOf` or `ActionContextOf` to extract the appropriate context type from your actor definition. + +### All Context Types + +Each lifecycle hook and handler has a corresponding `*ContextOf` type, exported from `"rivetkit"`. Pass `typeof myActor` as the type parameter. + +| Hook / Handler | Context Type | +|---|---| +| `createState` | `CreateContextOf` | +| `onCreate` | `CreateContextOf` | +| `createVars` | `CreateVarsContextOf` | +| `createConnState` | `CreateConnStateContextOf` | +| `onBeforeConnect` | `BeforeConnectContextOf` | +| `onConnect` | `ConnectContextOf` | +| `onDisconnect` | `DisconnectContextOf` | +| `onDestroy` | `DestroyContextOf` | +| `onMigrate` | `MigrateContextOf` | +| `onWake` | `WakeContextOf` | +| `onSleep` | `SleepContextOf` | +| `onStateChange` | `StateChangeContextOf` | +| `onBeforeActionResponse` | `BeforeActionResponseContextOf` | +| `actions.*` | `ActionContextOf` | +| `run` | `RunContextOf` | +| `workflow` orchestration helpers (root, `loop`, `try`, `race`, `join` branches) | `WorkflowContextOf` | +| `workflow` `step` / `tryStep` run + rollback helpers | `WorkflowStepContextOf` | +| `onRequest` | `RequestContextOf` | +| `onWebSocket` | `WebSocketContextOf` | + +`ActorContextOf`, `ConnContextOf`, and `ConnInitContextOf` are general-purpose base context types useful for helper functions that don't correspond to a specific hook. + +Workflow context extractors are exported from both `"rivetkit"` and `"rivetkit/workflow"`. + +_Source doc path: /docs/actors/types_ diff --git a/.agents/skills/rivetkit/reference/actors/versions.md b/.agents/skills/rivetkit/reference/actors/versions.md new file mode 100644 index 0000000..1b45129 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/versions.md @@ -0,0 +1,241 @@ +# Versions & Upgrades + +> Source: `src/content/docs/actors/versions.mdx` +> Canonical URL: https://rivet.dev/docs/actors/versions +> Description: When you deploy new code, Rivet ensures actors are upgraded seamlessly without downtime. + +--- +## How Versions Work + +Each runner has a **version number**. When you deploy new code with a new version, Rivet handles the transition automatically: + +- **New actors go to the newest version**: When allocating actors, Rivet always prefers runners with the highest version number +- **Multiple versions can coexist**: Old actors continue running on old versions while new actors are created on the new version +- **Drain old actors**: When enabled, a runner connecting with a newer version number will gracefully stop old actors to be rescheduled to the new version + +Versions are not configured by default. See [Registry Configuration](/docs/general/registry-configuration) to learn how to configure the runner version. + +`RIVET_ENVOY_VERSION` is only needed when self-hosting or using a custom runner. Rivet Compute handles versioning automatically. + +### Example Scenario + +### Drain Enabled + +When a new version is deployed, existing actors are gracefully stopped on the old runner and rescheduled onto the new version. + +```mermaid +sequenceDiagram + participant R1 as Runner v1 + participant R2 as Runner v2 + + Note over R1: Currently running + Note over R2: Deployed + R2->>R1: Drain old actors + R1->>R2: Reschedule actors + Note over R1: Shut down when all actors stopped +``` + +### Drain Disabled + +When a new version is deployed, both versions coexist. New actors are created on the new version while existing actors continue running on the old version until. + +```mermaid +sequenceDiagram + participant R1 as Runner v1 + participant R2 as Runner v2 + + Note over R1: Currently running + Note over R2: Deployed + Note over R1: Actor 1 sleeps from inactivity + Note over R2: Actor 1 wakes up when prompted +``` + +## Configuration + +### Setting the Version + +Configure the runner version using an environment variable or programmatically: + +```bash {{"title": "Environment Variable"}} +RIVET_ENVOY_VERSION=2 +``` + +The version **must** be set at build time, not at runtime. Do not use `Date.now()` or similar runtime values in your registry setup code. This would assign a different version every time the server starts, causing actors to be drained and rescheduled on every restart instead of only on new deployments. + +### Example Configurations + +We recommend injecting a build-time value that increments with every deployment. Here are concrete examples for common setups: + +### Dockerfile + +Generate the version at build time and bake it into the image as an environment variable: + +```bash @nocheck +docker build --build-arg RIVET_ENVOY_VERSION=$(date +%s) . +``` + +```dockerfile @nocheck +FROM node:20-slim +ARG RIVET_ENVOY_VERSION +ENV RIVET_ENVOY_VERSION=$RIVET_ENVOY_VERSION +WORKDIR /app +COPY . . +RUN npm install && npm run build +CMD ["node", "dist/server.js"] +``` + +All containers from this image will share the same version. + +### Next.js + +Set the version in `next.config.ts`. Next.js evaluates this file once at build time and inlines the value into the bundle: + +```typescript @nocheck +import type { NextConfig } from "next"; + +const nextConfig: NextConfig = { + env: { + RIVET_ENVOY_VERSION: String(Math.floor(Date.now() / 1000)), + }, +}; + +export default nextConfig; +``` + +### Vite + +Use `define` in your Vite config. This is evaluated once at build time and inlined into the bundle: + +```typescript @nocheck +import { defineConfig } from "vite"; + +export default defineConfig({ + define: { + "process.env.RIVET_ENVOY_VERSION": JSON.stringify( + String(Math.floor(Date.now() / 1000)) + ), + }, +}); +``` + +### CI/CD + +Set the version from your CI pipeline: + +```yaml @nocheck +# GitHub Actions +env: + RIVET_ENVOY_VERSION: ${{ github.run_number }} +``` + +```bash @nocheck +# Railway / Render / generic CI +export RIVET_ENVOY_VERSION=$(date +%s) +``` + +```bash @nocheck +# Git commit count +export RIVET_ENVOY_VERSION=$(git rev-list --count HEAD) +``` + +### Build Script + +Generate a version file during your build step and import it: + +```json @nocheck +{ + "scripts": { + "build": "echo \"export const BUILD_VERSION = $(date +%s);\" > src/build-version.ts && tsc" + } +} +``` + +```typescript @nocheck +import { actor, setup } from "rivetkit"; +import { BUILD_VERSION } from "./build-version"; + +const myActor = actor({ state: {}, actions: {} }); + +const registry = setup({ + use: { myActor }, + envoy: { + version: BUILD_VERSION, + }, +}); +``` + +### Drain on Version Upgrade + +The `drainOnVersionUpgrade` option controls whether old actors are stopped when a new version is deployed. This is configured in the Rivet dashboard under your runner configuration. See [Pool Configuration](/docs/general/pool-configuration) for the full set of pool options, including how to rate-limit actor eviction during the drain. + +| Value | Behavior | +|-------|----------| +| `false` | Old actors continue running. New actors go to new version. Versions coexist. | +| `true` (default) | Old actors receive stop signal and have 30m to finish gracefully. | + +## Upgrading Actor State + +When you deploy a new version, existing actors may need to handle schema changes in their persisted data. + +### SQLite (recommended for complex schemas) + +**Drizzle (recommended)** + +Use [Drizzle](/docs/actors/sqlite-drizzle) for typed schemas with generated migrations. Drizzle generates versioned `.sql` migration files from your TypeScript schema and applies them in order automatically. This is the recommended approach when your schema evolves frequently. + +**Raw SQL** + +For actors using [raw SQLite](/docs/actors/sqlite), migrations run automatically via the `onMigrate` hook on every actor start. RivetKit wraps the hook in a SQLite savepoint, so the migration is fully atomic. Use SQLite's `user_version` pragma to track which migrations have run: + +### In-memory state (`c.state`) + +If you use `c.state` for persistence, you are responsible for handling schema changes yourself. If you add, remove, or rename fields between versions, your code must handle the old shape gracefully. + +**Manual defaults in `onWake`** + +Apply defaults for missing fields: + +**Zod schema coercion** + +Use [Zod](https://zod.dev/) to parse persisted state on wake. Zod's `.default()` fills in missing fields automatically, so old actor state is coerced to the current schema: + +For anything beyond simple defaults, consider moving to [SQLite](/docs/actors/sqlite) where you get proper migration tooling. + +## Advanced + +### How Version Upgrade Detection Works + +When `drainOnVersionUpgrade` is enabled, Rivet uses two mechanisms to detect version changes: + +- **New runner connection**: When a runner connects with a newer version number, the engine immediately drains all older runners with the same name. This is the primary mechanism for [runner mode](/docs/general/runtime-modes) deployments. +- **Metadata polling** (serverless only): In [serverless mode](/docs/general/runtime-modes), runners periodically poll the engine to check for newer versions and self-drain if one is found. This ensures old runners drain even if no new requests trigger a runner connection. + +### SIGTERM Handling + +When a runner process receives SIGTERM, it gracefully stops all actors before exiting: + +- Each actor's `onSleep` hook is called, giving it time to save state +- Actors are rescheduled to other available runners +- The runner waits up to **30 minutes** for all actors to finish stopping +- If the process is force-killed before actors finish (e.g. SIGKILL), actors are rescheduled with a crash backoff penalty instead of a clean handoff + +Actors have a maximum of 30 minutes to clean up during shutdown. Ensure your platform's drain grace period is at most 30 minutes. + +### Shutdown Timeouts + +Several timeouts control how long each part of the shutdown process can take: + +| Timeout | Default | Description | Configuration | +|---------|---------|-------------|---------------| +| `actor_stop_threshold` | 30m | Engine-side limit on how long each actor has to stop before being marked lost | [Engine config](/docs/self-hosting/configuration) (`pegboard.actor_stop_threshold`) | +| `sleepGracePeriod` | 15s | Total graceful sleep budget for `onSleep`, `waitUntil`, `keepAwake`, and async raw WebSocket handlers | [Actor options](/docs/actors/lifecycle#options) | +| `runner_lost_threshold` | 15s | Fallback detection if the runner dies without graceful shutdown | [Engine config](/docs/self-hosting/configuration) (`pegboard.runner_lost_threshold`) | + +Rivet has a max shutdown grace period of 30 minutes that cannot be configured. + +## Related + +- [Runtime Modes](/docs/general/runtime-modes): Serverless vs runner deployment modes +- [Lifecycle](/docs/actors/lifecycle): Actor lifecycle hooks including `onSleep` + +_Source doc path: /docs/actors/versions_ diff --git a/.agents/skills/rivetkit/reference/actors/websocket-handler.md b/.agents/skills/rivetkit/reference/actors/websocket-handler.md new file mode 100644 index 0000000..f94499d --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/websocket-handler.md @@ -0,0 +1,201 @@ +# Low-Level WebSocket Handler + +> Source: `src/content/docs/actors/websocket-handler.mdx` +> Canonical URL: https://rivet.dev/docs/actors/websocket-handler +> Description: Actors can handle WebSocket connections through the `onWebSocket` handler. + +--- +For most use cases, [actions](/docs/actors/actions) and [events](/docs/actors/events) provide high-level connection handling powered by WebSockets that's easier to work with than low-level WebSockets. However, low-level handlers are required when implementing custom use cases. + +## Handling WebSocket Connections + +The `onWebSocket` handler manages low-level WebSocket connections. It receives the actor context and a `WebSocket` object. + +See also the [raw WebSocket handler example](https://github.com/rivet-dev/rivet/tree/main/examples/raw-websocket-handler). + +## Connecting To Actors + +### Via RivetKit Client + +Use the `.webSocket()` method on an actor handle to open a WebSocket connection to the actor's `onWebSocket` handler. This can be executed from either your frontend or backend. + +```typescript index.ts @hide @nocheck +import { actor, setup } from "rivetkit"; + +export const chat = actor({ + state: { messages: [] as string[] }, + onWebSocket: (c, websocket) => { + websocket.addEventListener("message", (event) => { + c.state.messages.push(event.data as string); + }); + }, + actions: {} +}); + +export const registry = setup({ use: { chat } }); +registry.start(); +``` + +```typescript client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +const actor = client.chat.getOrCreate(["my-chat"]); + +// Open WebSocket connection +const ws = await actor.webSocket("/"); + +// Listen for messages +ws.addEventListener("message", (event) => { + const message = JSON.parse(event.data as string); + console.log("Received:", message); +}); + +// Send messages +ws.send(JSON.stringify({ type: "chat", text: "Hello!" })); +``` + +The `.webSocket()` method returns a standard WebSocket. + +### Via getGatewayUrl + +Use `.getGatewayUrl()` to get the raw gateway URL for the actor. This is useful when you need to use the URL with external tools or custom WebSocket clients. + +```typescript index.ts @hide @nocheck +import { actor, setup } from "rivetkit"; + +export const chat = actor({ + state: { messages: [] as string[] }, + onWebSocket: (c, websocket) => { + websocket.addEventListener("message", (event) => { + c.state.messages.push(event.data as string); + }); + }, + actions: {} +}); + +export const registry = setup({ use: { chat } }); +registry.start(); +``` + +```typescript client.ts @nocheck +import { createClient } from "rivetkit/client"; +import type { registry } from "./index"; + +const client = createClient("http://localhost:6420"); + +const actor = client.chat.getOrCreate(["my-chat"]); + +// Get the raw gateway URL +const gatewayUrl = await actor.getGatewayUrl(); +// gatewayUrl = "https://...rivet.dev/..." + +// Convert to WebSocket URL and connect +const wsUrl = gatewayUrl.replace("http://", "ws://").replace("https://", "wss://"); +const ws = new WebSocket(`${wsUrl}/websocket/`); + +ws.addEventListener("message", (event) => { + const message = JSON.parse(event.data as string); + console.log("Received:", message); +}); + +ws.addEventListener("open", () => { + ws.send(JSON.stringify({ type: "chat", text: "Hello!" })); +}); +``` + +### Via HTTP API + +This handler can be accessed with raw WebSockets using `wss://api.rivet.dev/gateway/{actorId}@{token}/websocket/{...path}`. + +For example, to connect to the chat actor above: + +```typescript +// Replace with your actor ID and token +const actorId = "your-actor-id"; +const token = "your-token"; + +const ws = new WebSocket( + `wss://api.rivet.dev/gateway/${actorId}@${token}/websocket/` +); + +ws.addEventListener("message", (event) => { + const message = JSON.parse(event.data as string); + console.log("Received:", message); +}); + +ws.addEventListener("open", () => { + ws.send(JSON.stringify({ type: "chat", text: "Hello!" })); +}); +``` + +```bash +wscat -c "wss://api.rivet.dev/gateway/{actorId}@{token}/websocket/" +``` + +The path after `/websocket/` is passed to your `onWebSocket` handler and can be used to route to different functionality within your actor. For example, to connect with a custom path `/admin`: + +```typescript +// Replace with your actor ID and token +const actorId = "your-actor-id"; +const token = "your-token"; + +const ws = new WebSocket( + `wss://api.rivet.dev/gateway/${actorId}@${token}/websocket/admin` +); +``` + +```bash +wscat -c "wss://api.rivet.dev/gateway/{actorId}@{token}/websocket/admin" +``` + +See the [HTTP API reference](/docs/actors/http-api) for more information on WebSocket routing and authentication. + +### Via Proxying Connections + +You can proxy WebSocket connections from your own server to actor handlers using the RivetKit client. This is useful when you need to add custom authentication or connection management before forwarding to actors. + +See also the [raw WebSocket handler with proxy example](https://github.com/rivet-dev/rivet/tree/main/examples/raw-websocket-handler-proxy). + +## Connection & Lifecycle Hooks + +`onWebSocket` will trigger the `onBeforeConnect`, `onConnect`, and `onDisconnect` hooks. Read more about [lifecycle hooks](/docs/actors/lifecycle). + +Open WebSockets will be listed in `c.conns`. `conn.send` and `c.broadcast` have no effect on low-level WebSocket connections. Read more about [connections](/docs/actors/connections). + +## WinterTC Compliance + +The `onWebSocket` handler uses standard WebSocket APIs and will work with existing libraries expecting WinterTC-compliant WebSocket objects. + +## Advanced + +## WebSocket Hibernation + +WebSocket hibernation allows actors to go to sleep while keeping WebSocket connections alive. Actors automatically wake up when a message is received or the connection closes. + +Enable hibernation by setting `canHibernateWebSocket: true`. You can also pass a function `(request) => boolean` for conditional control. + +Since `open` only fires once when the client first connects, use `c.conn.state` to store per-connection data that persists across sleep cycles. See [connections](/docs/actors/connections) for more details. + +### Accessing the Request + +The underlying HTTP request is available via `c.request`. This is useful for accessing the path or query parameters. + +### Skip Ready Wait + +Connections are normally held at the gateway until the actor is ready. Pass `skipReadyWait: true` on `handle.webSocket()` to connect immediately, including while the actor is still starting or in the [sleep grace period](/docs/actors/lifecycle#shutdown-sequence). See [Skip Ready Wait](/docs/clients/javascript#skip-ready-wait) for details. + +### Async Handlers + +The `onWebSocket` handler can be async, allowing you to perform async code before setting up event listeners: + +## API Reference + +- [`WebSocketContext`](/typedoc/interfaces/rivetkit.mod.WebSocketContext.html) - Context for WebSocket handlers +- [`UniversalWebSocket`](/typedoc/interfaces/rivetkit.mod.UniversalWebSocket.html) - Universal WebSocket interface +- [`handleRawWebSocketHandler`](/typedoc/functions/rivetkit.mod.handleRawWebSocketHandler.html) - Function to handle raw WebSocket +- [`UpgradeWebSocketArgs`](/typedoc/interfaces/rivetkit.mod.UpgradeWebSocketArgs.html) - Arguments for WebSocket upgrade + +_Source doc path: /docs/actors/websocket-handler_ diff --git a/.agents/skills/rivetkit/reference/actors/workflows.md b/.agents/skills/rivetkit/reference/actors/workflows.md new file mode 100644 index 0000000..9c59975 --- /dev/null +++ b/.agents/skills/rivetkit/reference/actors/workflows.md @@ -0,0 +1,228 @@ +# Workflows + +> Source: `src/content/docs/actors/workflows.mdx` +> Canonical URL: https://rivet.dev/docs/actors/workflows +> Description: Build durable, replayable run loops in Rivet Actors with steps, queue waits, timers, and rollback. + +--- +Use workflows for durable, multi-step execution with replay safety. + +## What are workflows? + +A workflow is a durable, replayable run handler for a Rivet Actor. + +- Survives restarts: workflow progress is saved automatically. +- Re-runs safely: replay follows the same recorded steps. +- Event-driven: workflows can pause for queue messages, then continue. + +## Getting started + +### Simple workflow + +Use this when you need a short multi-step sequence. + +### Loops + +This is the recommended workflow shape for most actor workloads. + +- Use a queue wait inside the loop to receive the next unit of work. +- Keep actor state changes in a single workflow loop. +- This gives you one durable workflow that manages all actor progress. + +### Setup & teardown + +Use this when the workflow should initialize resources, process queued commands, then clean up. + +## Features + +### Queue + +Use this for fire-and-forget commands where the client does not need a reply. + +Use the `Loops` example above as the baseline pattern. + +### Request/response (using queue) + +Use this when the caller needs a response from queued processing. + +### Timers + +Use queue messages as the trigger source, then sleep durably inside the workflow. + +### Join + +Use `join` when several independent tasks can run in parallel. + +### Race + +Use `race` when you need first-winner behavior. + +### Timeouts + +Use step timeouts and retries for slow or flaky dependencies. + +Step timeouts are critical by default and fail immediately. Set `retryOnTimeout: true` if a timeout should retry like any other error using `maxRetries`. + +Workflows use roll-forward semantics everywhere. When a step throws, any `state` or `vars` mutations it made before failing are never rolled back, whether the step retries or the failure is caught by `tryStep` or `try`. The next attempt observes whatever the failed attempt already wrote, so write steps idempotently: check before you increment, or move the mutation after the fallible work. + +### Handling terminal failures as data + +Use `tryStep` when a step failure should produce data instead of failing the whole workflow. + +Use `try` when you want to recover from terminal `step`, `join`, or `race` failures inside a named block. + +```ts +async function runPaymentFlow(ctx: any) { + return await ctx.try("payment-flow", async (blockCtx: any) => { + const auth = await blockCtx.step("authorize", async (blockCtx) => + authorizeOrder("order-123"), + ); + const capture = await blockCtx.step("capture", async (blockCtx) => + captureOrder("order-123"), + ); + return { auth, capture }; + }); +} + +async function authorizeOrder(orderId: string): Promise { + return `auth-${orderId}`; +} + +async function captureOrder(orderId: string): Promise { + return `capture-${orderId}`; +} +``` + +- `tryStep` and `try` only catch terminal failures. Retry backoff, sleeps, queue waits, eviction, and history divergence still rethrow. +- Catching a failure does not undo it. `state` and `vars` mutations made before the failure remain visible after `tryStep` or `try` returns, so use explicit compensating steps when a caught failure needs cleanup. +- `RollbackError` is not caught by default. Pass `catch: ["rollback"]` when you want rollback failures returned as data. + +### Error hooks + +Use `onError` when you want a best-effort notification for workflow failures. + +- Step failures include the attempt number, retry counts, whether the step will retry, and the next retry delay. +- Workflow failures also include terminal errors outside steps, such as rollback failures or code/history mismatches. +- The hook is observational. It is not part of workflow replay, so use it for logging, metrics, or updating non-critical actor state. +- This is also a good place to forward workflow failures to Sentry or another error reporting pipeline. + +### Rollback + +Use rollback checkpoints before steps that have compensating actions. + +## Patterns + +### Store workflow progress in state + broadcast + +Store progress in `state` so replay and recovery always restore it. Broadcast state changes so clients can render progress in realtime. + +### Cron (queue-driven) + +Rivet scheduling triggers actions. For cron-like workflows, use a small scheduled action as a bridge that enqueues work, then process that work in the workflow loop. + +These are common workflow shapes used in production systems. + +### Queue-driven worker + +Use this when external systems enqueue work and the actor should process each item durably. + +### Setup & teardown + +Use this when you need one-time initialization before a long-lived loop, plus cleanup when the actor stops sleeping or is destroyed. + +### Human approval gate + +Use this when an operation must pause for a user or system decision before continuing. + +### Fan-out / fan-in (join) + +Use this when independent work items can run in parallel and you need a single merged result. + +### Batch drainer + +Use this when throughput matters and handling one message at a time is too expensive. + +### Coordinator -> worker RPC + +Use this when one actor orchestrates work by calling actions on other actors. + +### Request/response over queue (async RPC) + +Use this when you want decoupled actor-to-actor communication with durable waits and explicit completion. + +### Scatter-gather across actors + +Use this when multiple actors can process independent parts of a request in parallel, then return a merged response. + +### Timeout + fallback actor + +Use this when a primary actor call might be slow or unavailable and you need a deterministic fallback path. + +### Cross-actor saga (compensating actions) + +Use this when a workflow spans multiple actors and each side effect may need compensation. + +### Signal-driven control loop + +Use this when workflow progress should be triggered by commands/events instead of fixed polling intervals. + +### Poll + backoff loop + +Use this when an external dependency has variable availability and retries should slow down after failures. + +### Child worker orchestration + +Use this when one workflow coordinates many child workers (actors or worker workflows) and manages their lifecycle. + +### Bounded drain + concurrency cap + +Use this when inbound work can spike and you need predictable per-iteration limits. + +### Versioned workflow evolution + +Use this when workflow structure changes across deployments and old histories must still replay. + +### Version gates with `getVersion` + +Use `ctx.getVersion(name, latest)` to branch behavior when you change a workflow's logic while old instances are still in flight. It returns the version this instance is pinned to at that point: + +- A fresh instance resolves to `latest`. +- An instance that already executed past this point under older code resolves to `1` (the implicit floor). + +The resolved version is recorded in history, so replays are deterministic and each instance stays on the branch it started on. Inside a loop, every iteration resolves independently, so in-flight iterations finish on the old branch while new iterations pick up `latest`. + +`latest` must be an integer `>= 1`, and the gate name must be unique within its scope like any other entry. Once every old instance has drained, retire the gate by replacing the call with `ctx.removed(name, "version_check")`. + +### Checkpoint-friendly loop design + +Use this when you need reliable replay and resume semantics across crashes and restarts. + +## Migrations + +- Keep workflow entry names stable once deployed. +- If an old entry was removed or renamed, call `ctx.removed(name, originalType)`. +- To change behavior at a point while old instances are still running, gate it with `ctx.getVersion(name, latest)` (see [Version gates](#version-gates-with-getversion)). +- This keeps replay compatible across deployments. + +## Step-only access to actor APIs + +`state`, `vars`, `db`, `client()`, and connection/event APIs are only valid inside `ctx.step(...)` callbacks. + +Use non-step workflow code for orchestration only: queue waits, sleeps, loops, joins, races, and rollback boundaries. Keep actor-local side effects in steps. + +## Debugging + +- `GET /inspector/workflow-history` returns workflow history status for an actor. +- Response includes `isWorkflowEnabled` and `history`. +- In non-dev mode, inspector endpoints require authorization. + +## Recommendations + +- Prefer queue-driven loops for long-lived workflows. +- Structure long-lived workflows with setup and teardown around the main loop. +- Keep actor state changes and side effects inside steps. +- Store workflow progress in `state` and broadcast updates as progress changes. +- Use timeouts and rollback for external side effects. +- Write step bodies idempotently. `state` and `vars` mutations from a failed attempt are never rolled back, whether the step retries or `tryStep`/`try` catches the failure. + +_Source doc path: /docs/actors/workflows_ diff --git a/.agents/skills/rivetkit/reference/cli.md b/.agents/skills/rivetkit/reference/cli.md new file mode 100644 index 0000000..34880ea --- /dev/null +++ b/.agents/skills/rivetkit/reference/cli.md @@ -0,0 +1,103 @@ +# CLI + +> Source: `src/content/docs/cli.mdx` +> Canonical URL: https://rivet.dev/docs/cli +> Description: Reference for the optional rivet CLI: deploy to Rivet Compute and run local dev for serverless platforms. + +--- +The `rivet` CLI (`@rivetkit/cli`) is optional. You only need it for: + +| Use case | Command | +| --- | --- | +| Deploy to Rivet Compute | `rivet deploy` | +| Local dev for serverless platforms (Cloudflare, Supabase) | `rivet dev --provider ` | + +Run it with your package runner: + +```bash +npx @rivetkit/cli +``` + +| Command | Description | +| --- | --- | +| `rivet dev` | Run a local engine and your handler's dev server. | +| `rivet deploy` | Build and deploy the project to Rivet Cloud. | +| `rivet engine` | Run the bundled `rivet-engine` binary directly. | +| `rivet setup-ci` | Install the GitHub Actions deploy workflow. | + +## `rivet dev` + +Starts a local engine, spawns your dev server, and registers the serverless runner pointing at it. The engine keeps running across restarts; Ctrl-C stops only the dev server. + +```bash +rivet dev [--provider ] [--port N] [--fn-name NAME] [--url URL] [-- ...] +``` + +`--provider` selects how the dev server is launched. Anything after `--` is appended to the preset command (or is the command to run when no provider is set). + +| `--provider` | Spawns | Port | +| --- | --- | --- | +| _(omitted)_ | your `-- ` (needs `--port`) | from `--port` | +| `serverless` | your `-- ` (gets `PORT`) | auto | +| `cloudflare` | `wrangler dev` | `8787` | +| `supabase` | `supabase functions serve` | `54321` | +| `none` | nothing (engine only) | — | + +For `cloudflare`, the CLI also passes the engine endpoint as `--var RIVET_ENDPOINT:...`, so the Worker connects back with no `wrangler.toml` config. + +| Flag | Description | +| --- | --- | +| `--port` | Handler port. Required without a provider unless `--url` is set. | +| `--fn-name` | Supabase function name (default `rivet`). | +| `--url` | Explicit handler URL, overriding port and path. | +| `--engine-binary` | Path to a `rivet-engine` binary. | + +## `rivet deploy` + +Builds and pushes your project's Docker image and upserts the managed pool, printing the dashboard URL. See [Deploying to Rivet Compute](/docs/deploy/rivet-compute). + +```bash +rivet deploy --token cloud_api_xxxxx +``` + +The token is saved to `~/.rivet/credentials` (also read from `RIVET_CLOUD_TOKEN`), so later deploys can omit it. + +| Flag | Default | Description | +| --- | --- | --- | +| `--token` | env / credentials | Rivet Cloud API token. | +| `--namespace` | `production` | Cloud namespace. | +| `--project` / `--org` | from token | Override project/org. | +| `--dockerfile` | `Dockerfile` | Dockerfile to build. | +| `--build-context` | `.` | Docker build context. | +| `--env KEY=VAL` | — | Environment override, repeatable. | +| `--image` | project slug | Image repository name. | +| `--tag` | git short SHA | Image tag. | + +## `rivet engine` + +Runs the bundled `rivet-engine` binary directly, against the same local database and ports as `rivet dev`. Arguments are forwarded verbatim. + +```bash +rivet engine nuke # wipe local engine state +rivet engine wf list # inspect workflows +``` + +## `rivet setup-ci` + +Installs `.github/workflows/rivet-deploy.yml`, which deploys to Rivet Cloud on push and pull request. Add `--force` to overwrite. Then set the token secret: + +```bash +gh secret set RIVET_CLOUD_TOKEN +``` + +## Engine binary resolution + +`rivet dev` and `rivet engine` resolve the `rivet-engine` binary from, in order: `--engine-binary`, `RIVET_ENGINE_BINARY_PATH`, a binary bundled next to the CLI, a local `target/{debug,release}` build, then an auto-downloaded release. Set `RIVETKIT_ENGINE_AUTO_DOWNLOAD=0` to require a local binary. + +## Related + +- [Deploying to Rivet Compute](/docs/deploy/rivet-compute) +- [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) +- [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) + +_Source doc path: /docs/cli_ diff --git a/.agents/skills/rivetkit/reference/clients/javascript.md b/.agents/skills/rivetkit/reference/clients/javascript.md new file mode 100644 index 0000000..689d79b --- /dev/null +++ b/.agents/skills/rivetkit/reference/clients/javascript.md @@ -0,0 +1,120 @@ +# Node.js & Bun + +> Source: `src/content/docs/clients/javascript.mdx` +> Canonical URL: https://rivet.dev/docs/clients/javascript +> Description: Connect JavaScript apps to Rivet Actors. + +--- +## Getting Started + +See the [backend quickstart guide](/docs/actors/quickstart/backend) for getting started. + +## Minimal Client + +## Stateless vs Stateful + +## Getting Actors + +## Connection Parameters + +Use `params` for static connection parameters. Use `getParams` when the value can change between connection attempts, such as refreshing a JWT before each `.connect()` or reconnect. + +## Subscribing to Events + +## Connection Lifecycle + +## Low-Level HTTP & WebSocket + +For actors that implement `onRequest` or `onWebSocket`, call them directly: + +```ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("history"); +const history = await response.json(); + +const ws = await handle.webSocket("stream"); +ws.addEventListener("message", (event) => { + console.log("message:", event.data); +}); +ws.send("hello"); +``` + +## Calling from Backend + +## Error Handling + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`createClient()` automatically reads: + +- `RIVET_ENDPOINT` (endpoint) +- `RIVET_NAMESPACE` +- `RIVET_TOKEN` +- `RIVET_RUNNER` + +Defaults to `http://localhost:6420` when unset. RivetKit runs on port 6420 by default. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, use your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## Advanced + +### Skip Ready Wait + +Requests are normally held at the gateway until the actor is ready to accept traffic. An actor is not ready while it's still starting (before `onWake` finishes) or while it's in the [sleep grace period](/docs/actors/lifecycle#shutdown-sequence) (running `onSleep`, `waitUntil`, and pending disconnects). + +Pass `skipReadyWait: true` on the [low-level HTTP and WebSocket APIs](#low-level-http--websocket) to deliver immediately and reach the actor's `onRequest` / `onWebSocket` handler in either window: + +```ts @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("/healthz", { + skipReadyWait: true, +}); + +const ws = await handle.webSocket("probe", undefined, { + skipReadyWait: true, +}); +``` + +Requests can still return transient lifecycle or gateway errors. Retry once the actor is available again. + +- `actor.stopping`: the actor has fully stopped, i.e. the sleep grace period has ended but it has not yet restarted. +- `guard.actor_stopped_while_waiting`: the request reached the actor tunnel, but the actor stopped before the gateway received a response. +- `guard.tunnel_request_aborted`: the actor tunnel aborted the request before a response started. +- `guard.tunnel_message_timeout`: the gateway dropped the in-flight tunnel request after its tunnel message timeout. +- `guard.tunnel_response_closed`: the actor tunnel closed before sending a response. +- `guard.gateway_response_start_timeout`: the gateway timed out waiting for the actor response to start. + +## API Reference + +**Package:** [rivetkit](https://www.npmjs.com/package/rivetkit) + +See the [RivetKit client overview](/docs/clients). + +- [`createClient`](/typedoc/functions/rivetkit.client_mod.createClient.html) - Create a client +- [`Client`](/typedoc/types/rivetkit.mod.Client.html) - Client type + +_Source doc path: /docs/clients/javascript_ diff --git a/.agents/skills/rivetkit/reference/clients/react.md b/.agents/skills/rivetkit/reference/clients/react.md new file mode 100644 index 0000000..9b976e2 --- /dev/null +++ b/.agents/skills/rivetkit/reference/clients/react.md @@ -0,0 +1,88 @@ +# React + +> Source: `src/content/docs/clients/react.mdx` +> Canonical URL: https://rivet.dev/docs/clients/react +> Description: Connect React apps to Rivet Actors. + +--- +## Getting Started + +See the [React quickstart guide](/docs/actors/quickstart/react) for getting started. + +## Install + +## Minimal Client + +## Stateless vs Stateful + +## Getting Actors + +## Connection Parameters + +## Subscribing to Events + +## Connection Lifecycle + +## Low-Level HTTP & WebSocket + +Use the JavaScript client for raw HTTP and WebSocket access: + +```tsx @nocheck +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const handle = client.chatRoom.getOrCreate(["general"]); + +const response = await handle.fetch("history"); +const history = await response.json(); + +const ws = await handle.webSocket("stream"); +ws.addEventListener("message", (event) => { + console.log("message:", event.data); +}); +ws.send("hello"); +``` + +## Calling from Backend + +Use the JavaScript client on your backend (Node.js/Bun). See the [JavaScript client docs](/docs/clients/javascript). + +## Error Handling + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +Don't build keys with string interpolation like `"org:${userId}"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`createRivetKit()` (and the underlying `createClient()` instance) automatically read: + +- `RIVET_ENDPOINT` +- `RIVET_NAMESPACE` +- `RIVET_TOKEN` +- `RIVET_RUNNER` + +Defaults to `http://localhost:6420` when unset. RivetKit runs on port 6420 by default. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, use your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## API Reference + +**Package:** [@rivetkit/react](https://www.npmjs.com/package/@rivetkit/react) + +- [`createRivetKit`](/docs/clients/react) - Create hooks for React +- [`useActor`](/docs/clients/react) - Hook for actor instances + +_Source doc path: /docs/clients/react_ diff --git a/.agents/skills/rivetkit/reference/clients/rust.md b/.agents/skills/rivetkit/reference/clients/rust.md new file mode 100644 index 0000000..32bebfc --- /dev/null +++ b/.agents/skills/rivetkit/reference/clients/rust.md @@ -0,0 +1,367 @@ +# Rust (Beta) + +> Source: `src/content/docs/clients/rust.mdx` +> Canonical URL: https://rivet.dev/docs/clients/rust +> Description: Connect Rust apps to Rivet Actors. + +--- +Rust support is in beta. The supported public Rust API is `rivetkit` and `rivetkit::client`; lower-level crates are internal implementation details and do not carry a stability guarantee. See the full API reference on [docs.rs/rivetkit](https://docs.rs/rivetkit), or the runnable [`hello-world-rust`](https://github.com/rivet-dev/rivet/tree/main/examples/hello-world-rust) example. + +## Getting Started + +See the [Rust quickstart guide](/docs/actors/quickstart/rust) for getting started. + +## Install + +Add the `rivetkit` crate and its companions: + +```sh +cargo add rivetkit anyhow async-trait +cargo add serde --features derive +cargo add tokio --features full +``` + +The Rust client is strongly typed. It shares the same action and event types as your actor, so define your actor in `src/lib.rs` and import those types from both your server and your client. There is no need to redefine the actor on the client. See [Define Your Actor](/docs/actors/quickstart/rust#define-your-actor) in the quickstart for the actor definition this page builds on. + +## Minimal Client + +```rust @nocheck +use counter::{Counter, Increment}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + let count = counter.send(Increment { amount: 1 }).await?; + println!("New count: {count}"); + + Ok(()) +} +``` + +`counter` here is your crate name (the package `name` in `Cargo.toml`, with dashes as underscores). `Counter` and `Increment` are the types you defined alongside your actor. + +## Stateless vs Stateful + +```rust @nocheck +use counter::{Counter, Increment, NewCount}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + + // Stateless: each call is independent + counter.send(Increment { amount: 1 }).await?; + + // Stateful: keep a connection open for realtime events + let connection = counter.connect(); + connection + .on::(|event| println!("count: {}", event.count)) + .await; + connection.send(Increment { amount: 1 }).await?; + + connection.disconnect().await; + Ok(()) +} +``` + +A stateless call on the handle opens a short-lived request per action. A connection keeps a WebSocket open so you can receive events and reuse it across calls. + +## Getting Actors + +```rust @nocheck +use counter::Counter; +use rivetkit::{ + client::{Client, ClientConfig, GetOrCreateOptions}, + prelude::*, + TypedClientExt, +}; +use serde_json::json; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + // Get or create an actor + let room = client.get_or_create_typed_default::("counter", ["room-42"])?; + + // Get an existing actor handle (fails when used if the actor does not exist) + let existing = client.get_typed_default::("counter", ["room-42"])?; + + // Create a new actor with input + let created = client.get_or_create_typed::( + "counter", + ["game-1"], + GetOrCreateOptions { + create_with_input: Some(json!({ "mode": "ranked" })), + ..Default::default() + }, + )?; + + // Get an actor handle by ID + let by_id = client.get_for_id("counter", "actor-id", Default::default())?; + + // Resolve the actor ID + let resolved_id = room.inner().resolve().await?; + println!("Resolved ID: {resolved_id}"); + + Ok(()) +} +``` + +`get_typed_default` / `get_or_create_typed_default` use default options. The non-default variants (`get_typed` / `get_or_create_typed`) take `GetOptions` / `GetOrCreateOptions` for connection parameters, input, and region. + +## Connection Parameters + +Pass connection parameters through the handle options. They are delivered to the actor's `create_conn_state` callback: + +```rust @nocheck +use counter::Counter; +use rivetkit::{ + client::{Client, ClientConfig, GetOrCreateOptions}, + prelude::*, + TypedClientExt, +}; +use serde_json::json; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + let chat = client.get_or_create_typed::( + "counter", + ["general"], + GetOrCreateOptions { + params: Some(json!({ "authToken": "jwt-token-here" })), + ..Default::default() + }, + )?; + + let connection = chat.connect(); + connection.disconnect().await; + Ok(()) +} +``` + +## Subscribing to Events + +`on` registers a typed callback for an event and returns once the subscription is registered: + +```rust @nocheck +use counter::{Counter, NewCount}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let connection = client + .get_or_create_typed_default::("counter", ["general"])? + .connect(); + + connection + .on::(|event| println!("count changed: {}", event.count)) + .await; + + Ok(()) +} +``` + +Event callbacks are synchronous and run for every matching event. The actor's emitted event type (here `NewCount`) is decoded into the typed value for you. + +## Connection Lifecycle + +The lower-level connection exposes lifecycle callbacks and the current status. Reach it with `connection.inner()`: + +```rust @nocheck +use counter::Counter; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let connection = client + .get_or_create_typed_default::("counter", ["general"])? + .connect(); + let inner = connection.inner().clone(); + + inner.on_open(|| println!("connected")).await; + inner.on_close(|| println!("disconnected")).await; + inner.on_error(|message| eprintln!("error: {message}")).await; + inner + .on_status_change(|status| println!("status: {status:?}")) + .await; + + println!("current status: {:?}", inner.conn_status()); + + connection.disconnect().await; + Ok(()) +} +``` + +`ConnectionStatus` is one of `Idle`, `Connecting`, `Connected`, or `Disconnected`. Connections reconnect automatically with backoff until you call `disconnect`. + +## Low-Level HTTP & WebSocket + +For actors that implement `on_request` or `on_websocket`, call them directly on the untyped handle (`handle.inner()`). `fetch` returns a `reqwest::Response`, and `web_socket` returns a `tokio_tungstenite` stream. This example also needs a few extra crates: + +```sh +cargo add futures-util tokio-tungstenite +cargo add reqwest --features json +``` + +```rust @nocheck +use counter::Counter; +use futures_util::{SinkExt, StreamExt}; +use reqwest::{header::HeaderMap, Method}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; +use tokio_tungstenite::tungstenite::Message; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let handle = client.get_or_create_typed_default::("counter", ["general"])?; + + // Raw HTTP request + let response = handle + .inner() + .fetch("history", Method::GET, HeaderMap::new(), None) + .await?; + let history: Vec = response.json().await?; + println!("history: {history:?}"); + + // Raw WebSocket connection + let mut ws = handle.inner().web_socket("stream", None).await?; + ws.send(Message::text("hello")).await?; + if let Some(message) = ws.next().await { + println!("received: {:?}", message?); + } + + Ok(()) +} +``` + +## Calling from Backend + +The client is a normal Tokio type, so you can hold it in your backend (Axum, Actix, etc.) and call actors from request handlers. The client is `Clone` and cheap to share: + +```rust @nocheck +use counter::{Counter, Increment}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +async fn increment(client: Client) -> Result { + let counter = client.get_or_create_typed_default::("counter", ["server-counter"])?; + let count = counter.send(Increment { amount: 1 }).await?; + Ok(count) +} +``` + +## Error Handling + +Action and connection calls return `anyhow::Result`. Actor-side errors surface as an `anyhow::Error` carrying the error group, code, message, and metadata: + +```rust @nocheck +use counter::{Counter, Increment}; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + let counter = client.get_or_create_typed_default::("counter", ["my-counter"])?; + + match counter.send(Increment { amount: 1 }).await { + Ok(count) => println!("count: {count}"), + Err(error) => eprintln!("action failed: {error:#}"), + } + + Ok(()) +} +``` + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```rust @nocheck +use counter::Counter; +use rivetkit::{ + client::{Client, ClientConfig}, + prelude::*, + TypedClientExt, +}; + +#[tokio::main] +async fn main() -> Result<()> { + let client = Client::new(ClientConfig::new("http://localhost:6420").namespace("default")); + + // Compound key: [org, room] + let room = client.get_or_create_typed_default::("counter", ["org-acme", "general"])?; + let actor_id = room.inner().resolve().await?; + println!("Actor ID: {actor_id}"); + + Ok(()) +} +``` + +Keys accept arrays of `&str` or `String` (`["org-acme", "general"]`). Don't build keys with string interpolation like `format!("org:{user_id}")` when `user_id` contains user data. Use arrays instead to prevent key injection attacks. + +### Configuration + +`ClientConfig::new(endpoint)` is a builder. The endpoint is always required; there is no default. Common options: + +```rust @nocheck +use rivetkit::client::ClientConfig; + +let config = ClientConfig::new("http://localhost:6420") + .namespace("default") + .token("pk_...") + .pool_name("my-pool") + .header("x-custom", "value"); +``` + +- `namespace` - target namespace (defaults to the engine's configured namespace). +- `token` - authentication token for the engine. +- `pool_name` - runner pool to target. +- `header` / `headers` - extra HTTP headers sent with each request. +- `max_input_size` - cap on encoded action input size. + +For serverless deployments, set the endpoint to your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints) for details. + +## API Reference + +See the full client API documentation on [docs.rs/rivetkit-client](https://docs.rs/rivetkit-client/latest/rivetkit_client/). + +_Source doc path: /docs/clients/rust_ diff --git a/.agents/skills/rivetkit/reference/clients/swift.md b/.agents/skills/rivetkit/reference/clients/swift.md new file mode 100644 index 0000000..c760645 --- /dev/null +++ b/.agents/skills/rivetkit/reference/clients/swift.md @@ -0,0 +1,454 @@ +# Swift + +> Source: `src/content/docs/clients/swift.mdx` +> Canonical URL: https://rivet.dev/docs/clients/swift +> Description: Connect Swift apps to Rivet Actors. + +--- +## Install + +Add the Swift package dependency and import `RivetKitClient`: + +```swift +// Package.swift +dependencies: [ + .package(url: "https://github.com/rivet-dev/rivetkit-swift", from: "2.0.0") +] + +targets: [ + .target( + name: "MyApp", + dependencies: [ + .product(name: "RivetKitClient", package: "rivetkit-swift") + ] + ) +] +``` + +## Minimal Client + +### Endpoint URL + +```swift +import RivetKitClient + +let config = try ClientConfig( + endpoint: "https://my-namespace:pk_...@api.rivet.dev" +) +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["my-counter"]) +let count: Int = try await handle.action("increment", 1, as: Int.self) +``` + +### Explicit Fields + +```swift +import RivetKitClient + +let config = try ClientConfig( + endpoint: "https://api.rivet.dev", + namespace: "my-namespace", + token: "pk_..." +) +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["my-counter"]) +let count: Int = try await handle.action("increment", 1, as: Int.self) +``` + +## Stateless vs Stateful + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["my-counter"]) + +// Stateless: each call is independent +let current: Int = try await handle.action("getCount", as: Int.self) +print("Current count: \(current)") + +// Stateful: keep a connection open for realtime events +let conn = handle.connect() + +// Subscribe to events using AsyncStream +let eventTask = Task { + for await count in await conn.events("count", as: Int.self) { + print("Event: \(count)") + } +} + +_ = try await conn.action("increment", 1, as: Int.self) + +eventTask.cancel() +await conn.dispose() +await client.dispose() +``` + +## Getting Actors + +```swift +import RivetKitClient + +struct GameInput: Encodable { + let mode: String +} + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +// Get or create an actor +let room = client.getOrCreate("chatRoom", ["room-42"]) + +// Get an existing actor (fails if not found) +let existing = client.get("chatRoom", ["room-42"]) + +// Create a new actor with input +let created = try await client.create( + "game", + ["game-1"], + options: CreateOptions(input: GameInput(mode: "ranked")) +) + +// Get actor by ID +let byId = client.getForId("chatRoom", "actor-id") + +// Resolve actor ID +let resolvedId = try await room.resolve() +print("Resolved ID: \(resolvedId)") + +await client.dispose() +``` + +Actions support positional overloads for 0–5 args: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("counter", ["my-counter"]) + +let count: Int = try await handle.action("getCount") +let updated: String = try await handle.action("rename", "new-name") +let ok: Bool = try await handle.action("setScore", "user-1", 42) + +print("Count: \(count), Updated: \(updated), OK: \(ok)") +await client.dispose() +``` + +If you need more than 5 arguments, use the raw JSON fallback: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("counter", ["my-counter"]) + +let args: [JSONValue] = [ + .string("user-1"), + .number(.int(42)), + .string("extra"), + .string("more"), + .string("args"), + .string("here") +] +let ok: Bool = try await handle.action("setScore", args: args, as: Bool.self) +print("OK: \(ok)") + +await client.dispose() +``` + +## Connection Parameters + +```swift +import RivetKitClient + +struct ConnParams: Encodable { + let authToken: String +} + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +let chat = client.getOrCreate( + "chatRoom", + ["general"], + options: GetOrCreateOptions(params: ConnParams(authToken: "jwt-token-here")) +) + +let conn = chat.connect() + +// Use the connection... +for await status in await conn.statusChanges() { + print("Status: \(status.rawValue)") + if status == .connected { + break + } +} + +await conn.dispose() +await client.dispose() +``` + +## Subscribing to Events + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let conn = client.getOrCreate("chatRoom", ["general"]).connect() + +// Subscribe to events using AsyncStream +let messageTask = Task { + for await (from, body) in await conn.events("message", as: (String, String).self) { + print("\(from): \(body)") + } +} + +// For one-time events, break after receiving +let gameOverTask = Task { + for await _ in await conn.events("gameOver", as: Void.self) { + print("done") + break + } +} + +// Let it run for a bit +try await Task.sleep(for: .seconds(5)) + +// Cancel when done +messageTask.cancel() +gameOverTask.cancel() +await conn.dispose() +await client.dispose() +``` + +Event streams support 0–5 typed arguments. If you need raw values or more than 5 arguments, use `JSONValue`: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let conn = client.getOrCreate("chatRoom", ["general"]).connect() + +let rawTask = Task { + for await args in await conn.events("message") { + print(args) + } +} + +try await Task.sleep(for: .seconds(5)) +rawTask.cancel() +await conn.dispose() +await client.dispose() +``` + +## Connection Lifecycle + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let conn = client.getOrCreate("chatRoom", ["general"]).connect() + +// Monitor status changes (immediately yields current status) +let statusTask = Task { + for await status in await conn.statusChanges() { + print("status: \(status.rawValue)") + } +} + +// Monitor errors +let errorTask = Task { + for await error in await conn.errors() { + print("error: \(error.group).\(error.code)") + } +} + +// Monitor open/close events +let openTask = Task { + for await _ in await conn.opens() { + print("connected") + } +} + +let closeTask = Task { + for await _ in await conn.closes() { + print("disconnected") + } +} + +// Check current status +let current = await conn.currentStatus +print("Current status: \(current.rawValue)") + +// Let it run for a bit +try await Task.sleep(for: .seconds(5)) + +// Cleanup +statusTask.cancel() +errorTask.cancel() +openTask.cancel() +closeTask.cancel() +await conn.dispose() +await client.dispose() +``` + +## Low-Level HTTP & WebSocket + +For actors that implement `onRequest` or `onWebSocket`, you can call them directly: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("chatRoom", ["general"]) + +// Raw HTTP request +let response = try await handle.fetch("history") +let history: [String] = try response.json([String].self) +print("History: \(history)") + +// Raw WebSocket connection +let websocket = try await handle.websocket(path: "stream") +try await websocket.send(text: "hello") +let message = try await websocket.receive() +print("Received: \(message)") + +await client.dispose() +``` + +## Calling from Backend + +Use the same client in server-side Swift (Vapor, Hummingbird, etc.): + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +let handle = client.getOrCreate("counter", ["server-counter"]) +let count: Int = try await handle.action("increment", 1, as: Int.self) +print("Count: \(count)") + +await client.dispose() +``` + +## Error Handling + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +do { + _ = try await client.getOrCreate("user", ["user-123"]) + .action("updateUsername", "ab", as: String.self) +} catch let error as ActorError { + print("Error code: \(error.code)") + print("Metadata: \(String(describing: error.metadata))") +} + +await client.dispose() +``` + +If you need an untyped response, you can decode to `JSONValue`: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) +let handle = client.getOrCreate("data", ["raw"]) + +let value: JSONValue = try await handle.action("getRawPayload") +print("Raw value: \(value)") + +await client.dispose() +``` + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```swift +import RivetKitClient + +let config = try ClientConfig(endpoint: "http://localhost:6420") +let client = RivetKitClient(config: config) + +// Use compound keys for hierarchical addressing +let room = client.getOrCreate("chatRoom", ["org-acme", "general"]) +let actorId = try await room.resolve() +print("Actor ID: \(actorId)") + +await client.dispose() +``` + +Don't build keys with string interpolation like `"org:\(userId)"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Variables + +`ClientConfig` reads optional values from environment variables: + +- `RIVET_NAMESPACE` - Namespace (can also be in endpoint URL) +- `RIVET_TOKEN` - Authentication token (can also be in endpoint URL) +- `RIVET_RUNNER` - Runner name (defaults to `"default"`) + +The `endpoint` parameter is always required. There is no default endpoint. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, set the endpoint to your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## API Reference + +### Client +- `RivetKitClient(config:)` - Create a client with a config +- `ClientConfig` - Configure endpoint, namespace, and token +- `client.get()` / `getOrCreate()` / `getForId()` / `create()` - Get actor handles +- `client.dispose()` - Dispose the client and all connections + +### ActorHandle +- `handle.action(name, args..., as:)` - Stateless action call +- `handle.connect()` - Create a stateful connection +- `handle.resolve()` - Get the actor ID +- `handle.getGatewayUrl()` - Get the raw gateway URL +- `handle.fetch(path, request:)` - Raw HTTP request +- `handle.websocket(path:)` - Raw WebSocket connection + +### ActorConnection +- `conn.action(name, args..., as:)` - Action call over WebSocket +- `conn.events(name, as:)` - AsyncStream of typed events +- `conn.statusChanges()` - AsyncStream of status changes +- `conn.errors()` - AsyncStream of connection errors +- `conn.opens()` - AsyncStream that yields on connection open +- `conn.closes()` - AsyncStream that yields on connection close +- `conn.currentStatus` - Current connection status +- `conn.dispose()` - Close the connection + +### Types +- `ActorConnStatus` - Connection status enum (`.idle`, `.connecting`, `.connected`, `.disconnected`, `.disposed`) +- `ActorError` - Typed actor errors with `group`, `code`, `message`, `metadata` +- `JSONValue` - Raw JSON value for untyped responses + +_Source doc path: /docs/clients/swift_ diff --git a/.agents/skills/rivetkit/reference/clients/swiftui.md b/.agents/skills/rivetkit/reference/clients/swiftui.md new file mode 100644 index 0000000..4ae65d8 --- /dev/null +++ b/.agents/skills/rivetkit/reference/clients/swiftui.md @@ -0,0 +1,359 @@ +# SwiftUI + +> Source: `src/content/docs/clients/swiftui.mdx` +> Canonical URL: https://rivet.dev/docs/clients/swiftui +> Description: Build SwiftUI apps with Rivet Actors. + +--- +## Install + +Add the Swift package dependency and import `RivetKitSwiftUI`: + +```swift +// Package.swift +dependencies: [ + .package(url: "https://github.com/rivet-dev/rivetkit-swift", from: "2.0.0") +] + +targets: [ + .target( + name: "MyApp", + dependencies: [ + .product(name: "RivetKitSwiftUI", package: "rivetkit-swift") + ] + ) +] +``` + +`RivetKitSwiftUI` re-exports `RivetKitClient` and `SwiftUI`, so a single import covers both. + +## Minimal Client + +```swift HelloWorldApp.swift +import RivetKitSwiftUI +import SwiftUI + +@main +struct HelloWorldApp: App { + var body: some Scene { + WindowGroup { + ContentView() + .rivetKit(endpoint: "https://my-namespace:pk_...@api.rivet.dev") + } + } +} +``` + +```swift ContentView.swift +import RivetKitSwiftUI +import SwiftUI + +struct ContentView: View { + @Actor("counter", key: ["my-counter"]) private var counter + @State private var count = 0 + + var body: some View { + VStack(spacing: 16) { + Text("\(count)") + .font(.system(size: 64, weight: .bold, design: .rounded)) + + Button("Increment") { + counter.send("increment", 1) + } + .disabled(!counter.isConnected) + } + .task { + count = (try? await counter.action("getCount")) ?? 0 + } + .onActorEvent(counter, "newCount") { (newCount: Int) in + count = newCount + } + } +} +``` + +## Actor Options + +The `@Actor` property wrapper always uses get-or-create semantics and accepts: + +- `name` (required) +- `key` as `String` or `[String]` (required) +- `params` (optional connection parameters) +- `createWithInput` (optional creation input) +- `createInRegion` (optional creation hint) +- `enabled` (toggle connection lifecycle) + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct ConnParams: Encodable { + let authToken: String +} + +struct ChatView: View { + @Actor( + "chatRoom", + key: ["general"], + params: ConnParams(authToken: "jwt-token"), + enabled: true + ) private var chat + + var body: some View { + Text("Chat: \(chat.connStatus.rawValue)") + } +} +``` + +## Actions + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct CounterView: View { + @Actor("counter", key: ["my-counter"]) private var counter + @State private var count = 0 + @State private var name = "" + + var body: some View { + VStack { + Text("Count: \(count)") + Text("Name: \(name)") + + Button("Fetch") { + Task { + count = try await counter.action("getCount") + name = try await counter.action("rename", "new-name") + } + } + + Button("Increment") { + counter.send("increment", 1) + } + } + } +} +``` + +## Subscribing to Events + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct GameView: View { + @Actor("game", key: ["game-1"]) private var game + @State private var count = 0 + @State private var isGameOver = false + + var body: some View { + VStack { + Text("Count: \(count)") + if isGameOver { + Text("Game Over!") + } + } + .onActorEvent(game, "newCount") { (newCount: Int) in + count = newCount + } + .onActorEvent(game, "gameOver") { + isGameOver = true + } + } +} +``` + +## Async Event Streams + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct ChatView: View { + @Actor("chatRoom", key: ["general"]) private var chat + @State private var messages: [String] = [] + + var body: some View { + List(messages, id: \.self) { message in + Text(message) + } + .task { + for await message in chat.events("message", as: String.self) { + messages.append(message) + } + } + } +} +``` + +## Connection Status + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct StatusView: View { + @Actor("counter", key: ["my-counter"]) private var counter + @State private var count = 0 + + var body: some View { + VStack { + Text("Status: \(counter.connStatus.rawValue)") + + if counter.connStatus == .connected { + Text("Connected!") + .foregroundStyle(.green) + } + + Button("Fetch via Handle") { + Task { + if let handle = counter.handle { + count = try await handle.action("getCount", as: Int.self) + } + } + } + .disabled(!counter.isConnected) + } + } +} +``` + +## Error Handling + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct UserView: View { + @Actor("user", key: ["user-123"]) private var user + @State private var errorMessage: String? + @State private var username = "" + + var body: some View { + VStack { + TextField("Username", text: $username) + + Button("Update Username") { + Task { + do { + let _: String = try await user.action("updateUsername", username) + } catch let error as ActorError { + errorMessage = "\(error.code): \(String(describing: error.metadata))" + } + } + } + + if let errorMessage { + Text(errorMessage) + .foregroundStyle(.red) + } + } + .onActorError(user) { error in + errorMessage = "\(error.group).\(error.code): \(error.message)" + } + } +} +``` + +## Concepts + +### Keys + +Keys uniquely identify actor instances. Use compound keys (arrays) for hierarchical addressing: + +```swift +import RivetKitSwiftUI +import SwiftUI + +struct OrgChatView: View { + @Actor("chatRoom", key: ["org-acme", "general"]) private var room + + var body: some View { + Text("Room: \(room.connStatus.rawValue)") + } +} +``` + +Don't build keys with string interpolation like `"org:\(userId)"` when `userId` contains user data. Use arrays instead to prevent key injection attacks. + +### Environment Configuration + +Call `.rivetKit(endpoint:)` or `.rivetKit(client:)` once at the root of your view tree: + +```swift +// With endpoint string (recommended for most apps) +@main +struct MyApp: App { + var body: some Scene { + WindowGroup { + ContentView() + .rivetKit(endpoint: "https://my-namespace:pk_...@api.rivet.dev") + } + } +} + +// With custom client (for advanced configuration) +@main +struct MyApp: App { + private let client = RivetKitClient( + config: try! ClientConfig(endpoint: "https://api.rivet.dev", token: "pk_...") + ) + + var body: some Scene { + WindowGroup { + ContentView() + .rivetKit(client: client) + } + } +} +``` + +When using `.rivetKit(endpoint:)`, the client is created once and cached per endpoint. When using `.rivetKit(client:)`, store the client as a property on `App` (not inside `body`) since SwiftUI can call `body` multiple times. + +### Environment Variables + +`ClientConfig` reads optional values from environment variables: + +- `RIVET_NAMESPACE` - Namespace (can also be in endpoint URL) +- `RIVET_TOKEN` - Authentication token (can also be in endpoint URL) +- `RIVET_RUNNER` - Runner name (defaults to `"default"`) + +The endpoint is always required. There is no default endpoint. + +### Endpoint Format + +Endpoints support URL auth syntax: + +``` +https://namespace:token@api.rivet.dev +``` + +You can also pass the endpoint without auth and provide `RIVET_NAMESPACE` and `RIVET_TOKEN` separately. For serverless deployments, set the endpoint to your app's `/api/rivet` URL. See [Endpoints](/docs/general/endpoints#url-auth-syntax) for details. + +## API Reference + +### Property Wrapper +- `@Actor(name, key:, params:, createWithInput:, createInRegion:, enabled:)` - SwiftUI property wrapper for actor connections + +### View Modifiers +- `.rivetKit(endpoint:)` - Configure client with an endpoint URL (creates cached client) +- `.rivetKit(client:)` - Configure client with a custom instance +- `.onActorEvent(actor, event) { ... }` - Subscribe to actor events (supports 0–5 typed args) +- `.onActorError(actor) { error in ... }` - Handle actor errors + +### ActorObservable +- `actor.action(name, args..., as:)` - Async action call +- `actor.send(name, args...)` - Fire-and-forget action +- `actor.events(name, as:)` - AsyncStream of typed events +- `actor.connStatus` - Current connection status +- `actor.isConnected` - Whether connected +- `actor.handle` - Underlying `ActorHandle` (optional) +- `actor.connection` - Underlying `ActorConnection` (optional) +- `actor.error` - Most recent error (optional) + +### Types +- `ActorConnStatus` - Connection status enum (`.idle`, `.connecting`, `.connected`, `.disconnected`, `.disposed`) +- `ActorError` - Typed actor errors with `group`, `code`, `message`, `metadata` + +_Source doc path: /docs/clients/swiftui_ diff --git a/.agents/skills/rivetkit/reference/cookbook/ai-agent.md b/.agents/skills/rivetkit/reference/cookbook/ai-agent.md new file mode 100644 index 0000000..1adb285 --- /dev/null +++ b/.agents/skills/rivetkit/reference/cookbook/ai-agent.md @@ -0,0 +1,127 @@ +# AI Agent + +> Source: `src/content/cookbook/ai-agent.mdx` +> Canonical URL: https://rivet.dev/cookbook/ai-agent +> Description: Build an AI agent backend with persistent memory: one Rivet Actor per conversation, queued message handling, and streaming LLM responses as realtime events. + +--- +Patterns for building AI agent backends with RivetKit, where each conversation is one Rivet Actor that owns its memory, its message queue, and its streaming output. + +## Starter Code + +Start with one of the working examples on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/ai-agent) and adapt it. The sections below describe the flagship `ai-agent` example unless a variant is called out explicitly. + +| Variant | Starter Code | Use When | +| --- | --- | --- | +| Queue-driven AI SDK agent | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/ai-agent) | You want a streaming chat agent where each conversation keeps its own persistent memory and processes one message at a time. | +| Sandbox coding agent | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/sandbox-coding-agent) | The agent should run a coding agent (Codex by default) inside an isolated [sandbox](/docs/actors/sandbox) via Docker, Daytona, or E2B. | +| Durable streams agent (experimental) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/experimental-durable-streams-ai-agent) | You want replayable, restart-safe prompt and response delivery through durable streams instead of actor state and events. | + +## Conversation Memory + +Use one actor per conversation, keyed by a conversation or agent id (see [Actor Keys](/docs/actors/keys)). The agent actor's persistent [state](/docs/actors/state) is the conversation memory: in the `ai-agent` example, `messages` and `status` live in JSON actor state and survive sleep and restarts with no external database. Every model call rebuilds the prompt from `c.state.messages` plus a system prompt, so memory and inference input are the same data. + +| Variant | Where Memory Lives | Persisted State Fields | +| --- | --- | --- | +| `ai-agent` | JSON actor state | `messages`, `status` | +| `sandbox-coding-agent` | JSON actor state plus the sandbox ACP session | `messages`, `status`, `sessionId` | +| `experimental-durable-streams-ai-agent` | Durable streams; the actor stores only its conversation id and a read cursor | `conversationId`, `promptStreamOffset` | + +## Message Handling + +In the `ai-agent` example, the client pushes user input onto the agent's `message` [queue](/docs/actors/queues) with `agent.connection.send("message", { text, sender })`. This is a queue push, not an action call. The actor's `run` hook (see [Lifecycle](/docs/actors/lifecycle)) consumes the queue serially with `for await (const queued of c.queue.iter())`. + +Serial queue consumption is the per-conversation concurrency guarantee: at most one in-flight model call per actor, with no extra locking. The `status` field (`thinking` while a model call is in flight) is UI signal only; the run loop is the actual lock. The loop also checks `c.aborted` inside the token stream so shutdown exits gracefully. + +| Variant | Message Ingress | Serialization Guarantee | +| --- | --- | --- | +| `ai-agent` | `message` queue pushed via `connection.send` | `run` hook pops one queued message at a time with `c.queue.iter()`. | +| `sandbox-coding-agent` | `sendMessage` [action](/docs/actors/actions), no queue | Each call awaits the sandbox round trip before broadcasting the result. | +| `experimental-durable-streams-ai-agent` | Durable prompt stream long-polled from `onWake` | `promptStreamOffset` is persisted per chunk, so restarts resume without reprocessing prompts. | + +## Streaming Responses + +The `ai-agent` actor broadcasts a `response` [event](/docs/actors/events) for every model text delta. The payload carries `messageId`, the per-token `delta`, the cumulative `content`, and a `done` flag (plus `error` on failure), so clients can either append deltas or idempotently replace the message by `messageId` using `content`. The example frontend replaces by `messageId`, which tolerates dropped events. The terminal broadcast has an empty `delta`, the full `content`, and `done: true`. + +Because the assistant message object lives in `c.state.messages` and is mutated in place during streaming, partial content persists if the actor restarts mid-stream. The example broadcasts once per AI SDK delta with no throttling; batching or throttling deltas is a recommended extension for high-traffic deployments, not something the example implements. + +Variant differences: `sandbox-coding-agent` sends a single `response` broadcast with `done: true` after the sandbox finishes (no incremental streaming), and `experimental-durable-streams-ai-agent` appends per-token chunks to a durable response stream, then broadcasts `responseComplete` or `responseError`. + +## Architecture + +| Topic | Summary | +| --- | --- | +| Topology | `agentManager["primary"]` singleton directory plus one `agent[agentId]` actor per conversation. | +| Ingress | Client pushes `AgentQueueMessage` payloads onto the agent's `message` queue with `connection.send`. | +| Streaming | One `response` broadcast per model delta, terminal broadcast with `done: true`. | +| Memory | Full transcript and status in JSON actor state; no external database. | + +The manager creates `AgentInfo` records and warms each agent through [actor-to-actor communication](/docs/actors/communicating-between-actors): `createAgent` calls `c.client()`, then `client.agent.getOrCreate([info.id])` and awaits `getStatus()` so the conversation actor exists before the client connects. The sandbox variant extends this topology with a `codingSandbox` actor that shares the agent's key (`codingSandbox.getOrCreate([c.key[0]])`), so the agent-to-sandbox mapping is implicit in the key space. + +**Actors** + +- **Key**: `agentManager["primary"]` +- **Responsibility**: Directory actor. Creates `AgentInfo` records, lists agents, and warms each agent actor via `c.client()`. +- **Actions** + - `createAgent` + - `listAgents` +- **Queues** + - None +- **State** + - JSON + - `agents` + +- **Key**: `agent[agentId]` +- **Responsibility**: One actor per conversation. Holds the full message history and status, consumes queued user messages in its `run` loop, calls the model via the AI SDK, and broadcasts streaming deltas. +- **Actions** + - `getHistory` + - `getStatus` +- **Queues** + - `message` +- **Events** + - `messageAdded` + - `status` + - `response` +- **State** + - JSON + - `messages` + - `status` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant AM as agentManager + participant A as agent + participant LLM as Model API + + C->>AM: createAgent(name) + AM->>A: getOrCreate([info.id]) + getStatus() + AM-->>C: AgentInfo + C->>A: connection.send("message", {text, sender}) + Note over A: run loop pops queue via c.queue.iter() + A-->>C: messageAdded (user message) + A-->>C: messageAdded (assistant placeholder) + A-->>C: status (thinking) + A->>LLM: streamText(system prompt + history) + loop each text delta + LLM-->>A: delta + A-->>C: response {messageId, delta, content, done: false} + end + A-->>C: response {delta: "", content, done: true} + A-->>C: status (idle) +``` + +## Security Checklist + +The examples ship without auth so they stay minimal. Apply this baseline before exposing an agent backend. + +- **API keys stay server-side**: `OPENAI_API_KEY` (or `ANTHROPIC_API_KEY`) is read by the AI SDK inside the actor process. The key never reaches the browser; clients only talk to the actor over RivetKit. The sandbox variant forwards keys into the sandbox env, never to the client. +- **Add authentication**: The examples have no auth, so anyone who reaches the server can create agents, list them, and message any agent whose key they can guess. Add `onBeforeConnect` or `createConnState` checks with scoped tokens as a recommended extension. See [Authentication](/docs/actors/authentication). +- **Validate and rate-limit queue payloads**: The example only skips bodies without a string `text`. Enforce payload size limits, schema validation, and per-connection rate limits as a recommended extension. +- **Derive sender identity server-side**: The example trusts the client-supplied `sender` field verbatim. Bind sender identity to the authenticated connection instead. +- **Cap or trim message history**: The example sends the full transcript on every model call with no cap. Trim or summarize old messages as a recommended extension so prompts and state stay bounded. +- **Set cost ceilings per conversation**: Add per-agent token budgets and quotas as a recommended extension. The sandbox variant runs real compute, so also enforce per-user sandbox quotas and restrict sandbox network egress. + +_Source doc path: /cookbook/ai-agent_ diff --git a/.agents/skills/rivetkit/reference/cookbook/chat-room.md b/.agents/skills/rivetkit/reference/cookbook/chat-room.md new file mode 100644 index 0000000..cb8dbe4 --- /dev/null +++ b/.agents/skills/rivetkit/reference/cookbook/chat-room.md @@ -0,0 +1,114 @@ +# Chat Room + +> Source: `src/content/cookbook/chat-room.mdx` +> Canonical URL: https://rivet.dev/cookbook/chat-room +> Description: Build a realtime chat room backend with Rivet Actors: one actor per room, SQLite-backed message history, and WebSocket broadcast to every connected client. + +--- +Patterns for building a chat room backend with RivetKit: room-scoped actors, persistent message history, and realtime delivery over WebSocket connections. + +## Starter Code + +Start with the working example on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/chat-room) and adapt it. The backend is a single `chatRoom` actor; the frontend is a React app using `@rivetkit/react` (see the [React quickstart](/docs/actors/quickstart/react)). + +| Topic | Summary | +| --- | --- | +| Room model | One `chatRoom` actor per room key. The frontend defaults the key to `general`; typing a different room name connects to a different actor. | +| History | SQLite `messages` table created in `db({ onMigrate })`, read back with `ORDER BY id ASC`. | +| Delivery | `sendMessage` inserts the row, then broadcasts a typed `newMessage` event to every connected client. | +| Identity | None in the example. `sender` is a plain action argument; production should bind identity to the connection. | + +## Room-Per-Actor Model + +Each room is one Rivet Actor instance, addressed by [key](/docs/actors/keys). The client calls `useActor({ name: "chatRoom", key: [roomId] })`, which gets-or-creates the actor for that room. This gives you: + +- **Isolation**: each room's history and connections are fully scoped to its key. Switching the room input re-keys the hook and connects to a different actor with separate history. +- **A single serialized writer**: all `sendMessage` calls for one room run through one actor, so message ordering is consistent without locks. The SQLite `AUTOINCREMENT` id is the canonical order, which is why `getHistory` sorts by `id` rather than by timestamp. +- **Natural scaling**: rooms spread across the cluster independently. A hot room does not slow down other rooms. + +## Message History Storage + +This example stores history in the actor's SQLite database, not in JSON state. Pick based on history size and query needs: + +| Approach | Use When | Implementation Guidance | +| --- | --- | --- | +| [SQLite](/docs/actors/sqlite) (what this example uses) | Large or long-lived history that needs ordering, caps, pagination, or search | Create the `messages` table in `db({ onMigrate })`, insert with parameterized queries (`c.db.execute("INSERT ... VALUES (?, ?, ?)", ...)`), and read with `ORDER BY id ASC`. History survives actor sleep and scales past what you want in memory. | +| [JSON state](/docs/actors/state) | Small recent history, for example the last 50 to 100 messages | Push onto a `messages` array in actor state and trim to a cap on every send. Simplest option, but the whole history lives in memory and there is no query layer, so it only fits bounded recent-history use cases. | + +## Broadcast Delivery + +New messages reach connected clients through a typed [event](/docs/actors/events): + +- The actor declares `events: { newMessage: event() }`, where `Message` is `{ sender, text, timestamp }`. +- The `sendMessage` [action](/docs/actors/actions) builds the message with a server-side `Date.now()` timestamp, inserts it into the `messages` table, then calls `c.broadcast("newMessage", message)` and returns the message to the caller. +- Each client subscribes with `useEvent("newMessage", ...)` and appends to its local list. The sender renders its own message through the same broadcast path as everyone else, so all clients stay on one code path. +- History load is connection-gated: once the connection is ready, the client calls `getHistory()` once to render the backlog, then relies on events for everything after. + +Use `c.broadcast(...)` for room-wide messages. For private or per-recipient payloads (such as DMs inside a room), send on the individual connection instead, which is a recommended extension beyond this example. + +## Typing Indicators And Presence (Extension) + +The example does not implement typing indicators, presence, or join/leave handling of any kind. There is no `createConnState`, `onConnect`, or `onDisconnect` in the code. If you need them, add them as ephemeral [connection](/docs/actors/connections) behavior: + +- **Keep it ephemeral**: store the username and typing flag in per-connection state, never in SQLite or persisted actor state. Presence is derived from live connections and should disappear with them. +- **Broadcast on change only**: emit a typing event when a user starts or stops typing, and a presence event from `onConnect` / `onDisconnect`, rather than polling or ticking. +- **Expire on the client**: clear a typing indicator after a short client-side timeout so a dropped connection never leaves a stuck "is typing" row. + +## Per-User Inbox (Extension) + +For offline delivery, DMs, unread counts, or notification fanout, add a `userInbox[userId]` actor per user. This is an extension beyond the example: + +- The room actor forwards each message to the inbox actor of every member via [actor-to-actor calls](/docs/actors/communicating-between-actors), so users who are not connected to the room still accumulate messages. +- The inbox actor owns per-user unread state and serves it when the user comes online, independent of which rooms they are in. +- DMs become a degenerate room: either a `chatRoom` keyed by the sorted pair of user ids, or direct inbox-to-inbox delivery if you do not need shared history semantics. + +## Actors + +- **Key**: `chatRoom[roomId]` +- **Responsibility**: Owns one chat room. Persists the room's message history in its SQLite database and broadcasts each new message to every connected client. +- **Actions** + - `sendMessage` + - `getHistory` +- **Queues** + - None +- **Events** + - `newMessage` +- **State** + - SQLite + - `messages` table: `id` (autoincrement primary key), `sender`, `text`, `timestamp` + +## Lifecycle + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant R as chatRoom + + A->>R: connect with key [roomId] + Note over R: every start runs onMigrate (CREATE TABLE IF NOT EXISTS messages) + A->>R: getHistory() + R-->>A: Message[] ordered by id + B->>R: connect with key [roomId] + B->>R: getHistory() + R-->>B: Message[] ordered by id + A->>R: sendMessage(sender, text) + Note over R: INSERT row with server timestamp + R-->>A: newMessage (broadcast) + R-->>B: newMessage (broadcast) + A->>R: disconnect + Note over R: history stays in SQLite for the next connection +``` + +## Security Checklist + +The example is intentionally minimal and skips all of the following. Add them before production: + +- **Auth before join**: any client can join any room by knowing its name, and `sender` is arbitrary client input on every call. Validate a token during [connection auth](/docs/actors/authentication), bind identity to [connection state](/docs/actors/connections), and check room membership before serving history. Never trust a sender name passed as an action argument. +- **Message length clamps**: the example accepts empty messages and has no length limit. Trim server-side, reject empty text, and clamp to a maximum length. +- **Per-connection rate limiting**: rate limit `sendMessage` per connection to stop spam and broadcast amplification. +- **Server-side timestamps and ids**: the example already does this correctly. `timestamp` comes from `Date.now()` inside the action and `id` from SQLite `AUTOINCREMENT`. Keep it that way; never accept client-supplied timestamps or ids. +- **History caps**: `getHistory` returns every row with no limit. Add a `LIMIT` plus pagination, and prune or archive old rows so a long-lived room cannot grow unbounded. +- **Parameterized queries**: the example already inserts with `?` placeholders. Keep all user-supplied text out of SQL string interpolation. + +_Source doc path: /cookbook/chat-room_ diff --git a/.agents/skills/rivetkit/reference/cookbook/collaborative-text-editor.md b/.agents/skills/rivetkit/reference/cookbook/collaborative-text-editor.md new file mode 100644 index 0000000..cacbc1f --- /dev/null +++ b/.agents/skills/rivetkit/reference/cookbook/collaborative-text-editor.md @@ -0,0 +1,157 @@ +# Collaborative Text Editor + +> Source: `src/content/cookbook/collaborative-text-editor.mdx` +> Canonical URL: https://rivet.dev/cookbook/collaborative-text-editor +> Description: Build a collaborative text editor backend with Yjs CRDTs and Rivet Actors: per-document actors relay sync and awareness updates and persist snapshots. + +--- +Patterns for building a Yjs server on RivetKit: CRDT document sync, presence and cursors, and snapshot persistence, with one Rivet Actor per document acting as a relay. + +## Starter Code + +Start with the working example on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/collaborative-document) and adapt it to your editor. It ships a React frontend with a plain textarea, remote cursor overlays, and a workspace document index. + +| Use Case | Starter Code | Common Examples | +| --- | --- | --- | +| Shared document editing | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/collaborative-document) | Notion-style docs, shared notes, pair-writing tools, form co-editing | + +## CRDT vs OT + +Two families of algorithms solve concurrent text editing. The choice decides what your server has to do. + +| Dimension | CRDT (Yjs) | Operational Transformation | +| --- | --- | --- | +| Conflict resolution model | Commutative merges. Updates apply in any order on any peer and converge to the same result. | Server transforms each operation against every concurrent operation. Correctness depends on a central sequencer. | +| Offline support | Strong. Clients keep editing locally and merge buffered updates on reconnect. | Weak. Long-lived divergence makes transformation chains complex and fragile. | +| Server role | Relay plus persistence. The server applies opaque updates and rebroadcasts them. It never needs to understand document semantics. | Authoritative transformer. The server must implement transformation logic for every operation type. | +| Library maturity | Yjs is mature and widely deployed, with bindings for ProseMirror, CodeMirror, Monaco, and others. | Production-grade implementations are mostly proprietary (Google Docs) or aging (ShareDB). | + +The example uses Yjs because CRDTs let the server stay a relay-style Rivet Actor. The actor applies each incoming update to a server-side `Y.Doc` so it can persist the merged state and serve late joiners, but it never transforms operations or arbitrates conflicts. Ordering does not matter because Yjs merges are commutative. + +## Document Actor Model + +| Topic | Summary | +| --- | --- | +| Topology | One `document[workspaceId, documentId]` actor per document plus one `documentList[workspaceId]` coordinator per workspace. | +| Sync model | Each client holds a local `Y.Doc`. The document actor relays incremental Yjs updates as broadcast [events](/docs/actors/events) and keeps a server-side merged copy in vars. | +| Persistence | Full merged Yjs snapshot overwritten in one binary [actor KV](/docs/actors/kv) key (`yjs:doc`) on every sync update. Document metadata lives in JSON [state](/docs/actors/state). | +| Queues | None. The example is purely [actions](/docs/actors/actions) plus broadcast events. | +| Presence | Yjs Awareness relayed through the same `applyUpdate` action. Per-connection `connState` tracks asserted awareness clientIds for disconnect cleanup. | + +The two-actor split follows the coordinator pattern from [Design Patterns](/docs/actors/design-patterns): the coordinator owns discovery and creation, and each document actor owns one document's realtime state. Multi-part [keys](/docs/actors/keys) scope both actors to a workspace. + +**Actors** + +- **Key**: `document[workspaceId, documentId]` +- **Responsibility**: Applies incoming sync and awareness updates to a server-side `Y.Doc` and `Awareness`, persists the merged Yjs snapshot to actor KV, and broadcasts updates to all connected collaborators. +- **Actions** + - `getContent` + - `applyUpdate` + - `getAwareness` +- **Queues** + - None +- **State** + - JSON metadata only: `title`, `createdAt`, `updatedAt` + - Binary KV key `yjs:doc` holding the full merged Yjs snapshot + - Ephemeral vars: the live `Y.Doc` and `Awareness`, created in `createVars` and rehydrated from KV on actor start + - Per-connection `connState`: `clientIds` of awareness clients asserted by that connection + +- **Key**: `documentList[workspaceId]` +- **Responsibility**: Coordinator for one workspace. Creates document actors through the actor-to-actor client and maintains the index of document summaries. +- **Actions** + - `createDocument` + - `listDocuments` + - `deleteDocument` +- **Queues** + - None +- **State** + - JSON + - `documents` array of `DocumentSummary` entries (`id`, `title`, `createdAt`, `updatedAt`) + +The coordinator's `createDocument` generates a UUID, then explicitly creates the document actor with `c.client()` and passes `{ title, createdAt }` as creation [input](/docs/actors/input), which the document actor's `createState` consumes. See [Communicating Between Actors](/docs/actors/communicating-between-actors) for the actor-to-actor client. + +## Update Relay + +A single `applyUpdate(update, kind, clientId?)` action handles both update kinds. Updates cross the action boundary as `number[]` byte arrays and are converted back to `Uint8Array` on each side. + +| Kind | Server Applies To | Persists | Broadcasts | +| --- | --- | --- | --- | +| `"sync"` | `c.vars.doc` via `Y.applyUpdate` with origin `"client"` | Full merged snapshot to KV key `yjs:doc`, then bumps `updatedAt` | `sync` event carrying the incremental update | +| `"awareness"` | `c.vars.awareness` via `applyAwarenessUpdate` with origin `"client"` | Nothing. Presence is ephemeral. | `awareness` event carrying the update | + +Note the asymmetry on the sync branch: the broadcast carries only the small incremental update, while the KV write stores the full merged document re-encoded with `Y.encodeStateAsUpdate`. + +Yjs origin tags are the echo guards that keep the relay loop-free: + +| Origin Tag | Set Where | Effect | +| --- | --- | --- | +| `"local"` | Client edits inside `doc.transact(..., "local")` | The client's update listener fires and sends `applyUpdate` to the actor. | +| `"client"` | Server applying an incoming update to its `Y.Doc` or `Awareness` | Marks the change as client-originated on the server copy. | +| `"remote"` | Client applying broadcast events or initial sync data | Update listeners early-return on `"remote"`, so a client never re-sends its own echo. | + +On connect or reconnect, the client calls `getContent` and `getAwareness`, then applies both results to its local `Y.Doc` and `Awareness` with origin `"remote"`. After that, every change flows through `applyUpdate` and the broadcast events. + +## Awareness And Presence + +Presence (user names, colors, cursor positions) rides on the Yjs Awareness protocol instead of actor state: + +- Clients set presence with `awareness.setLocalStateField` for the `user` and `cursor` fields. The awareness update listener encodes the change and sends `applyUpdate(update, "awareness", awareness.clientID)`. +- The actor records each asserted `clientId` in that connection's `connState.clientIds`, applies the update to the server-side `Awareness`, and broadcasts the `awareness` event to all peers. See [Connections](/docs/actors/connections) for per-connection state. +- `onDisconnect` reads the connection's `clientIds`, calls `removeAwarenessStates` on the server-side `Awareness`, and broadcasts the encoded removal so every remaining client drops the departed user's cursor. See [Lifecycle](/docs/actors/lifecycle) for the hook. + +Because the actor tracks which awareness clientIds belong to which connection, presence cleanup is automatic on disconnect with no client cooperation required. + +## Persistence And Compaction + +The example persists with a full-snapshot overwrite: on every `"sync"` update, the actor re-encodes the entire merged document with `Y.encodeStateAsUpdate` and overwrites the single binary KV key `yjs:doc`. There is no append-only update log and no separate compaction job. Compaction is implicit because `Y.encodeStateAsUpdate` emits one compact merged representation of the document, so Yjs merge semantics keep the stored blob compact on their own. + +| Property | Full-Snapshot Overwrite (the example) | +| --- | --- | +| Write cost | One full-document KV write per sync update, so every keystroke rewrites the whole blob. | +| Read cost | One binary KV read in `createVars` rehydrates the document on actor start. | +| Crash safety | The last completed `applyUpdate` is durable. No log replay needed. | +| Sweet spot | Small to medium documents where simplicity beats write amplification. | + +**Recommended extension (not in the example)**: for large documents or very high edit rates, switch to appending incremental updates to a KV update log and writing a merged snapshot only periodically (for example every N updates). Boot becomes snapshot plus log replay, and the snapshot write becomes the explicit compaction step that truncates the log. Adopt this only when full-snapshot writes become the measured bottleneck or the blob approaches KV value size limits. + +## Lifecycle + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant DL as documentList + participant D as document + + A->>DL: listDocuments() + A->>DL: createDocument(title) + DL->>D: create([workspaceId, documentId], input) + DL-->>A: DocumentSummary + A->>D: connect + B->>D: connect + Note over D: createVars rehydrates Y.Doc from KV "yjs:doc" + A->>D: getContent() + getAwareness() + D-->>A: encoded doc + awareness state + Note over A: local edit with origin "local" + A->>D: applyUpdate(update, "sync") + Note over D: apply with origin "client", overwrite KV snapshot + D-->>B: sync event (incremental update) + Note over B: apply with origin "remote", no echo + A->>D: applyUpdate(update, "awareness", clientId) + D-->>B: awareness event + B-->>D: disconnect + Note over D: onDisconnect removes B's awareness clientIds + D-->>A: awareness event (removal) +``` + +## Security Checklist + +The example ships with no authentication or authorization. Harden it with this baseline before production. None of these are implemented in the example. + +- **Authenticate before connect**: Anyone who knows or guesses a workspace ID can connect, and because `useActor` implicitly getOrCreates, connecting with a nonexistent workspace ID silently creates a blank `documentList` coordinator. Add connection auth so unauthenticated clients never reach an actor. See [Authentication](/docs/actors/authentication). +- **Per-document access control**: Validate that the authenticated user is allowed to access the specific `[workspaceId, documentId]` key, not just any document. +- **Cap and rate limit `applyUpdate`**: Update payloads are unvalidated `number[]` arrays with no size limit, and the example client sends one action per keystroke and per cursor move with zero throttling. Enforce payload size caps and per-connection rate limits on the server, and debounce on the client. +- **Do not trust client-asserted awareness clientIds**: The `clientId` argument to `applyUpdate` is client-supplied and trusted as-is. Derive or verify presence identity from connection-scoped server state instead. +- **Destroy actors and KV on delete**: `deleteDocument` only filters the entry out of the coordinator's index. The document actor and its KV snapshot are orphaned. On delete, also destroy the document actor and its storage, with a permission check on who may delete. + +_Source doc path: /cookbook/collaborative-text-editor_ diff --git a/.agents/skills/rivetkit/reference/cookbook/cron-jobs.md b/.agents/skills/rivetkit/reference/cookbook/cron-jobs.md new file mode 100644 index 0000000..12f7119 --- /dev/null +++ b/.agents/skills/rivetkit/reference/cookbook/cron-jobs.md @@ -0,0 +1,123 @@ +# Cron Jobs and Scheduled Tasks + +> Source: `src/content/cookbook/cron-jobs.mdx` +> Canonical URL: https://rivet.dev/cookbook/cron-jobs +> Description: Durable cron jobs with Rivet Actors: schedule.after and schedule.at timers survive restarts and crashes, plus re-arming recurring jobs and idempotent handlers. + +--- +Patterns for running durable cron jobs and scheduled tasks on Rivet Actors. Actor schedules are persistent timers owned by the engine, so a job keeps its deadline through actor sleep, restarts, upgrades, deploys, and crashes. + +## Starter Code + +Start from the working [Scheduling example on GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/scheduling). It implements a reminder service with one-shot timers, a React frontend, and live trigger events. + +## The Scheduling API + +The full API is documented in [Scheduling](/docs/actors/schedule). There are two methods, both available on the actor context: + +| Method | Behavior | +| --- | --- | +| `c.schedule.after(duration, actionName, ...args)` | Runs the named action after `duration` milliseconds. | +| `c.schedule.at(timestamp, actionName, ...args)` | Runs the named action at an exact epoch timestamp in milliseconds. | + +Key properties: + +- **Durable**: The schedule is persisted by the engine and the timer survives actor sleep, restart, upgrade, and crash. If the actor is asleep at the deadline, the engine wakes it to run the action. See [Lifecycle](/docs/actors/lifecycle). +- **Plain actions as callbacks**: The scheduled callback is an ordinary [action](/docs/actors/actions) on the same actor, invoked by name. Arguments after the action name are forwarded positionally, for example `c.schedule.after(delayMs, "triggerReminder", reminder.id)`. +- **No cancellation API**: Rivet does not currently support canceling a scheduled action. The pattern is a tombstone guard: remove the entry from [state](/docs/actors/state) and have the scheduled action no-op when it cannot find its entry. The example's `cancelReminder` and `triggerReminder` actions implement exactly this. + +## Recurring Jobs Via Re-Arm + +`c.schedule` is one-shot, so recurring jobs are built by having the scheduled action re-arm itself at the end of each run: + +Arm the first run from `onCreate` or a setup action; after that, the action keeps the chain alive by rescheduling itself. + +Re-arming with `after` measures the next run from the end of the current one, so the cadence drifts later by the job's runtime on every cycle. If runs must stay aligned to a fixed cadence, re-arm with `c.schedule.at(c.state.lastRunAt + DAY_MS, "runReport")` instead. + +The Scheduling example itself only uses one-shot reminders. A real re-arm implementation lives in the [idle world actor](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/idle/), where the `collectProduction` action credits production, updates `lastCollectedAt`, and calls a `scheduleCollection` helper that re-arms with `c.schedule.after(delayMs, "collectProduction", { buildingId })`. It also shows catch-up handling: if the action runs late, it computes how many whole intervals elapsed since the last run and credits them in one batch before re-arming. + +For multi-step jobs that need retries and progress tracking inside a single run, consider [Workflows](/docs/actors/workflows) instead of chaining schedules. + +## Durability Comparison + +| Approach | Timer Durability | Horizontal Scaling | Deploys And Restarts | +| --- | --- | --- | --- | +| `setTimeout` / `setInterval` | In-process memory only | Every replica arms its own timer, so jobs run once per instance | All pending timers are lost on restart or crash | +| `node-cron` and similar libraries | In-process memory only | Every instance runs the job unless you add external locking | Schedule resets on deploy; runs missed during downtime are skipped | +| External cron service | Lives outside your app | Needs a public HTTP endpoint plus its own dedupe and retry state | Survives your deploys but is separate infrastructure to operate | +| Rivet Actor scheduling | Persisted by the engine as a durable timer | Exactly one actor per key, so the timer is armed once rather than once per replica | Survives actor sleep, restart, upgrade, and crash | + +## Idempotency + +A scheduled action can fire more than you expect: a crash between doing the work and re-arming can cause the action to run again, and because schedules cannot be cancelled, an action can fire for an entry that was already removed. Design handlers so a duplicate firing is harmless: + +- **Store a run marker in state**: Keep a `lastRunAt` timestamp or a sequence number in actor state and update it inside the action. On each firing, compute elapsed time since the marker and skip or batch accordingly. The idle world actor's `collectProduction` does this with `lastCollectedAt` and whole-interval batching. +- **Tombstone guard for cancelled entries**: The example's `triggerReminder` looks the reminder up in `c.state.reminders` first and returns with a warning if it is gone, so a fire-after-cancel is a safe no-op. +- **Keep work and marker updates in the same action**: Actor state writes are persisted with the action, so updating the marker in the same handler that does the work keeps the two consistent. + +## Topology + +| Topology | Use When | Example Key | +| --- | --- | --- | +| Singleton job actor | One global job such as a nightly report or cleanup pass | `job["daily-report"]` | +| Actor per scheduled entity | Per-user or per-resource timers such as reminders, trials, or billing periods | `reminder[userId]` | + +The Scheduling example uses a single shared `reminderActor["main"]` key for demo simplicity. For production reminder systems, prefer one actor per user so timers, state, and load are isolated per entity. See [Keys](/docs/actors/keys). + +## Reminder Service Example + +| Topic | Summary | +| --- | --- | +| Scheduling | One-shot timers armed with `c.schedule.after(delayMs, "triggerReminder", reminder.id)` or `c.schedule.at(timestamp, "triggerReminder", reminder.id)`. | +| State | JSON state holding `reminders` and `completedCount`; the scheduled action mutates state when it fires. | +| Events | `triggerReminder` broadcasts a `reminderTriggered` event to all connected clients. See [Events](/docs/actors/events). | +| Cancellation | `cancelReminder` only removes the reminder from state; the scheduled action may still fire and no-ops via a state lookup guard. | + +**Actors** + +- **Key**: `reminderActor["main"]` +- **Responsibility**: Stores reminders in persistent state, arms a future self-action per reminder via `c.schedule`, marks reminders completed when the scheduled action fires, and broadcasts `reminderTriggered` to connected clients. +- **Actions** + - `scheduleReminder` + - `scheduleReminderAt` + - `triggerReminder` + - `getReminders` + - `cancelReminder` + - `getStats` +- **Queues** + - None +- **State** + - JSON + - `reminders` + - `completedCount` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant R as reminderActor + participant E as Engine + + C->>R: scheduleReminder(message, delayMs) + R->>E: schedule.after(delayMs, triggerReminder, id) + Note over E: schedule persisted + alarm armed + R-->>C: reminder + Note over R: actor sleeps + E->>R: alarm fires, actor wakes + Note over R: triggerReminder(id) runs + R-->>C: reminderTriggered event + Note over R: recurring jobs re-arm here with schedule.after +``` + +## Security Checklist + +The example is intentionally open: any client can connect to the shared `["main"]` key and schedule or cancel anything. Treat all of the following as required extensions for production: + +- **Validate schedule inputs**: Clamp `delayMs` and `timestamp` from clients. Reject negative delays, timestamps in the past, and absurdly far-future deadlines, and bound message or payload sizes. +- **Never schedule client-chosen actions**: Expose specific actions like `scheduleReminder` that internally arm a fixed callback. Do not pass a client-supplied action name or unchecked args into `c.schedule`. +- **Authenticate and scope keys**: Add connection [authentication](/docs/actors/authentication) and use per-user actor keys instead of one global key, so users cannot read or cancel each other's schedules. +- **Prune completed entries**: The example's `reminders` array grows without bound. Remove or archive completed entries so state stays small. +- **Use stable IDs**: Generate entry IDs with `crypto.randomUUID()` rather than timestamp-plus-random strings. + +_Source doc path: /cookbook/cron-jobs_ diff --git a/.agents/skills/rivetkit/reference/cookbook/live-cursors.md b/.agents/skills/rivetkit/reference/cookbook/live-cursors.md new file mode 100644 index 0000000..71c94ab --- /dev/null +++ b/.agents/skills/rivetkit/reference/cookbook/live-cursors.md @@ -0,0 +1,152 @@ +# Live Cursors and Presence + +> Source: `src/content/cookbook/live-cursors.mdx` +> Canonical URL: https://rivet.dev/cookbook/live-cursors +> Description: Live cursors and multiplayer presence with Rivet Actors: per-connection cursor state, realtime updates over events or raw WebSockets, and throttling. + +--- +Patterns for building live cursors, multiplayer presence, and realtime cursor sharing with RivetKit. One room actor fans cursor positions out to every connected client, keyed per room with [actor keys](/docs/actors/keys). + +## Starter Code + +Start with one of the two working variants on GitHub. Both implement the same collaborative cursor canvas with persistent text labels; they differ only in transport. + +| Variant | Starter Code | Transport | Presence Storage | +| --- | --- | --- | --- | +| `cursors` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/cursors) | Typed [actions](/docs/actors/actions) and [events](/docs/actors/events) over the RivetKit connection | `connState` per connection | +| `cursors-raw-websocket` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/cursors-raw-websocket) | Raw [`onWebSocket` handler](/docs/actors/websocket-handler) with a custom JSON message protocol | Socket map in `createVars` | + +Use `cursors` by default: typed actions, typed events, and automatic connection tracking cover most apps with less code. Use `cursors-raw-websocket` when you need full control of the wire format, for example a custom JSON or binary protocol, or clients that do not use the RivetKit client library. + +## Connection State vs Persistent State + +Presence is ephemeral by definition. A cursor position is only meaningful while its connection is alive, so it belongs in per-connection storage, not in persistent actor state. Persistent state is reserved for data that must survive disconnects and actor restarts. + +| Data | Where It Lives | Why | +| --- | --- | --- | +| Cursor position | `connState` (`cursors`) or the `createVars` socket map (`cursors-raw-websocket`) | Scoped to one connection and discarded with it. Stale presence cannot accumulate in storage. | +| Text labels (`textLabels`) | Persistent actor `state` in both variants | Canvas content must survive disconnects and actor restarts. | + +In the `cursors` variant, `updateCursor` writes `c.conn.state.cursor` and `getRoomState` rebuilds the presence snapshot by iterating `c.conns.values()`, so the cursor map is always derived from live connections rather than stored. See [Connections](/docs/actors/connections) for `connState` and [State](/docs/actors/state) for persistence semantics. + +## Presence Lifecycle + +- **Join**: The `cursors-raw-websocket` variant pushes an `init` message with the current `{ cursors, textLabels }` snapshot as soon as a socket connects. The `cursors` variant has no explicit join broadcast; the client calls the `getRoomState` action once after connecting to seed its local maps, and peers first see a new user on that user's first `cursorMoved` broadcast. +- **Move**: Every `updateCursor` call writes the connection's presence entry, then broadcasts `cursorMoved` to all connections, including the sender. +- **Leave**: The `cursors` variant handles leave in `onDisconnect`, broadcasting `cursorRemoved` with the connection's last cursor. The raw variant does the same from the socket `close` listener, then deletes the session from the `vars.websockets` map. Clients delete that user from their local cursor map, so stale cursors disappear the moment a tab closes. + +See [Lifecycle](/docs/actors/lifecycle) for `onDisconnect` and `createVars`. + +## Update Throttling + +Neither example throttles. Both frontends send a cursor update on every raw `mousemove` event with no debounce or interval cap. That is fine for a demo, but a fast mouse on a high-refresh display can emit hundreds of events per second per user. The patterns below are recommended production hardening on top of the starter code, not something the examples implement. + +| Layer | Pattern | Guidance | +| --- | --- | --- | +| Client (smoothness) | Throttle to 20-30Hz | Sample the latest pointer position every 33-50ms and send only that. Drop intermediate moves, but always flush the final position so cursors settle at the true location. Interpolate between received positions on the rendering side. | +| Server (enforcement) | Per-connection rate limit | Track the last accepted update timestamp per connection and drop or coalesce updates arriving faster than your cap. Client throttles are cooperative; the actor is the enforcement boundary. | + +## Actors + +- **Key**: `cursorRoom[roomId]` (the frontend defaults `roomId` to `"general"`) +- **Responsibility**: Holds per-connection cursor presence in `connState`, persists shared text labels in actor state, and broadcasts cursor and text updates to all connections. +- **Actions** + - `updateCursor` + - `updateText` + - `removeText` + - `getRoomState` +- **Events** + - `cursorMoved` + - `cursorRemoved` + - `textUpdated` + - `textRemoved` +- **Queues** + - None +- **State** + - JSON + - `textLabels` (persistent) + - `connState.cursor` per connection (ephemeral) + +- **Key**: `cursorRoom[roomId]` (resolved via `client.cursorRoom.getOrCreate(roomId)`) +- **Responsibility**: Exposes a raw WebSocket endpoint, tracks live sockets and their cursors in a `createVars` map keyed by a `sessionId` query parameter, persists text labels, and manually fans JSON frames out to every socket. +- **Actions** + - `getOrCreate` (stub returning `{ status: "ok" }`; the frontend resolves the actor ID with the client handle's `getOrCreate(roomId).resolve()`, which creates the actor without dispatching this action) + - `getRoomState` +- **Queues** + - None +- **State** + - JSON + - `textLabels` (persistent) + - `vars.websockets` map of `sessionId` to socket and cursor (in-memory, lost on restart) + +The raw variant defines no RivetKit events. Its message names are `type` fields on raw JSON frames: + +| Direction | Message `type` | Payload | +| --- | --- | --- | +| Client to server | `updateCursor` | `{ userId, x, y }` | +| Client to server | `updateText` | `{ id, userId, text, x, y }` | +| Client to server | `removeText` | `{ id }` | +| Server to client | `init` | `{ cursors, textLabels }` snapshot on connect | +| Server to client | `cursorMoved`, `textUpdated`, `textRemoved`, `cursorRemoved` | The corresponding cursor, label, or ID payload | + +## Lifecycle + +### cursors (Actions + Events) + +```mermaid +sequenceDiagram + participant A as Client A + participant R as cursorRoom + participant B as Other Clients + + A->>R: connect via useActor (cursorRoom[roomId]) + A->>R: getRoomState() + R-->>A: {cursors, textLabels} + loop every mouse move + A->>R: updateCursor(userId, x, y) + Note over R: write c.conn.state.cursor + R-->>B: cursorMoved (broadcast) + end + A->>R: updateText(id, userId, text, x, y) + Note over R: upsert persistent state.textLabels + R-->>B: textUpdated (broadcast) + Note over A: tab closes + Note over R: onDisconnect reads conn.state.cursor + R-->>B: cursorRemoved (broadcast) +``` + +### cursors-raw-websocket + +```mermaid +sequenceDiagram + participant A as Client A + participant R as cursorRoom + participant B as Other Clients + + A->>R: getOrCreate(roomId).resolve() + R-->>A: actorId + A->>R: open WebSocket /gateway/{actorId}/websocket?sessionId=... + Note over R: close 1008 if sessionId is missing + Note over R: store socket in vars.websockets + R-->>A: init {cursors, textLabels} + loop every mouse move + A->>R: {type: "updateCursor"} frame + Note over R: update session cursor in vars + R-->>B: cursorMoved frame + end + Note over A: socket closes + R-->>B: cursorRemoved frame + Note over R: delete session from vars.websockets +``` + +## Security Checklist + +Both examples ship without authentication so the presence pattern stays readable. Everything below is recommended hardening for production, not behavior the examples implement. + +- **Identity**: Bind presence identity to the connection (`c.conn.id` in the actions variant, a server-generated session ID in the raw variant). Never trust a client-supplied `userId`; in the examples it is a random client-generated string, so any client can impersonate or remove any cursor. +- **Authorization**: Authorize label mutations by owner. In the examples, `updateText` accepts arbitrary `id` and `userId` arguments and `removeText` accepts an arbitrary `id`, so any client can edit or delete any label. +- **Input validation**: Clamp `x` and `y` to canvas bounds, cap text label length, and cap the total `textLabels` count so persistent state cannot grow unbounded. +- **Rate limiting**: Enforce a per-connection cap on `updateCursor` (for example 30Hz) and on label writes, as described in [Update Throttling](#update-throttling). +- **Protocol strictness (raw variant)**: Validate message shape before use and close the socket on malformed JSON instead of logging and continuing. Reject duplicate `sessionId` values rather than silently overwriting another session's socket entry. + +_Source doc path: /cookbook/live-cursors_ diff --git a/.agents/skills/rivetkit/reference/cookbook/multiplayer-game.md b/.agents/skills/rivetkit/reference/cookbook/multiplayer-game.md new file mode 100644 index 0000000..425b113 --- /dev/null +++ b/.agents/skills/rivetkit/reference/cookbook/multiplayer-game.md @@ -0,0 +1,713 @@ +# Multiplayer Game + +> Source: `src/content/cookbook/multiplayer-game.mdx` +> Canonical URL: https://rivet.dev/cookbook/multiplayer-game +> Description: Pragmatic patterns for building multiplayer games: matchmaking, tick loops, realtime state, interest management, and validation. + +--- +Patterns for building multiplayer games with RivetKit, intended as a practical checklist you can adapt per genre. + +## Starter Code + +Start with one of the working examples on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/) and adapt it to your game. Do not start from scratch for matchmaking and lifecycle flows. + +| Game Classification | Starter Code | Common Examples | +| --- | --- | --- | +| Battle Royale | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/battle-royale/) | Fortnite, Apex Legends, PUBG, Warzone | +| Arena | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/arena/) | Call of Duty TDM/FFA, Halo Slayer, Counter-Strike casual, VALORANT unrated, Overwatch Quick Play, Rocket League | +| IO Style | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/io-style/) | Agar.io, Slither.io, surviv.io | +| Open World | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/open-world/) | Minecraft survival servers, Rust-like worlds, MMO zone/chunk worlds | +| Party | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/party/) | Fall Guys private lobbies, custom game rooms, social party sessions | +| Physics 2D | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-2d/) | Top-down physics brawlers, 2D arena games, platform fighters | +| Physics 3D | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-3d/) | Physics sandbox sessions, 3D arena games, movement playgrounds | +| Ranked | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/ranked/) | Chess ladders, competitive card games, duel arena ranked queues | +| Turn-Based | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/turn-based/) | Chess correspondence, Words With Friends, async board games | +| Idle | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/idle/) | Cookie Clicker, Idle Miner Tycoon, Adventure Capitalist | + +## Server Simulation + +### Game Loop And Tick Rates + +| Pattern | Use When | Implementation Guidance | +| --- | --- | --- | +| Fixed realtime loop | Battle Royale, Arena, IO Style, Open World, Ranked | Run in `run` with `sleep(tickMs)` and exit on `c.aborted`. | +| Action-driven updates | Party, Turn-Based | Mutate and broadcast only on actions/events rather than scheduled ticks. | +| Coarse offline progression | Any mode with idle progression | Use `c.schedule.after(...)` with coarse windows (for example 5 to 15 minutes) and apply catch-up from elapsed wall clock time. | + +### Physics + +Start with custom kinematic logic for simple games. Switch to a full physics engine when you need joints, stacked bodies, high collision density, or complex shapes (rotated polygons, capsules, convex hulls, triangle meshes). + +Pick one engine per simulation. Keep frontend-only libs out of backend simulation paths and treat server state as authoritative. + +| Dimension | Primary Engine | Fallback Engines | Example Code | +| --- | --- | --- | --- | +| 2D | `@dimforge/rapier2d` | `planck-js`, `matter-js` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-2d/) | +| 3D | `@dimforge/rapier3d` | `cannon-es`, `ammo.js` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-3d/) | + +### Spatial Indexing + +For non-physics spatial queries, use a dedicated index instead of naive `O(n^2)` checks: + +| Index Type | Recommendation | +| --- | --- | +| AABB index | For AOI, visibility, and non-collider entities, use `rbush` for dynamic sets or `flatbush` for static-ish sets. | +| Point index | For nearest-neighbor or within-radius queries, use `d3-quadtree`. | + +## Networking & State Sync + +### Netcode + +| Model | When To Use | Implementation | +| --- | --- | --- | +| Hybrid (client movement, server combat) | Shooters, action sports, ranked duels | Client owns movement and sends capped-rate position updates. Server validates for anti-cheat. Combat (projectiles, hits, damage) is fully server-authoritative. | +| Server-authoritative with interpolation | IO Style, persistent worlds | Client sends input commands. Server simulates on fixed ticks and publishes authoritative snapshots. Client interpolates between snapshots. | +| Server-authoritative (basic logic) | Turn-based, event-driven | Server validates and applies discrete actions (turns, phase transitions, votes). Client displays confirmed state. | + +### Realtime Data Model + +- **Snapshots and diffs**: Publish state as events. Send a full snapshot on join/resync, then per-tick diffs for regular updates. +- **Batch per tick**: Keep events small and typed. Batch high-frequency updates per tick. +- **Avoid UI framework state for game updates**: Use `requestAnimationFrame` or a Canvas/Three.js loop for simulation, not React state. Reserve UI framework state for menus, HUD, and forms. +- **Broadcast vs per-connection**: Use `c.broadcast(...)` for shared updates and `conn.send(...)` for private/per-player data. + +### Shared Simulation Logic + +Shared simulation logic runs on both the client and the server. For example, an `applyInput(state, input, dt)` function that integrates velocity and clamps to world bounds can run on the client for prediction and on the server for validation. + +- **Hybrid modes**: Client runs shared movement as primary authority, server runs it for anti-cheat validation. +- **Server-authoritative modes**: Client uses shared logic for interpolation and prediction only. +- **Keep it pure**: Movement integration, input transforms, collision helpers, and constants only. +- **Put shared code in `src/shared/`**: Keep deterministic helpers in `src/shared/sim/*` with no side effects. + +### Interest Management + +Control what each client receives to reduce bandwidth and prevent information leaks. + +#### Per-Player Replication Filters + +- **Filter by relevance**: Send each client only state relevant to that player (proximity, line-of-sight, team, or game phase). +- **Shooters and action games**: Limit replication by proximity and optional field-of-view checks. +- **Server-side only**: Clients should never receive data they should not see. + +#### Sharded Worlds + +- **Partition large worlds**: Use chunk actors keyed by `worldId:chunkX:chunkY`. +- **Subscribe to nearby chunks**: Clients connect only to nearby partitions (for example a 3x3 chunk window). +- **Use sparingly**: Only when the world is large and state-heavy (sandbox builders, MMOs), not as a default for small matches. + +## Backend Infrastructure + +### Persistence + +- **In-memory state**: Best for realtime game state that changes every tick (player positions, inputs, match phase, scores). +- **SQLite (`rivetkit/db`)**: Better for large or table-like state that needs queries, indexes, or long-term persistence (tiles, inventory, matchmaking pools). Serialize DB work through a queue since multiple actions can hit the same actor concurrently. + +### Matchmaking Patterns + +Common building blocks used across the architecture patterns below. + +#### Actor Topology + +| Primitive | Use When | Typical Ownership | +| --- | --- | --- | +| `matchmaker["main"]` + `match[matchId]` | Session-based multiplayer (battle royale, arena, ranked, party, turn-based) | Matchmaker owns discovery/assignment. Match owns lifecycle and gameplay state. | +| `chunk[worldId,chunkX,chunkY]` | Large continuous worlds that need sharding | Each chunk owns local players, chunk state, and local simulation. | +| `world[playerId]` | Per-player progression loops (idle/solo world state) | Per-player resources, buildings, timers, and progression. | +| `player[username]` | Canonical profile/rating reused across matches | Durable player stats (for example rating and win/loss). | +| `leaderboard["main"]` | Shared rankings across many matches/players | Global ordered score rows and top lists. | + +#### Queueing Strategy + +- Multiple players can hit the matchmaker at the same time, so actions like find/create, queue/unqueue, and close need to be serialized through actor queues to avoid races. +- Match-local actions (gameplay, scoring) do not need queueing unless they write back to the matchmaker. + +## Security And Anti-Cheat + +Start with this baseline, then harden further for competitive or high-risk environments. + +### Baseline Checklist + +- **Identity**: Use `c.conn.id` as the authoritative transport identity. Treat `playerId`/`username` in params as untrusted input and bind through server-issued assignment/join tickets. +- **Authorization**: Validate the caller is allowed to mutate the target entity (room membership, turn ownership, host-only actions). +- **Input validation**: Clamp sizes/lengths, validate enums, and validate usernames (length, allowed chars, avoid unbounded Unicode). +- **Rate limiting**: Per-connection rate limits for spammy actions (chat, join/leave, fire, movement updates). +- **State integrity**: Server recomputes derived state (scores, win conditions, placements). Never allow client-authoritative changes to inventory/currency/leaderboard totals. + +### Movement Validation + +For any mode with client-authoritative movement (hybrid flows), clients may send position/rotation updates for smoothness, but the server must: + +- Enforce max delta per update (speed cap) based on elapsed time. +- Reject or clamp teleports. +- Enforce world bounds (and basic collision if applicable). +- Rate limit update frequency (for example 20Hz max). + +## Architecture Patterns + +Each game type below starts with a quick summary table, then details actors and lifecycle. + +### Battle Royale + +| Topic | Summary | +| --- | --- | +| Matchmaking | Immediate routing to the fullest non-started lobby (oldest tie-break); players wait in lobby until capacity, then the match starts. | +| Netcode | Hybrid. Client owns movement, camera, and local prediction. Server owns zone state, projectiles, hit resolution, eliminations, loot, and final placement. | +| Tick Rate | 10 ticks/sec (`100ms`) with a fixed loop for zone progression and lifecycle checks. | +| Physics | Client owns movement with server anti-cheat validation; projectiles, hits, and damage are server-authoritative. Use `@dimforge/rapier3d` for 3D or `@dimforge/rapier2d` for top-down 2D. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Finds or creates lobbies, tracks pending reservations, and maintains occupancy. +- **Actions** + - `findMatch` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **Queues** + - `findMatch` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **State** + - SQLite + - `matches` + - `pending_players` + - `player_count` includes connected and pending players + +- **Key**: `match[matchId]` +- **Responsibility**: Runs lobby/live/finished phases, owns player state, zone progression, and eliminations. +- **Actions** + - `connect` + - Movement and combat actions +- **Queues** + - None +- **State** + - JSON + - `phase` + - `players` + - `zone` + - `eliminations` + - `snapshot data` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant M as match + + C->>MM: findMatch() + alt no open lobby + MM->>M: create(matchId) + end + MM-->>C: {matchId, playerId} + C->>M: connect(playerId) + M->>MM: pendingPlayerConnected(matchId, playerId) + MM-->>M: accepted + Note over M: lobby countdown -> live + M-->>C: snapshot + shoot events + M->>MM: closeMatch(matchId) +``` + +### Arena + +| Topic | Summary | +| --- | --- | +| Matchmaking | Mode-based fixed-capacity queues (`duo`, `squad`, `ffa`) that build only full matches and pre-assign teams (except FFA). | +| Netcode | Hybrid. Client owns movement plus prediction and smoothing. Server owns team or FFA assignment, projectiles, hit resolution, phase transitions, and scoring. | +| Tick Rate | 20 ticks/sec (`50ms`) with a tighter loop for live team and FFA snapshots. | +| Physics | Medium to high intensity; client movement with server validation and server-authoritative combat/entities. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Runs mode queues, builds full matches, assigns teams, and publishes assignments. +- **Actions** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **Queues** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **State** + - SQLite + - `player_pool` + - `matches` + - `assignments` keyed by connection and player + +- **Key**: `match[matchId]` +- **Responsibility**: Runs match phases and in-match player/team state for score and win conditions. +- **Actions** + - `connect` + - Gameplay actions +- **Queues** + - None +- **State** + - JSON + - `phase` + - `players` + - `team assignments` + - `score and win state` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant M as match + + C->>MM: queueForMatch(mode) + Note over MM: enqueue in player_pool + Note over MM: fill when capacity reached + MM->>M: create(matchId, assignments) + Note over MM: persist assignments + MM-->>C: assignmentReady + C->>M: connect(playerId) + Note over M: waiting -> live when all players connect + M->>MM: matchCompleted(matchId) +``` + +### IO Style + +| Topic | Summary | +| --- | --- | +| Matchmaking | Open-lobby routing to the fullest room below capacity; room counts are heartbeated and new lobbies are auto-created when needed. | +| Netcode | Server-authoritative with interpolation. Client sends input intents and interpolates. Server owns movement, bounds, room membership, and canonical snapshots. | +| Tick Rate | 10 ticks/sec (`100ms`) with lightweight periodic room snapshots. | +| Physics | Low to medium intensity; server-authoritative kinematic movement, escalating to a physics engine only when collisions get complex. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Routes players into the fullest open lobby and tracks reservations and occupancy. +- **Actions** + - `findLobby` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **Queues** + - `findLobby` + - `pendingPlayerConnected` + - `updateMatch` + - `closeMatch` +- **State** + - SQLite + - `matches` + - `pending_players` + - Occupancy includes pending reservations + +- **Key**: `match[matchId]` +- **Responsibility**: Runs per-match movement simulation and broadcasts snapshots. +- **Actions** + - `connect` + - `setInput` +- **Queues** + - None +- **State** + - JSON + - `players` + - `inputs` + - `movement state` + - `snapshot cache` + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant M as match + + C->>MM: findLobby() + alt no open lobby + MM->>M: create(matchId) + end + MM-->>C: {matchId, playerId} + C->>M: connect(playerId) + M->>MM: pendingPlayerConnected(matchId, playerId) + MM-->>M: accepted + Note over M: fixed tick simulation + M-->>C: snapshot events + M->>MM: closeMatch(matchId) +``` + +### Open World + +| Topic | Summary | +| --- | --- | +| Matchmaking | Client-driven chunk routing from world coordinates, with nearby chunk windows preloaded via adjacent chunk connections. | +| Netcode | Hybrid for sandbox (client movement with validation) or server-authoritative for MMO-like flows. Server owns chunk routing, persistence, and canonical world state. | +| Tick Rate | 10 ticks/sec per chunk actor (`100ms`), so load scales with active chunks. | +| Physics | Medium to high at scale; chunk-local simulation can be server-authoritative (MMO-like) or client movement with server validation (sandbox-like). | + +**Actors** + +- **Key**: `chunk[worldId,chunkX,chunkY]` +- **Responsibility**: Owns chunk-local players, blocks, movement tick, and chunk membership. +- **Actions** + - `connect` + - `enterChunk` + - `addPlayer` + - `setInput` + - `leaveChunk` + - `removePlayer` +- **Queues** + - None +- **State** + - JSON + - `connections` + - `players` + - `blocks` scoped to one chunk key + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant CH as chunk + + Note over C: resolve chunk keys from world position + loop each visible chunk + C->>CH: connect(worldId, chunkX, chunkY, playerId) + Note over CH: store connection metadata + end + C->>CH: enterChunk/addPlayer + loop movement updates + C->>CH: setInput(...) + CH-->>C: snapshot + end + C->>CH: leaveChunk/removePlayer or disconnect + Note over CH: remove membership and metadata +``` + +### Party + +| Topic | Summary | +| --- | --- | +| Matchmaking | Host-created private party flow using party codes and explicit joins. | +| Netcode | Server-authoritative (basic logic). Server owns membership, host permissions, and phase transitions. | +| Tick Rate | No continuous tick; updates are event-driven (`join`, `start`, `finish`). | +| Physics | Low intensity for lobby-first flows; usually no dedicated physics or indexing unless you add realtime mini-games. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Handles party create/join flow, validates join tickets, and tracks party size. +- **Actions** + - `createParty` + - `joinParty` + - `verifyJoin` + - `updatePartySize` + - `closeParty` +- **Queues** + - `createParty` + - `joinParty` + - `verifyJoin` + - `updatePartySize` + - `closeParty` +- **State** + - SQLite + - `parties` + - `join_tickets` for party lookup and join validation + +- **Key**: `match[matchId]` +- **Responsibility**: Owns party members, host role, ready flags, and phase transitions. +- **Actions** + - `connect` + - `startGame` + - `finishGame` +- **Queues** + - None +- **State** + - JSON + - `members` + - `host` + - `ready state` + - `phase` + - `party events` + +**Lifecycle** + +### Host Flow + +```mermaid +sequenceDiagram + participant H as Host Client + participant MM as matchmaker + participant M as match + + H->>MM: createParty() + MM-->>H: {matchId, partyCode, playerId, joinToken} + H->>M: connect(playerId, joinToken) + M->>MM: verifyJoin(...) + MM-->>M: allowed + M->>MM: updatePartySize(playerCount) + H->>M: startGame() / finishGame() + M->>MM: closeParty(matchId) +``` + +### Joiner Flow + +```mermaid +sequenceDiagram + participant J as Joiner Client + participant MM as matchmaker + participant M as match + + J->>MM: joinParty(partyCode) + MM-->>J: {matchId, playerId, joinToken} + J->>M: connect(playerId, joinToken) + M->>MM: verifyJoin(...) + MM-->>M: allowed / denied + M->>MM: updatePartySize(playerCount) +``` + +### Ranked + +| Topic | Summary | +| --- | --- | +| Matchmaking | ELO-based queue pairing with a widening search window as wait time increases. | +| Netcode | Hybrid. Client owns movement with local prediction and interpolation. Server owns projectiles, hit resolution, match results, and rating updates. | +| Tick Rate | 20 ticks/sec (`50ms`) with fixed live ticks for deterministic pacing and broadcast cadence. | +| Physics | Medium to high intensity; client movement with server validation and server-authoritative combat/hit resolution. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Runs rating-based queueing, pairing, assignment persistence, and completion fanout. +- **Actions** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **Queues** + - `queueForMatch` + - `unqueueForMatch` + - `matchCompleted` +- **State** + - SQLite + - `player_pool` + - `matches` + - `assignments` with rating window and connection scoping + +- **Key**: `match[matchId]` +- **Responsibility**: Runs ranked match phase, score, and winner reporting. +- **Actions** + - `connect` + - Gameplay actions +- **Queues** + - None +- **State** + - JSON + - `phase` + - `players` + - `score` + - `winner` + - `completion payload` + +- **Key**: `player[username]` +- **Responsibility**: Stores canonical player MMR and win/loss profile. +- **Actions** + - `initialize` + - `getRating` + - `applyMatchResult` +- **Queues** + - None +- **State** + - JSON + - `rating` + - `wins` + - `losses` + - `match counters` + +- **Key**: `leaderboard["main"]` +- **Responsibility**: Stores and serves top-ranked players. +- **Actions** + - `updatePlayer` +- **Queues** + - None +- **State** + - SQLite + - Leaderboard score rows + - Top-list ordering + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant MM as matchmaker + participant P as player + participant M as match + participant LB as leaderboard + + C->>MM: queueForMatch(username) + MM->>P: initialize/getRating + P-->>MM: rating + Note over MM: store queue row + retry pairing + MM->>M: create(matchId, assigned players) + MM-->>C: assignmentReady + C->>M: connect(username) + M->>MM: matchCompleted(...) + MM->>P: applyMatchResult(...) + MM->>LB: updatePlayer(...) + Note over MM: remove matches + assignments rows +``` + +### Turn-Based + +| Topic | Summary | +| --- | --- | +| Matchmaking | Async private-invite and public-queue pairing in the same pattern. | +| Netcode | Server-authoritative (basic logic). Client can draft moves before submit. Server owns turn ownership, committed move log, turn order, and completion state. | +| Tick Rate | No continuous tick; move submission and turn transitions drive updates. | +| Physics | Very low intensity; no realtime physics loop, just discrete rules validation. Indexing is optional and mostly for board or query convenience at scale. | + +**Actors** + +- **Key**: `matchmaker["main"]` +- **Responsibility**: Handles private invite and public queue pairing for async matches. +- **Actions** + - `createGame` + - `joinByCode` + - `queueForMatch` + - `unqueueForMatch` + - `closeMatch` +- **Queues** + - `createGame` + - `joinByCode` + - `queueForMatch` + - `unqueueForMatch` + - `closeMatch` +- **State** + - SQLite + - `matches` + - `player_pool` + - `assignments` for invite and queue mapping + +- **Key**: `match[matchId]` +- **Responsibility**: Owns board state, turn order, move validation, and final result. +- **Actions** + - `connect` + - `makeMove` +- **Queues** + - None +- **State** + - JSON + - `board` + - `turns` + - `players` + - `connection presence` + - `result` + +**Lifecycle** + +### Public Queue + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant MM as matchmaker + participant M as match + + A->>MM: queueForMatch() + B->>MM: queueForMatch() + Note over MM: pair first two queued players + MM->>M: create(matchId) + seed X/O players + MM-->>A: assignment/match info + MM-->>B: assignment/match info + A->>M: connect(playerId) + B->>M: connect(playerId) + A->>M: makeMove() + B->>M: makeMove() + opt all players disconnected for timeout + Note over M: destroy after idle timeout + end + M->>MM: closeMatch(matchId) +``` + +### Private Invite + +```mermaid +sequenceDiagram + participant A as Client A + participant B as Client B + participant MM as matchmaker + participant M as match + + A->>MM: createGame() + MM-->>A: {matchId, playerId, inviteCode} + B->>MM: joinByCode(inviteCode) + MM->>M: create(matchId) + seed X/O players + MM-->>A: assignment/match info + MM-->>B: assignment/match info + A->>M: connect(playerId) + B->>M: connect(playerId) + A->>M: makeMove() + B->>M: makeMove() + M->>MM: closeMatch(matchId) +``` + +### Idle + +| Topic | Summary | +| --- | --- | +| Matchmaking | No matchmaker; each player uses a direct per-player actor and a shared leaderboard actor. | +| Netcode | Server-authoritative (basic logic). Client owns UI and build intent. Server owns resources, production rates, building validation, and leaderboard totals. | +| Tick Rate | No continuous tick; use `c.schedule.after(...)` for coarse intervals and compute offline catch-up from elapsed wall time. | +| Physics | None for standard idle loops; transitions are discrete (`build`, `collect`, `upgrade`) and do not need spatial indexing. | + +**Actors** + +- **Key**: `world[playerId]` +- **Responsibility**: Owns one player's progression, buildings, production scheduling, and state updates. +- **Actions** + - `initialize` + - `build` + - `collectProduction` +- **Queues** + - None +- **State** + - JSON + - Per-player buildings + - `resources` + - `timers` + - `progression state` + +- **Key**: `leaderboard["main"]` +- **Responsibility**: Stores global scores and serves leaderboard updates. +- **Actions** + - `updateScore` +- **Queues** + - `updateScore` +- **State** + - SQLite + - `scores` table keyed by player + - Current leaderboard totals + +**Lifecycle** + +```mermaid +sequenceDiagram + participant C as Client + participant W as world + participant LB as leaderboard + + C->>W: getOrCreate(playerId) + initialize() + Note over W: seed state + schedule collection + W-->>C: stateUpdate + loop gameplay loop + C->>W: build() / collectProduction() + W->>LB: updateScore(...) + Note over LB: upsert scores + LB-->>C: leaderboardUpdate + W-->>C: stateUpdate + end +``` + +_Source doc path: /cookbook/multiplayer-game_ diff --git a/.agents/skills/rivetkit/reference/cookbook/per-tenant-database.md b/.agents/skills/rivetkit/reference/cookbook/per-tenant-database.md new file mode 100644 index 0000000..e3c5616 --- /dev/null +++ b/.agents/skills/rivetkit/reference/cookbook/per-tenant-database.md @@ -0,0 +1,119 @@ +# Database per Tenant + +> Source: `src/content/cookbook/per-tenant-database.mdx` +> Canonical URL: https://rivet.dev/cookbook/per-tenant-database +> Description: Multi-tenant data isolation with one Rivet Actor per tenant: the actor key is the tenant id, so each tenant gets its own isolated dataset and migrations. + +--- +Patterns for database-per-tenant architectures with RivetKit. Instead of one shared database with a `tenant_id` column on every table, each tenant gets its own Rivet Actor, and that actor owns the tenant's entire dataset. + +## Starter Code + +Start with the working example on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/per-tenant-database) and adapt it. The example stores each tenant's dataset in JSON actor state and serves a React dashboard with live event updates. + +| Topic | Summary | +| --- | --- | +| Isolation | One `companyDatabase` actor per tenant, keyed by company name. Switching tenants swaps the entire dataset. | +| State | JSON actor state holding `employees` and `projects` arrays plus timestamps. No SQLite, no queues, no scheduling. | +| Realtime | Every write action mutates state, then broadcasts a typed event (`employeeAdded`, `projectAdded`) to all connected clients of that tenant. | +| Auth | None. The sign-in screen is cosmetic. Production guidance is in the [security checklist](#security-checklist). | + +## The Isolation Model + +The actor key is the tenant id. The client connects with `useActor({ name: "companyDatabase", key: [companyName] })` and the actor reads `c.key[0]` in `createState` to seed that tenant's dataset. This gives you: + +- **One actor per tenant**: `companyDatabase[tenantId]` addresses exactly one actor instance. Two tenants can never share an actor. +- **One dataset per tenant**: All reads and writes go through that actor's [state](/docs/actors/state), so there is no shared table with a `tenant_id` column to filter incorrectly. Cross-tenant leaks require constructing the wrong key, not forgetting a `WHERE` clause. +- **No key injection**: Keys are arrays, not interpolated strings. `key: [tenantId]` cannot be escaped the way `"tenant:" + tenantId` string concatenation can. See [Keys](/docs/actors/keys). + +The example's test ([tests/per-tenant-database.test.ts](https://github.com/rivet-dev/rivet/tree/main/examples/per-tenant-database/tests/per-tenant-database.test.ts)) proves the isolation: data written to `companyDatabase["Alpha Co"]` never appears in `companyDatabase["Beta Co"]`. + +## Choosing a State Backend + +The example uses plain JSON actor state. The same key-equals-tenant model works with any actor state backend. + +| Backend | Use When | Docs | Working Code | +| --- | --- | --- | --- | +| JSON actor state | Small datasets, simple reads, whole dataset fits comfortably in memory. What the example uses. | [State](/docs/actors/state) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/per-tenant-database) | +| Actor SQLite (`rivetkit/db`) | Tables, indexes, SQL queries, larger-than-memory data, per-tenant relational schema. | [SQLite](/docs/actors/sqlite) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/kitchen-sink/src/actors/state/sqlite-raw.ts) | +| SQLite + Drizzle | Typed schema, query builder, and generated migration files on top of actor SQLite. | [SQLite + Drizzle](/docs/actors/sqlite-drizzle) | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/kitchen-sink/src/actors/state/sqlite-drizzle/) | + +With either SQLite option, every tenant gets its own embedded SQLite database, since the database is scoped to the actor and the actor is scoped to the tenant. + +## Migrations + +The per-tenant example has no migrations because JSON state has no schema. When you adopt SQLite, migrations run per tenant database: + +- **Raw SQL**: `db({ onMigrate })` runs your migration SQL inside a SQLite savepoint before the actor serves traffic. If `onMigrate` throws, all migration SQL rolls back atomically and the actor does not start. See [SQLite](/docs/actors/sqlite). +- **Drizzle**: `drizzle-kit` generates migration files from your typed schema, and `db({ schema, migrations })` applies them when the actor wakes. See [SQLite + Drizzle](/docs/actors/sqlite-drizzle). + +Because each tenant has its own database, migrations roll out per actor as each tenant's actor wakes, rather than as one large migration against a shared database. + +## Tenant Id Must Come From Auth + +The example's sign-in is cosmetic: the client picks any company string and that string becomes the actor key, so any visitor can read and write any tenant's data. Do not ship this. As a required production extension (not implemented by the example): + +- Derive the tenant id from a verified credential, such as a JWT claim, never from user input. +- Validate the credential against `c.key` in `onBeforeConnect` (pass/fail) or `createConnState` (store the verified user on connection state). See [Authentication](/docs/actors/authentication) and [Connections](/docs/actors/connections). +- Add per-action permission checks on top of connection-level auth. See [Access Control](/docs/actors/access-control). + +## Actors + +- **Key**: `companyDatabase[companyName]` (single-element array key; `c.key[0]` is the company name) +- **Responsibility**: One actor per tenant. Holds that company's employees and projects in persistent state, serves reads and writes via actions, and broadcasts mutations to connected clients. +- **Actions** + - `addEmployee` + - `listEmployees` + - `addProject` + - `listProjects` + - `getStats` +- **Queues** + - None +- **Events** + - `employeeAdded` + - `projectAdded` +- **State** + - JSON + - `company_name` + - `employees` + - `projects` + - `created_at` + - `updated_at` + +Every write action follows the same mutate-then-broadcast shape: push the record into `c.state`, bump `updated_at`, broadcast the typed event, return the record. See [Actions](/docs/actors/actions) and [Events](/docs/actors/events). + +## Lifecycle + +```mermaid +sequenceDiagram + participant A as Tenant A client + participant DA as companyDatabase A + participant B as Tenant B client + participant DB as companyDatabase B + + Note over A: authenticate and derive tenant id + A->>DA: connect with key [tenantA] + Note over DA: createState seeds company_name, employees, projects + A->>DA: listEmployees() + listProjects() + getStats() + A->>DA: addEmployee(name, role) + DA-->>A: employeeAdded event + B->>DB: connect with key [tenantB] + Note over DB: separate actor, separate dataset + B->>DB: listEmployees() + DB-->>B: tenant B data only +``` + +In the example, the "authenticate" step is a free-text company picker. The rest of the flow matches the diagram: `createState` seeds the dataset on first creation, the dashboard loads with `listEmployees`, `listProjects`, and `getStats`, and every connected client of the same tenant receives `employeeAdded` and `projectAdded` events. + +## Security Checklist + +The example ships with none of these. Apply all of them before production. + +- **Tenant identity**: Derive the tenant id from a verified JWT claim, never from a client-supplied string. +- **Connection validation**: In `onBeforeConnect` or `createConnState`, verify the credential's tenant claim matches `c.key` and reject mismatches. +- **Per-action authorization**: Check the caller's role before mutating actions (`addEmployee`, `addProject`), not just at connect time. See [Access Control](/docs/actors/access-control). +- **Input validation**: Clamp name and role lengths and validate enums. The example only trims input and substitutes fallback defaults. +- **Key construction**: Always pass the tenant id as an array element (`key: [tenantId]`). Never interpolate tenant ids into key strings, and never build keys from one tenant's input to address another tenant's actor. +- **Growth limits**: As a recommended extension, cap or paginate the `employees` and `projects` arrays. The example lets them grow unboundedly in JSON state; move to [SQLite](/docs/actors/sqlite) when the dataset outgrows memory. + +_Source doc path: /cookbook/per-tenant-database_ diff --git a/.agents/skills/rivetkit/reference/cookbook/vpc-air-gapped.md b/.agents/skills/rivetkit/reference/cookbook/vpc-air-gapped.md new file mode 100644 index 0000000..f7d87a3 --- /dev/null +++ b/.agents/skills/rivetkit/reference/cookbook/vpc-air-gapped.md @@ -0,0 +1,136 @@ +# Deploying Rivet in a VPC or Air-Gapped Network + +> Source: `src/content/cookbook/vpc-air-gapped.mdx` +> Canonical URL: https://rivet.dev/cookbook/vpc-air-gapped +> Description: Run Rivet entirely inside your own perimeter: single-binary or Docker Compose install, file system storage with no database infrastructure, and no outbound telemetry by default. + +--- +Patterns for running self-hosted Rivet inside a private network: a VPC without internet egress, an on-premises rack, or a fully air-gapped environment. The engine is one service, the recommended single-node storage backend is the local file system, and the engine makes no outbound connections by default. Self-hosting is the only Rivet deployment model that supports air-gapped networks; see the [Self-Hosting Overview](/docs/self-hosting) for the full comparison with BYOC. + +## What Runs Inside the Perimeter + +A self-hosted deployment has three components, all of which live inside your network: + +| Component | Role | Inside the perimeter | +| --- | --- | --- | +| Your backend | Your application server, including the runner that executes actor code | Yes | +| Rivet Engine | Orchestration service that manages actor lifecycle, routes messages, and serves the dashboard and APIs | Yes | +| Storage | Persistence for actor state. Local file system for single-node, PostgreSQL or FoundationDB for multi-node | Yes | + +There is no license server, no Rivet Cloud account, and no callback to `rivet.dev`. Clients inside the perimeter reach actors through the engine's gateway over your private network. See [Architecture](/docs/self-hosting#architecture). + +## Single-Binary Install + +The engine compiles to a single `rivet-engine` binary. Build it from source outside the perimeter, then copy the binary across the boundary: + +```bash +git clone https://github.com/rivet-dev/rivet.git +cd rivet +cargo build --release -p rivet-engine +# Copy target/release/rivet-engine into the perimeter. +``` + +Prebuilt binaries are coming soon; see [Installing Rivet Engine](/docs/self-hosting/install) for current options. + +Run it with the file system backend, which stores everything on local disk and is the production-ready choice for single-node deployments. The [File System](/docs/self-hosting/filesystem) docs list air-gapped environments as a primary use case because it needs no database infrastructure: + +```bash +RIVET__database__file_system__path="/var/lib/rivet/data" ./rivet-engine +``` + +Configuration can also come from files. The engine discovers config at `/etc/rivet/config.json` on Linux (JSON, JSON5, JSONC, YAML, and YML are all supported), and `--config` overrides the path. Environment variables use the `RIVET__` prefix with `__` as the separator. See [Configuration](/docs/self-hosting/configuration). + +The engine serves its own dashboard on port `6420`, so inspection and namespace management work with nothing but a browser inside the perimeter. + +## Docker Compose Deployment + +For Docker hosts without registry access, move the engine image across the boundary the standard way: + +```bash +# Outside the perimeter. +docker pull rivetdev/engine:latest +docker save rivetdev/engine:latest -o rivet-engine.tar +# Inside the perimeter. +docker load -i rivet-engine.tar +``` + +Then run the engine and your app together in one Compose file: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - rivet-data:/data + environment: + RIVET__FILE_SYSTEM__PATH: "/data" + restart: unless-stopped + + my-app: + build: . + environment: + RIVET_ENDPOINT: "http://default:admin@rivet-engine:6420" + depends_on: + - rivet-engine + restart: unless-stopped + +volumes: + rivet-data: +``` + +`RIVET_ENDPOINT` uses the format `http://namespace:token@host:port` and tells your app to connect to the engine as a runner instead of running standalone. After both services start, register your runner with the engine through the dashboard or its API. The full walkthrough, including PostgreSQL setup for multi-node deployments, is in [Docker Compose](/docs/self-hosting/docker-compose). + +## No Outbound Telemetry + +The engine exports traces and metrics only when you opt in with OpenTelemetry. Export is disabled unless `RIVET_OTEL_ENABLED=1` is set, and the export target defaults to a local collector at `http://localhost:4317`. With no configuration, nothing crosses the perimeter. + +When you want observability, keep it inside the network: + +- Set `RIVET_OTEL_ENABLED=1` and point `RIVET_OTEL_GRPC_ENDPOINT` at a collector you run inside the perimeter. +- Adjust `RIVET_OTEL_SAMPLER_RATIO` to control trace sampling. +- Use the engine's health endpoint for liveness and readiness probes. + +See the [Production Checklist](/docs/self-hosting/production-checklist) for monitoring guidance. + +## Embedding Rivet in a Customer's Environment + +If you ship software that runs inside your customers' VPCs, the same setup turns Rivet into an internal component of your product rather than a service your customers must reach over the internet: + +- **Ship the engine next to your app.** Add `rivetdev/engine` to the Compose file or chart you already deliver. Your app finds it over the private network via `RIVET_ENDPOINT`, so one artifact deploys the whole stack. +- **One namespace per install.** The endpoint URL carries the namespace and token (`http://namespace:token@host:port`), so a single image works across customer deployments. See [Endpoints](/docs/general/endpoints). +- **Generate a strong admin token per install.** Replace the default token and keep it server-side. Never include the admin token in `RIVET_PUBLIC_ENDPOINT` or anywhere clients can read it. +- **Public endpoint only when needed.** `RIVET_PUBLIC_ENDPOINT` with a public (`pk_`) token is only required when browser clients connect to actors in [serverless runtime mode](/docs/general/runtime-modes). Backend-only deployments can skip it entirely. +- **TLS at the customer's edge.** Terminate TLS with the customer's reverse proxy or load balancer in front of the engine. + +## Scaling Past One Node + +| Backend | Use when | Status | +| --- | --- | --- | +| [File System](/docs/self-hosting/filesystem) (RocksDB-based) | Single-node deployments, including air-gapped installs | Production-ready, single node only | +| [PostgreSQL](/docs/self-hosting/postgres) | Multi-node deployments | Recommended for multi-node today, but experimental | +| FoundationDB | Largest production deployments | [Enterprise](/sales) | + +For multi-node deployments, run two or more engine nodes behind a load balancer and add NATS for pub/sub, which replaces the default PostgreSQL `LISTEN`/`NOTIFY` path at high throughput. Neither is needed for a single-node file system install. See the [Production Checklist](/docs/self-hosting/production-checklist). + +## Perimeter Checklist + +- **Admin token**: Generate a strong, random token for engine authentication and verify it is not exposed to clients. +- **TLS termination**: Encrypt connections to the engine via a reverse proxy or load balancer. +- **No public exposure**: Keep port `6420` reachable only from inside the perimeter unless clients outside it genuinely need access. +- **Health checks**: Configure liveness and readiness probes against the engine health endpoint. +- **Telemetry**: Leave OpenTelemetry export off, or point it at a collector inside the network. +- **Backups**: With the file system backend, back up the data directory. With PostgreSQL, configure automated backups and failover. + +## Full Configuration + +- [Self-Hosting Overview](/docs/self-hosting) for architecture and the self-host vs BYOC comparison +- [Installing Rivet Engine](/docs/self-hosting/install) for Docker, binary, and source installs +- [Docker Container](/docs/self-hosting/docker-container) and [Docker Compose](/docs/self-hosting/docker-compose) for container deployments +- [Kubernetes](/docs/self-hosting/kubernetes) for cluster deployments +- [Configuration](/docs/self-hosting/configuration) for every option and the full JSON schema +- [Endpoints](/docs/general/endpoints) for connecting your backend and clients +- [Production Checklist](/docs/self-hosting/production-checklist) before going live + +_Source doc path: /cookbook/vpc-air-gapped_ diff --git a/.agents/skills/rivetkit/reference/deploy/aws-ecs.md b/.agents/skills/rivetkit/reference/deploy/aws-ecs.md new file mode 100644 index 0000000..ab381ce --- /dev/null +++ b/.agents/skills/rivetkit/reference/deploy/aws-ecs.md @@ -0,0 +1,13 @@ +# Deploying to AWS ECS + +> Source: `src/content/docs/deploy/aws-ecs.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/aws-ecs +> Description: Run your backend on Amazon ECS with Fargate. + +--- +See the [AWS ECS template](https://github.com/rivet-dev/template-aws-ecs) for deployment instructions: + +- [Deploy with Terraform](https://github.com/rivet-dev/template-aws-ecs#option-a-deploy-with-terraform) +- [Deploy with AWS CLI](https://github.com/rivet-dev/template-aws-ecs#option-b-deploy-with-aws-cli) + +_Source doc path: /docs/deploy/aws-ecs_ diff --git a/.agents/skills/rivetkit/reference/deploy/aws-lambda.md b/.agents/skills/rivetkit/reference/deploy/aws-lambda.md new file mode 100644 index 0000000..f1327cc --- /dev/null +++ b/.agents/skills/rivetkit/reference/deploy/aws-lambda.md @@ -0,0 +1,10 @@ +# Deploy To Amazon Web Services Lambda + +> Source: `src/content/docs/deploy/aws-lambda.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/aws-lambda +> Description: _AWS Lambda is coming soon_ + +--- + + +_Source doc path: /docs/deploy/aws-lambda_ diff --git a/.agents/skills/rivetkit/reference/deploy/cloudflare.md b/.agents/skills/rivetkit/reference/deploy/cloudflare.md new file mode 100644 index 0000000..970078e --- /dev/null +++ b/.agents/skills/rivetkit/reference/deploy/cloudflare.md @@ -0,0 +1,53 @@ +# Deploying to Cloudflare Workers + +> Source: `src/content/docs/deploy/cloudflare.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/cloudflare +> Description: Deploy an existing Rivet project to Cloudflare Workers. + +--- +This guide covers deploying an existing Rivet project to Cloudflare Workers. + +## Prerequisites + +- [Cloudflare account](https://dash.cloudflare.com/) +- [`wrangler`](https://developers.cloudflare.com/workers/wrangler/) configured for your account +- A Rivet namespace from the [Rivet Dashboard](https://dashboard.rivet.dev/) or a self-hosted Rivet Engine + +## Steps + +### Set up your project + +Follow the [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) to set up your project locally. + +### Configure Wrangler + +Set your Rivet connection values as Worker variables. Find `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` in the [Rivet Dashboard](https://dashboard.rivet.dev/) under **Settings → Namespace → Advanced → Backend Configuration** and copy them in. + +```toml wrangler.toml +name = "rivetkit-cloudflare" +main = "src/index.ts" +compatibility_date = "2025-04-01" +compatibility_flags = ["nodejs_compat"] + +[vars] +RIVET_ENDPOINT = "https://your-namespace:sk_...@api.rivet.dev" +RIVET_PUBLIC_ENDPOINT = "https://your-namespace@api.rivet.dev" +``` + +### Deploy + +```sh +npx wrangler deploy +``` + +### Register the Serverless Runner URL + +After deploy, set the Worker URL with the `/api/rivet` path as the serverless runner URL in Rivet. + +## Related + +- [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) +- [Deploying to Supabase Functions](/docs/deploy/supabase) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/deploy/cloudflare_ diff --git a/.agents/skills/rivetkit/reference/deploy/container-runner.md b/.agents/skills/rivetkit/reference/deploy/container-runner.md new file mode 100644 index 0000000..7bb0c5a --- /dev/null +++ b/.agents/skills/rivetkit/reference/deploy/container-runner.md @@ -0,0 +1,95 @@ +# Container Runner + +> Source: `src/content/docs/deploy/container-runner.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/container-runner +> Description: Run any containerized server as a Rivet Actor. + +--- +The container runner (`rivet-container-runner`) is an adapter for running arbitrary containers as Rivet Actors. Use it for non-RivetKit workloads such as Unity or Godot dedicated game servers and batch jobs like FFmpeg transcoding. + +## Steps + +### Prerequisites + +- A containerized server (a Unity or Godot dedicated server, a plain Node process, or any HTTP/WebSocket server) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) +- Docker running locally + +### Install in Your Container + +Download the static binary from Rivet's release artifacts in your Dockerfile and set it as the entrypoint, passing your server's launch command after `--`: + +```dockerfile @nocheck +FROM debian:bookworm-slim +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl && rm -rf /var/lib/apt/lists/* + +# Install the Rivet container runner. +RUN curl -fsSL https://releases.rivet.dev/rivet/latest/container-runner/rivet-container-runner-x86_64-unknown-linux-musl \ + -o /usr/local/bin/rivet-container-runner \ + && chmod +x /usr/local/bin/rivet-container-runner + +# Your server binary and assets. +COPY build/ /game/ +WORKDIR /game + +ENTRYPOINT ["rivet-container-runner", "--", "./GameServer", "-batchmode", "-nographics", "-logFile", "-"] +``` + +Artifacts are published for `x86_64-unknown-linux-musl` and `aarch64-unknown-linux-musl`. The binaries are fully static, so they run in any Linux base image, including `scratch`. Pin a version by replacing `latest` with a release version, for example `https://releases.rivet.dev/rivet/2.3.3/container-runner/rivet-container-runner-x86_64-unknown-linux-musl`. + +### Deploy + +Deploy the image to [Rivet Compute](/docs/deploy/rivet-compute) with the CLI. For game servers, configure the pool with one actor per instance: + +```bash +npx @rivetkit/cli deploy \ + --token "$RIVET_CLOUD_TOKEN" \ + --instance-request-concurrency 1 \ + --dockerfile Dockerfile +``` + +### Create Actors and Connect Clients + +Create actors against the pool's runner (`default`) and connect clients through the gateway URL shown in the dashboard. WebSocket clients connect at the bare gateway URL with the `rivet` WebSocket subprotocol. + +## How It Works + +1. The engine cold-starts your container and calls `POST /api/rivet/start` on the port it injects as `RIVET_PORT`. +2. The runner spawns your server as a child process with `PORT` set to the child port, waits for the port to open, and reports the actor as running. +3. Gateway traffic for the actor arrives over Rivet's tunnel and is proxied to `127.0.0.1:`. WebSocket clients connect at the bare gateway URL with the `rivet` WebSocket subprotocol. Raw HTTP reaches the child under the `/request/*` prefix on the actor surface (the prefix is stripped before proxying); other paths are reserved for the runtime's own endpoints. +4. Child stdout and stderr are re-emitted with an `[actorId=... key=...]` prefix so actor logs are attributed in the dashboard. +5. When an actor stops, the runner sends its child `SIGTERM`, escalates to `SIGKILL` after a grace period, and exits the process once no actors remain. + +## Configuration + +All flags can also be set through environment variables: + +| Flag | Environment variable | Default | Description | +| --- | --- | --- | --- | +| `--port` | `RIVET_PORT` / `PORT` | `8080` | Serverless front-door HTTP port. Rivet Compute injects `RIVET_PORT` automatically. | +| `--child-port` | `CHILD_PORT` | `7770` | First local child port; each actor's child gets the next free port at or above this, exported to the child as `PORT`. | +| `--actor-name` | `RIVET_ACTOR_NAME` | `game` | Actor name this runner serves. | +| `--runner-version` | `RIVET_RUNNER_VERSION` | `1` | Version reported to the engine, used to drain old runners on deploy. | +| `--base-path` | `RIVET_SERVERLESS_BASE_PATH` | `/api/rivet` | Base path the engine calls for serverless start. | +| `--stop-grace-secs` | `RIVET_STOP_GRACE_SECS` | `25` | `SIGTERM` to `SIGKILL` grace period when stopping the child. Capped to a few seconds when the platform itself is reclaiming the instance, so shutdown fits inside the platform's own kill window. | +| `--readiness-timeout-secs` | `RIVET_READINESS_TIMEOUT_SECS` | `30` | How long to wait for the child's port to open before failing the start. | + +### Per-Actor Input + +The actor's `input` payload can override the launch spec per actor. All fields are optional and fall back to the entrypoint command. RivetKit clients pass this object directly; when creating actors through the raw engine API, encode it as CBOR before base64-encoding the `input` field: + +```json +{ + "command": ["./GameServer", "-batchmode"], + "args": ["-extra-flag"], + "env": { "MATCH_MODE": "ranked" } +} +``` + +`command` replaces the entrypoint command template, `args` are appended to it, and `env` adds environment variables for the child. + +## Source and Examples + +The runner and a full end-to-end example, including a Unity FishNet demo project and a local test harness, live in the Rivet repository under [`container-runner/`](https://github.com/rivet-dev/rivet/tree/main/container-runner). + +_Source doc path: /docs/deploy/container-runner_ diff --git a/.agents/skills/rivetkit/reference/deploy/freestyle.md b/.agents/skills/rivetkit/reference/deploy/freestyle.md new file mode 100644 index 0000000..eb6ed57 --- /dev/null +++ b/.agents/skills/rivetkit/reference/deploy/freestyle.md @@ -0,0 +1,136 @@ +# Deploying to Freestyle + +> Source: `src/content/docs/deploy/freestyle.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/freestyle +> Description: Deploy RivetKit app to Freestyle.sh, a cloud platform for running AI-generated code with built-in security and scalability. + +--- +Freestyle provides built-in security for running untrusted AI-generated code, making it ideal for AI agent applications. Using Rivet, it is easy to deploy your vibe-coded or user-provided RivetKit backends straight to Freestyle. + +- [Freestyle + Rivet](https://github.com/rivet-dev/rivet/tree/main/examples/freestyle) — Complete example of deploying RivetKit app to Freestyle.sh. + +## Setup + +### Install packages + +Install RivetKit and Hono and create your registry: + +```bash +npm install rivetkit hono +``` + +### Configure serverless driver + +Update your server code to run the registry serverless with Deno. + +```typescript index.ts @hide +import { actor, setup } from "rivetkit"; + +export const counter = actor({ + state: { count: 0 }, + actions: { + increment: (c, x: number) => { + c.state.count += x; + return c.state.count; + }, + }, +}); + +export const registry = setup({ + use: { counter }, +}); +registry.start(); +``` + +```typescript server.ts @nocheck +import { registry } from "./index"; + +// Freestyle uses Deno under the hood for web deployments +// @ts-ignore Deno is a Freestyle runtime global +Deno.serve((request: Request) => registry.handler(request)); +``` + +The `Deno.serve` API is provided by Freestyle's runtime environment. The `@ts-ignore` comment suppresses TypeScript errors for this platform-specific API. + +### Deploy to Freestyle + +Deploy your application to Freestyle with the correct configuration. Create a deployment script or add this to your existing deployment process: + +```typescript @nocheck +const FREESTYLE_DOMAIN = "my-domain.style.dev"; // Change to your desired Freestyle domain + +declare const freestyle: any; +declare const buildDir: string; + +const res = await freestyle.deployWeb(buildDir, { + envVars: { + FREESTYLE_ENDPOINT: `https://${FREESTYLE_DOMAIN}`, + RIVET_RUNNER_KIND: "serverless", + // For self-hosted instances: + // RIVET_ENDPOINT: "http://127.0.0.1:6420", + RIVET_ENDPOINT: "api.rivet.dev", + }, + timeout: 60 * 5, // Increases max request lifetime on the runner + entrypoint: "server.ts", // File which starts serverless runner + domains: [FREESTYLE_DOMAIN], + build: false, +}); +``` + +Details on `buildDir` and other settings are available on [Freestyle docs](https://docs.freestyle.sh/web/web). + +Run this deployment script to push your application to Freestyle. + +**Deployment Configuration:** + +- `timeout: 60 * 5` - Set timeout to 5 minutes for actor operations - it's important to keep this high +- `entrypoint: "server.ts"` - Entry point file with your serverless setup +- `domains` - Your Freestyle domain(s) +- `build: false` - Disable build if you're pre-building your assets + +### Configure runner + +Update the runner configuration on the Rivet side to connect with your Freestyle deployment. Create a configuration script and run it after your Freestyle deployment is live: + +```typescript @nocheck +import { RivetClient } from "@rivetkit/engine-api-full"; + +const rivet = new RivetClient({ + environment: "https://api.rivet.dev", + token: process.env.RIVET_API_TOKEN, +}); + +const FREESTYLE_DOMAIN = "my-domain.style.dev"; // Change to your desired Freestyle domain +const RIVET_NAMESPACE = "my-rivet-namespace"; // Change to your Rivet namespace + +await rivet.runnerConfigsUpsert("freestyle-runner", { + namespace: RIVET_NAMESPACE, + datacenters: { + default: { + serverless: { + url: `https://${FREESTYLE_DOMAIN}/start`, + runnersMargin: 1, + minRunners: 1, + maxRunners: 1, + slotsPerRunner: 1, + // Must be shorter than Freestyle request `timeout` config + requestLifespan: 60 * 5 - 5, + }, + }, + }, +}); +``` + +Execute this configuration script to register your Freestyle deployment with Rivet. + +**Runner Configuration:** + +- `url` - Freestyle deployment URL with `/start` endpoint +- `runnersMargin` - Buffer of runners to maintain +- `minRunners/maxRunners` - Scaling limits +- `slotsPerRunner` - Concurrent actors per runner +- `requestLifespan` - Request timeout (slightly less than Freestyle timeout) + +Once executed, Rivet will be connected to your Freestyle serverless instance. + +_Source doc path: /docs/deploy/freestyle_ diff --git a/.agents/skills/rivetkit/reference/deploy/gcp-cloud-run.md b/.agents/skills/rivetkit/reference/deploy/gcp-cloud-run.md new file mode 100644 index 0000000..f140950 --- /dev/null +++ b/.agents/skills/rivetkit/reference/deploy/gcp-cloud-run.md @@ -0,0 +1,74 @@ +# Deploying to Google Cloud Run + +> Source: `src/content/docs/deploy/gcp-cloud-run.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/gcp-cloud-run +> Description: Deploy your RivetKit app to Google Cloud Run. + +--- +## Steps + +### Prerequisites + +- Google Cloud project with Cloud Run and Artifact Registry enabled +- `gcloud` CLI authenticated (`gcloud auth login`) and project set (`gcloud config set project YOUR_PROJECT`) +- Artifact Registry repository or Container Registry enabled +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Package Your App + +Create a `Dockerfile` in your project root: + +```dockerfile +FROM node:20-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev +COPY . . +ENV PORT=8080 +CMD ["node", "server.js"] +``` + +### Build and Push the Image + +Use Cloud Build to build and push the image. Replace the region and repository with your own. + +```bash +gcloud builds submit --tag us-central1-docker.pkg.dev/YOUR_PROJECT/rivetkit-app/rivetkit-app:latest +``` + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select Google Cloud Run as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables to use when deploying. + +### Deploy to Cloud Run + +Deploy the service to Cloud Run, passing the Rivet environment variables. Adjust the region and image as needed. + +```bash +gcloud run deploy rivetkit-app \ + --image us-central1-docker.pkg.dev/YOUR_PROJECT/rivetkit-app/rivetkit-app:latest \ + --region us-central1 \ + --allow-unauthenticated \ + --min-instances 1 \ + --set-env-vars RIVET_ENDPOINT=,RIVET_PUBLIC_ENDPOINT= +``` + +### Connect to Rivet + +1. After deployment, note the service URL (e.g. `https://rivetkit-app-xxxxx-uc.a.run.app`) +2. On the Rivet dashboard, paste your URL with the `/api/rivet` path into the connect form (e.g. `https://rivetkit-app-xxxxx-uc.a.run.app/api/rivet`) +3. Click "Done" + +### Verify + +Confirm the service is running: + +```bash +gcloud run services describe rivetkit-app --region us-central1 --format 'value(status.conditions[?type="Ready"].status)' +``` + +Your app should appear as connected on the Rivet dashboard once the service reports ready. + +_Source doc path: /docs/deploy/gcp-cloud-run_ diff --git a/.agents/skills/rivetkit/reference/deploy/hetzner.md b/.agents/skills/rivetkit/reference/deploy/hetzner.md new file mode 100644 index 0000000..5b61024 --- /dev/null +++ b/.agents/skills/rivetkit/reference/deploy/hetzner.md @@ -0,0 +1,10 @@ +# Deploying to Hetzner + +> Source: `src/content/docs/deploy/hetzner.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/hetzner +> Description: Please see the VM & Bare Metal guide. + +--- + + +_Source doc path: /docs/deploy/hetzner_ diff --git a/.agents/skills/rivetkit/reference/deploy/kubernetes.md b/.agents/skills/rivetkit/reference/deploy/kubernetes.md new file mode 100644 index 0000000..43496a9 --- /dev/null +++ b/.agents/skills/rivetkit/reference/deploy/kubernetes.md @@ -0,0 +1,121 @@ +# Deploying to Kubernetes + +> Source: `src/content/docs/deploy/kubernetes.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/kubernetes +> Description: Deploy your RivetKit app to any Kubernetes cluster. + +--- +## Steps + +### Prerequisites + +- A Kubernetes cluster with `kubectl` access (EKS, GKE, k3s, etc.) +- Container registry credentials (Docker Hub, GHCR, GCR, etc.) +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Package Your App + +Create a `Dockerfile` in your project root: + +```dockerfile +FROM node:20-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev +COPY . . +ENV PORT=8080 +CMD ["node", "server.js"] +``` + +### Build and Push the Image + +```bash +docker build -t registry.example.com/your-team/rivetkit-app:latest . +docker push registry.example.com/your-team/rivetkit-app:latest +``` + +Replace `registry.example.com/your-team` with your registry path. Auth with `docker login` first if needed. + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select Kubernetes as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables. + +Create a `rivetkit-secrets.yaml` for your environment variables: + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: rivetkit-secrets +type: Opaque +stringData: + RIVET_ENDPOINT: + RIVET_PUBLIC_ENDPOINT: +``` + +### Deploy to Kubernetes + +Create a `deployment.yaml`: + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: rivetkit-app +spec: + replicas: 1 + selector: + matchLabels: + app: rivetkit-app + template: + metadata: + labels: + app: rivetkit-app + spec: + # Allow enough time for actors to gracefully stop on SIGTERM. + # The runner waits up to 30m for actors to finish. + # Add buffer for runner shutdown overhead after actors stop. + # See: /docs/actors/versions#graceful-shutdown-sigterm + terminationGracePeriodSeconds: 2100 + containers: + - name: rivetkit-app + image: registry.example.com/your-team/rivetkit-app:latest + envFrom: + - secretRef: + name: rivetkit-secrets +``` + +Apply both manifests: + +```bash +kubectl apply -f rivetkit-secrets.yaml +kubectl apply -f deployment.yaml +``` + +### Connect to Rivet + +1. Add a `Service` and Ingress to expose your app externally (e.g. `my-app.example.com`) +2. On the Rivet dashboard, paste your domain with the `/api/rivet` path into the connect form (e.g. `https://my-app.example.com/api/rivet`) +3. Click "Done" + +Rivet envoys connect to your app over long-lived WebSockets, and your app's clients (browsers, SDKs) do the same. Default Ingress and cloud load balancer idle timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +Raise the idle / read / send timeout on every Ingress and load balancer in front of your app to at least 1 hour (`3600` seconds). Examples: + +- **NGINX Ingress**: `nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"` and `nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"` +- **AWS Load Balancer Controller (ALB)**: `alb.ingress.kubernetes.io/load-balancer-attributes: idle_timeout.timeout_seconds=3600` +- **GCE Ingress (GKE)**: set `timeoutSec: 3600` on the `BackendConfig` referenced by the Service. + +### Verify + +Check that the pod is running: + +```bash +kubectl get pods -l app=rivetkit-app +``` + +Your app should appear as connected on the Rivet dashboard once the pod is ready. + +_Source doc path: /docs/deploy/kubernetes_ diff --git a/.agents/skills/rivetkit/reference/deploy/railway.md b/.agents/skills/rivetkit/reference/deploy/railway.md new file mode 100644 index 0000000..640ac37 --- /dev/null +++ b/.agents/skills/rivetkit/reference/deploy/railway.md @@ -0,0 +1,45 @@ +# Deploying to Railway + +> Source: `src/content/docs/deploy/railway.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/railway +> Description: Deploy your RivetKit app to Railway. + +--- +## Steps + +### Prerequisites + +- [Railway account](https://railway.app) +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Deploy to Railway + +1. Connect your GitHub account to Railway +2. Select your repository containing your RivetKit app +3. Railway will automatically detect and deploy your app + +See [Railway's deployment docs](https://docs.railway.com/quick-start) for more details. + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select Railway as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables to add to your Railway service. + +See [Railway's environment variables docs](https://docs.railway.com/guides/variables#service-variables) for more details. + +### Connect to Rivet + +1. In your Railway project, go to **Settings > Networking** +2. Click **Create Custom Domain** then **Create Domain** to generate a Railway domain (e.g. `my-app.railway.app`) +3. On the Rivet dashboard, paste your domain with the `/api/rivet` path into the connect form (e.g. `https://my-app.railway.app/api/rivet`) +4. Click "Done" + +Rivet envoys connect to your app over long-lived WebSockets, and your app's clients (browsers, SDKs) do the same. Railway's HTTP proxy supports WebSockets, but if you front your app with your own reverse proxy (NGINX, Caddy, etc.) inside the Railway service, raise its idle / read timeout to at least 1 hour (`3600` seconds). Default proxy timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +### Configure Sleeping & Multi-Region (Optional) + +- [Enable App Sleeping](https://docs.railway.com/reference/app-sleeping) to reduce costs when idle +- [Configure Multi-Region](https://docs.railway.com/reference/deployment-regions) to deploy closer to your users + +_Source doc path: /docs/deploy/railway_ diff --git a/.agents/skills/rivetkit/reference/deploy/rivet-compute.md b/.agents/skills/rivetkit/reference/deploy/rivet-compute.md new file mode 100644 index 0000000..69507aa --- /dev/null +++ b/.agents/skills/rivetkit/reference/deploy/rivet-compute.md @@ -0,0 +1,144 @@ +# Deploying to Rivet Compute + +> Source: `src/content/docs/deploy/rivet-compute.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/rivet-compute +> Description: Run your backend on Rivet Compute. + +--- +Using an AI coding agent? Open **Connect** on the [Rivet dashboard](https://dashboard.rivet.dev), select **Rivet Cloud**, and paste the one-shot prompt into your agent and have it connect with Rivet Compute for you. + +## Steps + +### Prerequisites + +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- A [Rivet Cloud](https://dashboard.rivet.dev) account and project +- Docker running locally + +### Create a Dockerfile + +Add a `Dockerfile` to your project root that builds and runs your RivetKit server: + +```dockerfile @nocheck +FROM node:24-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev +COPY . . +CMD ["node", "src/server.js"] +``` + +### Get Your Cloud Token + +1. Open the [Rivet dashboard](https://dashboard.rivet.dev) and navigate to your project +2. Click **Connect** and select **Rivet Cloud** +3. Copy the **`RIVET_CLOUD_TOKEN`** value shown + +### Deploy + +Run the deploy command from your project root. The token is saved to `~/.rivet/credentials`, so later deploys can omit it. + +```bash +npx @rivetkit/cli deploy --token cloud_api_xxxxx +``` + +The CLI resolves your project from the token, builds and pushes your Docker image to Rivet's built-in registry, upserts the managed pool, and prints the deployment URL on stdout when the pool is ready. + +### Optionally Add CI + +After local deploys work, install the GitHub Actions workflow that deploys on every push and pull request: + +```bash +npx @rivetkit/cli setup-ci +``` + +This writes `.github/workflows/rivet-deploy.yml`. Add your token as a repository secret to enable it: + +```bash +gh secret set RIVET_CLOUD_TOKEN +``` + +The workflow creates production and pull-request namespaces, posts preview links, and cleans up PR namespaces when pull requests close. See the [CLI reference](/docs/cli) for all commands. + +### Monitor Deployment + +The dashboard shows live status as Rivet Compute provisions your backend: + +| Status | Description | +| --- | --- | +| Initializing | Starting the runtime environment | +| Deploying | Pulling and launching your container | +| Binding | Connecting the runner to the network | +| Ready | Deployment complete | + +Once the status reaches **Ready**, your backend is live and actors are available for connections. + +If you are an agent monitoring the deployment via API rather than the dashboard, poll the managed-pool endpoint on the Cloud API. + +The `RIVET_CLOUD_TOKEN` secret is a `cloud_api_*` management token scoped to the Cloud API at `cloud-api.rivet.dev`. Use it for `Authorization: Bearer ...` against the Cloud API. Do not confuse it with a `pk_*` publishable key, which is scoped to the Rivet Engine API at `api.rivet.dev` and will 401 against this endpoint. + +Substitute `$CLOUD_API_URL` (typically `https://cloud-api.rivet.dev`), `$PROJECT`, `$ORG`, `$CLOUD_NAMESPACE`, and `$CLOUD_TOKEN`. + +Poll every 5 seconds until `status` is `ready`. Stop and investigate if `status` is `error`. + +```bash +curl -s "$CLOUD_API_URL/projects/$PROJECT/namespaces/$CLOUD_NAMESPACE/managed-pools/default?org=$ORG" -H "Authorization: Bearer $CLOUD_TOKEN" +``` + +## Checking Logs + +Use the CLI to read your deployment's logs. By default `rivet logs` prints the last 100 lines from the `production` namespace, oldest to newest, then exits. + +```bash +npx @rivetkit/cli logs +``` + +The CLI resolves your token the same way `deploy` does (the `--token` flag, then the `RIVET_CLOUD_TOKEN` environment variable, then `~/.rivet/credentials`). + +### Follow logs live + +Pass `--follow` (`-f`) to stream new logs as they arrive instead of fetching history: + +```bash +npx @rivetkit/cli logs --follow +``` + +Each formatted line is printed as ` [] `: + +``` +2026-06-16T18:26:51.160Z [INFO] eu-central-1 server listening on port 3000 +2026-06-17T11:24:20.425Z [ERROR] us-east-1 failed to connect to upstream +``` + +A few examples: + +```bash +# Last 200 lines from a specific namespace +npx @rivetkit/cli logs --namespace production -n 200 + +# Live tail, only lines containing "error" +npx @rivetkit/cli logs --follow --contains error + +# JSON output piped to jq +npx @rivetkit/cli logs -n 50 --json | jq . +``` + +## Troubleshooting + +If the status stays in **Initializing** for more than a few minutes, verify that: + +- The `RIVET_CLOUD_TOKEN` secret is correctly set in your GitHub repository +- The GitHub Actions workflow completed without errors — check the run logs + +If the status shows **Error**, check that your container starts successfully and does not exit immediately (you can check this with container logs). Common causes: + +- The server file is not calling `registry.start()` +- A runtime crash on startup — test the image locally with `docker run` +- The server is not listening on the `RIVET_PORT` environment variable (RivetKit reads `RIVET_PORT`, defaulting to `3000`) + +## Pricing + +You are billed for the compute resources your deployment uses while it is running. + +_Source doc path: /docs/deploy/rivet-compute_ diff --git a/.agents/skills/rivetkit/reference/deploy/supabase.md b/.agents/skills/rivetkit/reference/deploy/supabase.md new file mode 100644 index 0000000..fa98436 --- /dev/null +++ b/.agents/skills/rivetkit/reference/deploy/supabase.md @@ -0,0 +1,50 @@ +# Deploying to Supabase Functions + +> Source: `src/content/docs/deploy/supabase.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/supabase +> Description: Deploy an existing Rivet project to Supabase Edge Functions. + +--- +This guide covers deploying an existing Rivet project to Supabase Edge Functions. + +## Prerequisites + +- [Supabase project](https://supabase.com/) +- [Supabase CLI](https://supabase.com/docs/guides/cli) configured for your project +- A Rivet namespace from the [Rivet Dashboard](https://dashboard.rivet.dev/) or a self-hosted Rivet Engine + +## Steps + +### Set up your project + +Follow the [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) to set up your project locally. + +### Set Secrets + +Set your Rivet connection values as Supabase secrets. Find `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` in the [Rivet Dashboard](https://dashboard.rivet.dev/) under **Settings → Namespace → Advanced → Backend Configuration** and copy them in. + +```sh +npx supabase secrets set \ + RIVET_ENDPOINT=https://your-namespace:sk_...@api.rivet.dev \ + RIVET_PUBLIC_ENDPOINT=https://your-namespace@api.rivet.dev +``` + +### Deploy + +Make sure the function has the `deno.json` import map from the [quickstart](/docs/actors/quickstart/supabase) that points `rivetkit` at `@rivetkit/supabase`. It keeps the deploy to the WebAssembly runtime; without it the deploy pulls Rivet's native engine and fails with a `413` (request too large). + +```sh +npx supabase functions deploy rivet +``` + +### Register the Serverless Runner URL + +After deploy, set the function URL with the `/api/rivet` path as the serverless runner URL in Rivet. For a function named `rivet`, this is usually `https://your-project.functions.supabase.co/functions/v1/rivet/api/rivet`. + +## Related + +- [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) +- [Deploying to Cloudflare Workers](/docs/deploy/cloudflare) +- [SQLite](/docs/actors/sqlite) + +_Source doc path: /docs/deploy/supabase_ diff --git a/.agents/skills/rivetkit/reference/deploy/vercel.md b/.agents/skills/rivetkit/reference/deploy/vercel.md new file mode 100644 index 0000000..e8b5ba3 --- /dev/null +++ b/.agents/skills/rivetkit/reference/deploy/vercel.md @@ -0,0 +1,138 @@ +# Deploying to Vercel + +> Source: `src/content/docs/deploy/vercel.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/vercel +> Description: Deploy your Next.js Rivet app to Vercel. + +--- +This guide assumes a Next.js app. + +## Prerequisites + +- [Vercel account](https://vercel.com/) +- A Next.js Rivet app +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +## Steps + +### Set up your project + +Follow the [Next.js Quickstart](/docs/actors/quickstart/next-js) to set up your project. + +### Verify Your Project Structure + +Your Next.js project should have the following structure: + +- `src/app/api/rivet/[...all]/route.ts`: RivetKit route handler +- `src/rivet/registry.ts`: Actor definitions and registry + +The route handler sets `maxDuration` to extend the serverless function timeout so long-lived actor requests are not cut short: + +```ts src/app/api/rivet/[...all]/route.ts @nocheck +import { toNextHandler } from "@rivetkit/next-js"; +import { registry } from "@/rivet/registry"; + +export const maxDuration = 300; + +export const { GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS } = toNextHandler(registry); +``` + +### Set Environment Variables + +Set `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` in your Vercel project settings using the URL auth format: + +``` +RIVET_ENDPOINT=https://my-namespace:sk_****@api.rivet.dev +RIVET_PUBLIC_ENDPOINT=https://my-namespace:pk_****@api.rivet.dev +``` + +`RIVET_ENDPOINT` uses the secret token for server-side access. `RIVET_PUBLIC_ENDPOINT` uses the publishable token and tells the metadata endpoint what connection info to provide to clients. + +### Deploy to Vercel + +1. Connect your GitHub repository to Vercel +2. Vercel will deploy your app + +### Configure Preview Deployments (Recommended) + +Add a GitHub action to automatically create isolated Rivet namespaces for each PR: + +1. Add these secrets to your GitHub repository: + - `RIVET_CLOUD_TOKEN`: Get from [Rivet Dashboard](https://dashboard.rivet.dev) → Settings → Advanced → Cloud API Tokens + - `VERCEL_TOKEN`: Get from [Vercel Account Settings](https://vercel.com/account/tokens) + +2. Create `.github/workflows/rivet-preview.yml`: + +```yaml +name: Rivet Preview + +on: + pull_request: + types: [opened, synchronize, reopened] + push: + branches: [main] + +concurrency: + group: rivet-preview-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + rivet-preview: + runs-on: ubuntu-latest + permissions: + pull-requests: write + steps: + - uses: rivet-dev/preview-namespace-action@v1 + with: + platform: vercel + rivet-token: ${{ secrets.RIVET_CLOUD_TOKEN }} + vercel-token: ${{ secrets.VERCEL_TOKEN }} +``` + +## Troubleshooting + +``` +Error: ENOENT: no such file or directory, mkdir '.../rivetkit/.../state' +``` + +**Cause:** The `RIVET_ENDPOINT` environment variable is not configured. RivetKit falls back to the file system driver, which fails in Vercel's read-only serverless environment. + +**Solution:** Ensure `RIVET_ENDPOINT` is set with your Rivet endpoint using the URL auth format: + +``` +RIVET_ENDPOINT=https://my-namespace:sk_****@api.rivet.dev +``` + +If using the [preview-namespace-action](https://github.com/rivet-dev/preview-namespace-action), this is configured automatically. + +The `/api/rivet/metadata` endpoint returns data but `clientEndpoint`, `clientNamespace`, and `clientToken` are missing. + +**Cause:** The `RIVET_PUBLIC_ENDPOINT` environment variable is not configured. This tells the metadata endpoint what connection info to provide to clients. + +**Solution:** Set `RIVET_PUBLIC_ENDPOINT` with the publishable token (for client access): + +``` +RIVET_PUBLIC_ENDPOINT=https://my-namespace:pk_****@api.rivet.dev +``` + +If using the [preview-namespace-action](https://github.com/rivet-dev/preview-namespace-action), this is configured automatically. + +Rivet fails to connect to your Vercel deployment with a 401 error mentioning "Authentication Required". + +**Cause:** [Vercel Deployment Protection](https://vercel.com/docs/security/deployment-protection) is blocking requests from Rivet. + +**Solution:** + +1. Create a bypass secret in your Vercel project settings +2. In Rivet, go to **Settings > Providers** +3. Click the three dots on your provider and select **Edit** +4. Click **Add Header** and add `x-vercel-protection-bypass` with your bypass secret + +If using the [preview-namespace-action](https://github.com/rivet-dev/preview-namespace-action), this is configured automatically. + +## Related + +- [Next.js Quickstart](/docs/actors/quickstart/next-js) +- [Self-Hosting](/docs/general/self-hosting) + +_Source doc path: /docs/deploy/vercel_ diff --git a/.agents/skills/rivetkit/reference/deploy/vm-and-bare-metal.md b/.agents/skills/rivetkit/reference/deploy/vm-and-bare-metal.md new file mode 100644 index 0000000..6a123f9 --- /dev/null +++ b/.agents/skills/rivetkit/reference/deploy/vm-and-bare-metal.md @@ -0,0 +1,96 @@ +# Deploying to VMs & Bare Metal + +> Source: `src/content/docs/deploy/vm-and-bare-metal.mdx` +> Canonical URL: https://rivet.dev/docs/deploy/vm-and-bare-metal +> Description: Deploy your RivetKit app to any Linux VM or bare metal host. + +--- +## Steps + +### Prerequisites + +- A Linux VM or bare metal server with SSH access +- Your RivetKit app + - If you don't have one, see the [Quickstart](/docs/actors/quickstart) page or our [Examples](https://github.com/rivet-dev/rivet/tree/main/examples) +- Access to the [Rivet Cloud](https://dashboard.rivet.dev/) or a [self-hosted Rivet Engine](/docs/general/self-hosting) + +### Upload Your App + +- Build your RivetKit app locally +- Copy the build output to your server (example): + +```bash +scp -r ./dist user@server:/opt/rivetkit-app +``` + +Place the files somewhere readable by the service user, such as `/opt/rivetkit-app`. + +### Set Environment Variables + +After creating your project on the Rivet dashboard, select VM & Bare Metal as your provider. You'll be provided `RIVET_ENDPOINT` and `RIVET_PUBLIC_ENDPOINT` environment variables to use in the next step. + +### Create the systemd Service + +Create `/etc/systemd/system/rivetkit-app.service`: + +```ini +[Unit] +Description=RivetKit App +After=network.target + +[Service] +Type=simple +WorkingDirectory=/opt/rivetkit-app +ExecStart=/usr/bin/node server.js +Restart=on-failure +Environment=RIVET_ENDPOINT= +Environment=RIVET_PUBLIC_ENDPOINT= + +[Install] +WantedBy=multi-user.target +``` + +Replace the environment values with those from the Rivet dashboard and adjust paths to match your deployment. + +### Start the Service + +Reload systemd units and start the service: + +```bash +sudo systemctl daemon-reload +sudo systemctl enable --now rivetkit-app.service +``` + +### Connect to Rivet + +1. Ensure your server is accessible via a public URL (e.g. `https://my-app.example.com`) +2. On the Rivet dashboard, paste your URL with the `/api/rivet` path into the connect form (e.g. `https://my-app.example.com/api/rivet`) +3. Click "Done" + +If you front your app with a reverse proxy or load balancer (NGINX, HAProxy, Caddy, AWS ALB/NLB, etc.), raise its idle / read timeout to at least 1 hour (`3600` seconds). Rivet envoys connect to your app over long-lived WebSockets, and clients (browsers, SDKs) do the same. Default proxy timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +Examples: + +- **NGINX**: `proxy_read_timeout 3600s;` and `proxy_send_timeout 3600s;` in the relevant `location` block. +- **HAProxy**: `timeout client 1h` and `timeout server 1h` in the matching frontend / backend. +- **AWS ALB / NLB**: set the load balancer attribute `idle_timeout.timeout_seconds = 3600`. + +## Operating + +### Restart + +Restart the service after deploying new builds or environment changes: + +```bash +sudo systemctl restart rivetkit-app.service +``` + +### Logs + +Follow realtime logs when debugging: + +```bash +sudo journalctl -u rivetkit-app.service -f +``` + +_Source doc path: /docs/deploy/vm-and-bare-metal_ diff --git a/.agents/skills/rivetkit/reference/general/actor-configuration.md b/.agents/skills/rivetkit/reference/general/actor-configuration.md new file mode 100644 index 0000000..72bc6fd --- /dev/null +++ b/.agents/skills/rivetkit/reference/general/actor-configuration.md @@ -0,0 +1,19 @@ +# Actor Configuration + +> Source: `src/content/docs/general/actor-configuration.mdx` +> Canonical URL: https://rivet.dev/docs/general/actor-configuration +> Description: This page documents the configuration options available when defining a RivetKit actor. The actor configuration is passed to the `actor()` function. + +--- +## Basic Example + +## Configuration Reference + +## Related + +- [Registry Configuration](/docs/general/registry-configuration): Configure the RivetKit registry +- [State](/docs/actors/state): Managing actor state +- [Actions](/docs/actors/actions): Defining actor actions +- [Lifecycle](/docs/actors/lifecycle): Actor lifecycle hooks + +_Source doc path: /docs/general/actor-configuration_ diff --git a/.agents/skills/rivetkit/reference/general/architecture.md b/.agents/skills/rivetkit/reference/general/architecture.md new file mode 100644 index 0000000..3da2912 --- /dev/null +++ b/.agents/skills/rivetkit/reference/general/architecture.md @@ -0,0 +1,452 @@ +# Architecture + +> Source: `src/content/docs/general/architecture.mdx` +> Canonical URL: https://rivet.dev/docs/general/architecture +> Description: - rivetkit is the typescript library used for both local development & to connect your application to rivet - a rivetkit instance is called a "runner." you can run multiple runners to scale rivetkit horizontally. read omre about runners below. + +--- +## 3 ways of running + +### rivetkit + +- rivetkit is the typescript library used for both local development & to connect your application to rivet +- a rivetkit instance is called a "runner." you can run multiple runners to scale rivetkit horizontally. read more about runners below. + +#### local development + +- in local development, rivetkit provides a full actor environment for single-node deployments + +#### drivers + +- rivetkit supports multiple drivers. currently supports: file system (default in local dev), memory, rivet engine (used for rivet cloud & self-hosting), cloudflare durable objects (does not rely on rivet engine) +- drivers are very flexible to enable you to write your actors once and plug in to any system that fits your architecture adequately +- see the driver interface + - actordriver https://github.com/rivet-dev/rivet/blob/eeb01fc4d9ca0e06f2e740d267bd53280ca7330e/rivetkit-typescript/packages/rivetkit/src/actor/driver.ts + - managerdriver https://github.com/rivet-dev/rivet/blob/eeb01fc4d9ca0e06f2e740d267bd53280ca7330e/rivetkit-typescript/packages/rivetkit/src/manager/driver.ts + +### rivet cloud + +- provides multi-region and highest performance out of the box +- accessible at dashboard.rivet.dev and the api is avialble at api.rivet.dev + +### rivet self-hosted + +- available as a standalone rust binary or a docker contianer +- can be configured to persist to postgres or rocksdb +- can scale horiziontally across multipe nodes and can scale across multiple regions +- see [self-hosting docs](/docs/self-hosting/) + +## actors + +- Actors for long-lived processes with durable state, realtime, and hibernate when not in use. read more about actors at a high level at (link to actors/index) + +### actor-per-entity + +- actors are designed to have an actor-per-entity +- you can think about actors a bit like objects in object-oriented programming where each is responsible for their own state and expose methods (ie actions in our case) +- examples include + - actor per user + - actor per user session + - actor per document + - actor per game room + - actor per tenant + - actor per rate limit topic + +### architecting for scale + +- actors scale by: + - having isolated state to each actor that combines compute and storage for in-memory reads and writes + - communication is standardized based on actions & events + - scale horizontally +- read more about scaling at [Design Patterns](/docs/actors/design-patterns) + +### horizontal scaling + +- actors can run across multiple rivetkit runners. this is orchestrated by rivetkit itself. + +### lifecycle + +actors have create, destroy, wake, and sleep lifecycle hooks that you can implement to modify behavior. see the lifecycle docs for reference on actor lifecycel hook sequences + +### actor sleeping + +- actors sleep when not in use +- an actor is considered not in use when there are no active network connections to the actor (or the network connections are hibernatable websockets, see below) and there are no actions in flight +- actors have a sleep timeout (configured in `options.sleepTimeout`) that decides how long to keep the actor in memory with no recent activity +- sleep can be held off for the lifetime of a promise with `c.keepAwake(promise)` +- see the [sleeping docs](/docs/actors/lifecycle#sleeping) for full details + +### wake events + +- actors can wake to any of the follwoing events: + - network requests + - websocket messages + - alarms (see scheduling docs) + +### live actor migration + +- live actor migrations lets your application ugprade, crash, or hot reload cahnges without interruption to your user or application (including websockets) +- this is powered by hibernating websockets for live websocket migraiton & our fault tolerance mechanism (read more below) + +### coldstart performance + +- actors have negligible coldstart performance. the code to run the actor is already started (ie the runner), so creating/starting an actor is incredibly cheap. +- creating new actors with a key requires some overhead to communicate with other regions in order to reserve the actor's key (see below). actors can be created without keys with near-0 latency. + +### multi-region, globally unique actor keys + +- actors can optionally have a globally unique "key" +- when creating an actor with a key +- this system is highly optimized to reduce wan round trips using per-key Paxos with a custom database called Epoxy (https://github.com/rivet-dev/rivet/tree/main/engine/packages/epoxy) +- limitation: when creating an actor with a given key, that key will always be pinned to that region even if the actor is destroyed. creating a new actor with the same key will always live in the same region. +- see the actors keys document + +### input + +- actors have input data that can be passed to them when constructed +- this is similar to apssing data to a constructor in an object + +### generic parameters + +actor definitions include the following generic parameters that you'll see frequently in the code: + +- state +- conn state +- conn params +- ephemeral variables +- input data +- (experimental) database connector + +### persistence + +- state automatically flushes to storage intelligently +- to force a state flush and wait for it to finish, call (TODO: look this up in state document) +- read more about state persistence in the state document (link to document) +- state is stored in the same place as where the actor lives. loading an actor in to memory has comparable performance to network attached storage, and once in memory, has performance of any standard in-memory read/write like a variable. + +### scheduling & alarms + +- actors have a scheduling api to be able to wake up at any time in the indefinite future +- think of this like setTimeout but without a max timeout +- rivet is responsible for waking the actor when this timeout wakes + +### ephemeral variables + +- actors have the ability to create ephemrla variables for things that you do not want to be persisted with the actor's state +- this is useful for non-serializable data like a utility class like a pubsubs erver or something (TODO extra info) +- link to ephemeral variables docs + +### actions + +- for stateless clients, actions are sent as http requests via `POST /gateway/{actor id}/actions/{action name}` +- for stateful clients, actions are sent as websocket messages + +### events & subscriptions + +- events are sent as websocket messages + +### error handling + +- this is different than fault tolerance: + - error handling is a user error + - fault tolerance is something goes wrong that your applciation was not built to handle (ie hard crash, oom, network error) +- rivet provdies a special UserError class to throw custom errors that will be returned to the client +- all other errors are returned as a generic "internal error" +- this is becuase leaking error deatils is a common security hole, so we default to expose-nothing errors + +### logging + +- rivet uses pino for logging +- we expose a scoped child logger for each actor at `c.log` that automatically logs the actor id + key +- this allows you to search lgos easily by actor id without having to log the actor id frequently +- logs can be configured via the `RIVET_LOG_LEVEL` env var + +### fault tolerance + +- actors are fault tolerant, meaning that the host machine can crash and the actors will proceed to operate as if nothing happened +- runners maintain a socket with rivet engine. when this socket closes or takes to long to ping, actors will reschedule +- hibernating websockets (enabled by default) will live-migrate to the new actor as if nothing happened + +### crash policy + +- there are 3 crash policies: sleep, restart, and destroyed + - sleep (default, usually the option you want): + - when to use: actors that need high-performance in-memory logic. + - when not to use: you need this actor running at all times no matter what, even if idle + - examples: (list commone xamples) + - destroy: + - when to use: actors that need to run once until completion. on crash, do not try to reschedule. + - when not to use: if you want your actor to have fault tolerance and be able to run transaprenlty to the underlying runner + - examples: batch jobs, image conversions, ephemeral jobs, (TODO come up with better eaxmples) + - restart: + - when to use: actors that should be running at all times + - when not to use: if you don't absolutely need something running at all times, since this consumes needless compute resources. considure using the scheduling api instead. + - examples: maintain outbound sockets, daemons, always-running jobs, (TODO come up with better examples) + +the behavior for each is described below: + +| Event | Restart | Sleep | Destroy | +|------------------------------|--------------|--------------|--------------| +| Graceful exit (StopCode::Ok) | Destroy | Destroy | Destroy | +| Crash (non-Ok exit) | Reschedule | Sleep | Destroy | +| Lost (runner disappeared) | Reschedule | Sleep | Destroy | +| Lost + force_reschedule | Reschedule | Reschedule | Reschedule | +| GoingAway (runner draining) | Reschedule | Sleep | Destroy | +| No capacity (allocation) | Queue (wait) | Sleep | Queue (wait) | +| No capacity + serverless | Queue (wait) | Queue (wait) | Queue (wait) | +| Wake signal (while sleeping) | Reschedule | Reschedule | Reschedule | + +### inspector + +- actors provide an inspector api to implement the: + - repl + - state read/write + - network inspector + - event log +- this is impelmented over a websocket over bare + +### http api + +- see the http api document on actors + +### multi-region + +- actors can be scheduled across multiple regions +- each actor has an actor id which embeds which region it lives in +- networking is automatically routed to the region that an actor lives in +- limitation: actors curretnly cannot migrate across regions + +### backpressure + +#### no runner capacity + +- this is how actors with different crash policies behave when when there's backpressure: + - sleep = sleeps (sheds load by not rescheduling) + - restart = queues + - destroy = queues +- see the above matrix for more details on actor crash policy on how it handles no capacity. + +- the actor queue is built to withstand high amounts of backpressure on rivet, so queueing actors is fine here +- a large queue means it'll take more time for your application to process the queue to catch up with demand when it comes online. + +#### per-actor cpu & networking exhaustion + +- actors are isolated, so they each have their own individual bottleneck. you can think of this like a process thread where each thread can only do so much. +- there is no durable message queue/"mailbox" for actors. if the actor cannot respond in time, then the request is dropped. +- if an actor exhauses its cpu or networking, then the runner +- returns service unavailble (503) if the actor fails to respond to a request in time +- there is no hard cap on the networking or cpu usage for each actor at the moment +- if your actor is resource intensive, it's common to use a separate mailbox actor to act as a queue + +## runners + +### regular vs serverless runners + +there are 2 types of runners: + +- regular: these are standard nodejs processes connected to rivet that rivet can orchestrate actors to and send network requests to at any time +- serverless: rivet works with serverless platforms. when an actor is created, it has a request-per-actor model where it opens a long-running request on the serverless platofrm to run a given actor. + +### runner pool + +- runners are pooled together by sharing a common name (ie "default") +- when an actor is created, it chooses the pool by selecting the runner name to run on +- rivet will automatically load balance actors across these runners + +### runner key + +- not relevnat for serverless runners +- each runner has a unique key that it provides when connecting. keys are unique to the instace the runner is running on and should be the same if the runner is restarted. +- this can be the: machine's ip, k8s pod name, etc +- if there is an existing runner connected with a given key, the runner will disconnect the old runner and replace it +- rivet is designed to handle network partitions by waiting for runners to miss a ping, indicating it's no longer alive. however, often times runners restart immediately after a hard crash and reconnect. in this case, the runner will reconnect on restart and terminate the old runner in order to prevent further actors from scheduling to the crashed runner. + +### capacity + +- not relevnat for serverless runners +- each runner can be assigned a capacity of how many actors it can run +- rivet will schedule with spread (not binpacking) in order to spread load over actors + +#### usefulness of capacity = 1 + +- setting a capacity of 1 is helpful for situations where you have cpu-intensive apps that should not run with any other actors +- examples include game servers, ffmpeg jobs, etc + +### versions & upgrading code + +- each runner has a version index +- actors are always scheduled to the highest verison index (see runner priority below) +- this means that when a new runner is deployed: + 1. runners with higher index come online + 2. actors schedule to the highest index, stop scheduling to the older index + 3. old index runners start draining and migrating actors to new index + 4. all old runners are now shut down +- websocekts are live migrated to the new version when upgrading using hibernating websockets to users see no hiccup in their applications +- this is important because actors should never downgrade their runner. they should always move to a newer version of code in order to prevent corruption. + +### runner scheduling prioroty + +- actors are scheduled to runners sorted by priority of (version DESC, remaining capacity ASC) + +### multi-region + +TODO + +### shutdown sequence + +- runner shutdown is important to ensure that actors do not get unexpectedly terminated when either: + - upgrading your applciation and taking down old pods + - scaling down your runners horizontally (ie from an hpa) + - pressing ctrl-c when in development +- on shutdown: + 1. tell rivet the runner is stopping + 2. rivet tells all the actors on this runner to migrate + 3. runner waits for all actors to finish migrating + 4. runner exits process + +### reconnection + +- runners can handle temporary network partitions +- they'll automatically reconnect and replay missed commands/events between rivet and the runner +- this happens transparenlty to the user +- if disconnected for too long (indicating a network partition), the runner will shut itself down and exit + +### autoscaling + +- not relevant to serverless +- runners currently autoscale on cpu. more intelligent scaling is coming soon. +- tune your runner total slots capacity accordingly +- it's up to you to configure your hpa/etc to work like this. see the Connect guides (link to index page) for reference on hwo to configure this. + +### serverless timeouts + +- serverless runners take in to account the maximum run duration of the serverless platform +- the runners will mgirate actors to a new request before the request times out +- this is completely transparent to you and the user because of the fault tolerance and websocket migraiton characteristics +- it's common for actors to go sleep before hitting the serverless timeout + +## networking + +### web standards + +- everything in rivet is built on webstandards by default +- nothing in rivet requires you to use our sdk, our sdks are meant to be a convenience. it's built to be as easy to use raw http/websocket endpoints from scratch. +- actions, events, etc are all built on simple, well-documented http/websocket under the hood (link to openapi & asyncapi docs). +- you can use low-level request handlers (lnk to dock) and low-level weboscket handlers (link to doc) to handle low-level primtivies yourself + +### encoding + +- rivetkit's action/events api supports communicating via [VBARE](link to github repo, see the blog post for the link), CBOR, or JSON + - VBARE: high-perofrmance & compact, optimal use case + - CBOR: descent encoding/decoding perf + portable libraries, good for implemnting high-ish performance on other platforms + - JSON: good for fast implementations & debugging (easy to read) + +### tunneling + +- when a runner connects it opens a tunnel to rivet to allow incoming traffic + - this is simila to systems like tailscale, ngrok, or other vpns + - we do this for security & configuraiton simplicity since it means that you don't have to manage exposing your rivetkit applications' networkig to rivet. instead, anything that can open a socket to rivet can accept inbound traffic to actors. + +### gateway + +- incoming traffic to actors come to the Rivet gateway and are routed to the appropriate runner +- the rivet gateway automatically handles: + - multi-region routing to route traffic to the correct reigon for an actor + - automatically waking the actor if needed + - sending traffic over the runner + +### hibernating websockets + +- hibernating web sockets are a core component of live actor migration & fault tolerance. it allows us to maintain an open websocket while the actor crashes, upgrades, or moves to another runner. +TODO: copy the rest of this from low-level webosckets document and rephrase + +### actor health endpoin + +- actors provide a simple, utility health endpoint at `/health` that lets you check if your actor is reachable (e.g. `curl https://api.rivet.dev/gateway/{actor id}/health`) + +## multi-region + +### networking + +- actors may live in different regions than inbound requests +- Rivet uses the Epoxy (link again) system to handle global routing to route traffic to the correct region with high performance +- this is completely transparent to you. your app sends traffic to https://api.rivet.dev/gateway/* and it automatically routes to the correct actor in the appropriate region + +### globally unique actor keys + +- actor keys are globally unique to be able to benefit from multi-region capabilities without any extra work +- see more about globally uniuqe actor keys above +- see the actor keys document + +### regional endpoints + +- each reigon has a regional endpoint +- this endpoint is used specifically for connecting runners (for example https://api-us-east-1.rivet.dev), opt to use api.rivet.dev for all other traffic +- runners are required to connect to the regional endpoints + - this is because runners are sensitive to latency to the rivet regional datacenter + - we add datacenters regularly so each runner needs to be pinned to a single datacenter in order to ensure your availble datacneter list doesn't change sporadically without your consent + +### persistence + +- data is always persisted in the same region that is written +- this is important for minimal coldstarts & data locality laws + +## namespaces + +- rivet provides namespaces to run multiple actor systems in isolation +- this makes it really easy to have prod/staging environments or completely different applications running on the same rivet instance +- when you connect to rivet, you can specify which namespace you're connecting to +- self-hotsed rivet defaults to namespace "default" +- rivet cloud provdies isolated tokens for each namespace + +## manager api + +- rivet provides a standard rest api for managing actors + - useful endoints include: + - get /actors + - delete /actors/{} + - get /actors/names -> get all actor types available + +## comparison to prior art for actors + +### runtime + +- there are very few serious actor implementation targeted at the javascirpt eocsystem. rivet is arguably the most serious open-source actor implementation for typescript out there. + +### library vs orchestrator + +- some actor systems opt to be purely a library while rivet opts to have an orchestrator (i.e. the single rust binary) +- this lets us to a lot of things other actor systems can't: + - separating orchestration, persistence, and proxy lets us isoalte the core to be incredibly reliable while the fast-changing applications that ocnnect to rivet can be more error-prone safely. with a library, the blast radius of your application also affects the entire actor system. + - support for serverless platforms to benefit from cost, multi-region, blitz scaling, and relibaiblity benefits + - optimize fault tolerance since we can make more assumtions about application state when the rivet core does not crash and your app does + +### scheduling + +actors is a loose term, but there are generally 2 types of schedulign in practice: + +- ephemeral actors + - examples: erlang/otp, akka, swift + - provides no persistence or sleeping mechanism by defualt + - relies on supervisors for managing persistence +- [virtual actors](https://www.microsoft.com/en-us/research/project/orleans-virtual-actors/) + - an extension of the actor pattern that provides actors that can hibernate ("sleep") when not in use + - examples: orleans, dapr, durable objects + +rivet has similarities with both to provide more flexibility: + +- crash policies provdie for 3 types of actors: + - sleep -> most similar to virutal actors + - restart -> most similar to ephemeral actors but with a supervisor to auto-restart, however still has a durable queue ot handle backpressure + - crash -> most similar to traditional actors but with no supervisor to restart, however still has a durable queue to handle backpressure + +### communication + +- many actor frameworks use inbox patterns (think: queue-per-actor) to handle sending messages between actors +- there is no callback mechanims, instead you need to send messages back to the actual actor +- rivet opts to behave like web standards instead of using the message pattern + - actors can impelment the inbox pattern optionally + - but we provide lower-level networking to be able to be compatible with more techniologies + - rivet assumes the same serial concurerntly that other actors do (by the nature of javascript being single-threaded) but we allow you to run promises in parallel or handl eyour own concurrency control (which some other actor frameworks might require a spawning new actor to do) + +_Source doc path: /docs/general/architecture_ diff --git a/.agents/skills/rivetkit/reference/general/cors.md b/.agents/skills/rivetkit/reference/general/cors.md new file mode 100644 index 0000000..330fe38 --- /dev/null +++ b/.agents/skills/rivetkit/reference/general/cors.md @@ -0,0 +1,18 @@ +# Cross-Origin Resource Sharing + +> Source: `src/content/docs/general/cors.mdx` +> Canonical URL: https://rivet.dev/docs/general/cors +> Description: Cross-Origin Resource Sharing (CORS) controls which origins (domains) can access your actors. When actors are exposed to the public internet, proper origin validation is critical to prevent security breaches and denial of service attacks. + +--- +Unlike stateless HTTP APIs that use CORS headers, Rivet Actors are stateful and support persistent WebSocket connections. Since WebSockets don't natively support CORS, we validate origins manually in the `onBeforeConnect` hook before connections may open. + +## Implementing Origin Restrictions + +To implement origin restrictions on Rivet Actors, use the `onBeforeConnect` hook to verify the request. + +To catch the error on the client, use the following code: + + See tracking issue for [configuring CORS per-actor on the gateway](https://github.com/rivet-dev/rivet/issues/3539) that will remove the need to implement origin restrictions in `onBforeRequest`. + +_Source doc path: /docs/general/cors_ diff --git a/.agents/skills/rivetkit/reference/general/docs-for-llms.md b/.agents/skills/rivetkit/reference/general/docs-for-llms.md new file mode 100644 index 0000000..db0c216 --- /dev/null +++ b/.agents/skills/rivetkit/reference/general/docs-for-llms.md @@ -0,0 +1,51 @@ +# Documentation for LLMs & AI + +> Source: `src/content/docs/general/docs-for-llms.mdx` +> Canonical URL: https://rivet.dev/docs/general/docs-for-llms +> Description: Rivet provides optimized documentation formats specifically designed for Large Language Models (LLMs) and AI integration tools. + +--- +## Skills (Recommended) + +For AI coding assistants like Claude Code, Cursor, or Windsurf, install Rivet skills for the best development experience: + +```sh +npx skills add rivet-dev/skills +``` + +Skills provide your AI assistant with Rivet-specific knowledge, best practices, and code patterns directly in your project context. + +## Available Formats + +### `llms.txt` (Condensed) +A condensed version of the documentation perfect for quick reference and context-aware AI assistance. + +**Access:** /llms.txt + +This format includes: +- Key concepts and features +- Essential getting started information +- Summaries of main functionality +- Optimized for token efficiency + +### `llms-full.txt` (Complete) +The complete documentation in a single file, ideal for comprehensive AI assistance and in-depth analysis. + +**Access:** /llms-full.txt + +This format includes: +- Complete documentation content +- All examples and detailed explanations +- Full API references and guides +- Suitable for complex queries and comprehensive understanding + +## Access Pages As Markdown + +Each documentation page is also available as clean markdown by appending `.md` to any documentation URL path. + +For example: + +- Original URL: `https://rivet.dev/docs/actors` +- Markdown URL: `https://rivet.dev/docs/actors.md` + +_Source doc path: /docs/general/docs-for-llms_ diff --git a/.agents/skills/rivetkit/reference/general/edge.md b/.agents/skills/rivetkit/reference/general/edge.md new file mode 100644 index 0000000..814dde2 --- /dev/null +++ b/.agents/skills/rivetkit/reference/general/edge.md @@ -0,0 +1,24 @@ +# Edge Networking + +> Source: `src/content/docs/general/edge.mdx` +> Canonical URL: https://rivet.dev/docs/general/edge +> Description: Actors automatically run near your users on your provider's global network. + +--- +At the moment, edge networking is only supported on Rivet Cloud & Cloudflare Workers. More self-hosted platforms are on the roadmap. + +## Region selection + +### Automatic region selection + +By default, actors will choose the nearest region based on the client's location. + +Under the hood, Rivet and Cloudflare use [Anycast routing](https://en.wikipedia.org/wiki/Anycast) to automatically find the best location for the client to connect to without relying on a slow manual pinging process. + +### Manual region selection + +The region an actor is created in can be overridden using region options: + +See [Create Manage Actors](/docs/actors/communicating-between-actors) for more information. + +_Source doc path: /docs/general/edge_ diff --git a/.agents/skills/rivetkit/reference/general/endpoints.md b/.agents/skills/rivetkit/reference/general/endpoints.md new file mode 100644 index 0000000..5c376e1 --- /dev/null +++ b/.agents/skills/rivetkit/reference/general/endpoints.md @@ -0,0 +1,98 @@ +# Endpoints + +> Source: `src/content/docs/general/endpoints.mdx` +> Canonical URL: https://rivet.dev/docs/general/endpoints +> Description: Configure how your backend connects to Rivet and how clients reach your actors. + +--- +## Local Development + +No configuration is needed for local development. RivetKit runs entirely on your local machine without any extra configuration to run Rivet Actors. + +## Production Deployment + +When deploying to production, you need to configure endpoints so your backend can communicate with Rivet Engine and clients can reach your actors. + +Diagram showing Client connecting to Rivet, which connects to Your Backend + +### Private Endpoint + +The private endpoint tells your backend where to find the Rivet Engine. + +### Environment Variable + +```bash +RIVET_ENDPOINT=https://my-namespace:sk_xxxxx@api.rivet.dev +``` + +### Config + +### Public Endpoint + +The public endpoint tells clients where to connect to reach your actors. + +This endpoint and token will be exposed to the internet. Use a public token (`pk_`), not your secret token (`sk_`). + +The public endpoint is only required if using the [serverless runtime mode](/docs/general/runtime-modes#runners) and if you have a frontend using RivetKit. + +### Environment Variable + +```bash +RIVET_PUBLIC_ENDPOINT=https://my-namespace:pk_xxxxx@api.rivet.dev +``` + +### Config + +## Advanced + +### URL Auth Syntax + +Endpoint URLs support embedding namespace and token directly in the URL: + +``` +https://namespace:token@host/path +``` + +This is the recommended approach for simplicity. Alternatively, you can use separate environment variables: + +```bash +RIVET_ENDPOINT=https://api.rivet.dev +RIVET_NAMESPACE=my-namespace +RIVET_TOKEN=sk_xxxxx +``` + +### Security + +In serverless mode, the private endpoint is used to validate that requests to `GET /api/rivet/start` are coming from your trusted Rivet endpoint. If the private endpoint is not configured, anyone can run a self-hosted instance of Rivet and connect to your backend from any endpoint. + +### How Clients Connect + +This flow applies to [serverless runtime mode](/docs/general/runtime-modes#serverless). For [runner runtime mode](/docs/general/runtime-modes#runners) or [clients configured to connect directly to Rivet](/docs/clients/javascript), clients connect directly to Rivet and this metadata flow is not needed. + +When a client connects to your serverless application, it follows this flow: + +1. Client makes a request to `https://my-app.example.com/api/rivet/metadata` +2. Your app returns the public endpoint configuration: + ```json + { + "clientEndpoint": "https://api.rivet.dev", + "clientNamespace": "my-namespace", + "clientToken": "pk_xxxxx" + } + ``` +3. Client caches these values and uses them for subsequent requests +4. Client connects to `https://api.rivet.dev/gateway/{actor}`, which routes requests to your actors + +This indirection exists because Rivet acts as a gateway between clients and your actors. This is because Rivet handles routing, load balancing, and actor lifecycle management of actors. + +## Reference + +| Environment Variable | Config Option | Description | +|---------------------|---------------|-------------| +| `RIVET_ENDPOINT` | `endpoint` | Rivet Engine URL for your backend | +| `RIVET_NAMESPACE` | `namespace` | Namespace for actor isolation | +| `RIVET_TOKEN` | `token` | Authentication token for engine connection | +| `RIVET_PUBLIC_ENDPOINT` | `serverless.publicEndpoint` | Client-facing endpoint | +| `RIVET_PUBLIC_TOKEN` | `serverless.publicToken` | Client-facing token | + +_Source doc path: /docs/general/endpoints_ diff --git a/.agents/skills/rivetkit/reference/general/environment-variables.md b/.agents/skills/rivetkit/reference/general/environment-variables.md new file mode 100644 index 0000000..2a86e98 --- /dev/null +++ b/.agents/skills/rivetkit/reference/general/environment-variables.md @@ -0,0 +1,87 @@ +# Environment Variables + +> Source: `src/content/docs/general/environment-variables.mdx` +> Canonical URL: https://rivet.dev/docs/general/environment-variables +> Description: This page documents all environment variables that configure RivetKit behavior. + +--- +## Connection + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_ENDPOINT` | Endpoint URL to connect to Rivet Engine. Supports [URL auth syntax](/docs/general/endpoints#url-auth-syntax). | +| `RIVET_TOKEN` | Authentication token for Rivet Engine | +| `RIVET_NAMESPACE` | Namespace to use (default: "default") | + +## Public Endpoint + +These variables configure how clients connect to your actors. + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_PUBLIC_ENDPOINT` | Public endpoint for client connections. Supports [URL auth syntax](/docs/general/endpoints#url-auth-syntax). | +| `RIVET_PUBLIC_TOKEN` | Public token for client authentication | + +## Runner Configuration + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_RUNNER` | Runner name (default: "default") | +| `RIVET_RUNNER_VERSION` | Version number for the runner. See [Versions & Upgrades](/docs/actors/versions). | +| `RIVET_RUNNER_KIND` | Type of runner | +| `RIVET_TOTAL_SLOTS` | Total actor slots available (default: 100000) | + +## Engine + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_RUN_ENGINE` | Set to `1` to spawn the engine process | +| `RIVET_RUN_ENGINE_HOST` | Host to bind the spawned local engine process to. Defaults to `127.0.0.1`. | +| `RIVET_RUN_ENGINE_PORT` | Port to bind the spawned local engine process to. Defaults to `6420`. | +| `RIVET_RUN_ENGINE_VERSION` | Version of engine to download | + +## Inspector + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_INSPECTOR_DISABLE` | Set to `1` to disable the inspector | + +## Metrics + +| Environment Variable | Description | +|---------------------|-------------| +| `_RIVET_METRICS_TOKEN` | Bearer token that gates the per-actor Prometheus `/metrics` endpoint. When unset, `/metrics` is disabled. | + +## Experimental + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_EXPERIMENTAL_OTEL` | Set to `1` to enable experimental OTel tracing in Rivet Actors | + +## Storage + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVETKIT_RUNTIME` | Runtime binding to use for RivetKit core: `auto`, `native`, or `wasm`. Defaults to `auto`. | +| `RIVETKIT_STORAGE_PATH` | Overrides the default file-system storage path used by RivetKit when using the default driver. | + +## Lifecycle + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVETKIT_RUNTIME_MODE` | Controls how `registry.start()` runs. Accepted values are `envoy` and `serverless`; any other explicit value errors. Defaults to `envoy`: opens a long-lived WebSocket to the engine (Mode A). Set to `serverless` to bind an HTTP listener via `registry.listen()` (Mode B). | +| `RIVETKIT_PUBLIC_DIR` | Directory of static assets to serve alongside the framework routes when calling `registry.listen()`. Used as a fallback when `opts.publicDir` is not passed. On auto-listen via `registry.start()`, defaults to `/public` when this env var is unset. | +| `RIVET_PORT` | Port the listener binds when calling `registry.listen()` without an explicit `opts.port`. Must be an integer between 1 and 65535. Defaults to `3000`. | + +## Logging + +| Environment Variable | Description | +|---------------------|-------------| +| `RIVET_LOG_LEVEL` | Log level: `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `silent` | +| `RIVET_LOG_TARGET` | Set to `1` to include log target | +| `RIVET_LOG_TIMESTAMP` | Set to `1` to include timestamps | +| `RIVET_LOG_MESSAGE` | Set to `1` to include message formatting | +| `RIVET_LOG_ERROR_STACK` | Set to `1` to include error stack traces | +| `RIVET_LOG_HEADERS` | Set to `1` to log request headers | + +_Source doc path: /docs/general/environment-variables_ diff --git a/.agents/skills/rivetkit/reference/general/http-server.md b/.agents/skills/rivetkit/reference/general/http-server.md new file mode 100644 index 0000000..c3a386c --- /dev/null +++ b/.agents/skills/rivetkit/reference/general/http-server.md @@ -0,0 +1,96 @@ +# HTTP Server + +> Source: `src/content/docs/general/http-server.mdx` +> Canonical URL: https://rivet.dev/docs/general/http-server +> Description: Different ways to run your RivetKit HTTP server. + +--- +## Methods of Running Your Server + +### registry.start() + +The simplest way to run your server. Starts a local RivetKit server, serves static files from a `public` directory, and starts the actor runner: + +Run with `npx tsx --watch index.ts` (Node.js), `bun --watch index.ts` (Bun), or `deno run --allow-net --allow-read --allow-env --watch index.ts` (Deno). Clients connect to the Rivet Engine on `http://localhost:6420`. + +### With Fetch Handlers + +A [fetch handler](https://wintercg.org/) is a function that takes a `Request` and returns a `Response`. This is the standard pattern used by Cloudflare Workers, Deno Deploy, Bun, and other modern runtimes. + +Use `registry.serve()` to get a fetch handler: + +To integrate with a router like [Hono](https://hono.dev/) or [Elysia](https://elysiajs.com/), use `registry.handler()`: + +### Hono + +### Elysia + +Then run your server: + +```bash Node.js +npx tsx --watch server.ts +``` + +```bash Bun +bun --watch server.ts +``` + +```bash Deno +deno run --allow-net --allow-read --allow-env --watch server.ts +``` + +### Explicit HTTP Server + +If you need to explicitly start the HTTP server instead of using the fetch handler pattern: + +### Node.js (Hono) + +Using Hono with `@hono/node-server`: + +### Node.js (Adapter) + +Using `@whatwg-node/server` to adapt the fetch handler to Node's HTTP server: + +```ts server.ts @nocheck +import { actor, setup } from "rivetkit"; +import { createServer } from "node:http"; +import { createServerAdapter } from "@whatwg-node/server"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +const handler = createServerAdapter(registry.serve().fetch); +const server = createServer(handler); +server.listen(3000); +``` + +### Bun + +Using Bun's native server: + +```ts server.ts @nocheck +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +Bun.serve({ + port: 3000, + fetch: (request: Request) => registry.handler(request), +}); +``` + +### Deno + +Using Deno's native server: + +```ts server.ts @nocheck +import { actor, setup } from "rivetkit"; + +const myActor = actor({ state: {}, actions: {} }); +const registry = setup({ use: { myActor } }); + +Deno.serve({ port: 3000 }, (request: Request) => registry.handler(request)); +``` + +_Source doc path: /docs/general/http-server_ diff --git a/.agents/skills/rivetkit/reference/general/logging.md b/.agents/skills/rivetkit/reference/general/logging.md new file mode 100644 index 0000000..f7ce9eb --- /dev/null +++ b/.agents/skills/rivetkit/reference/general/logging.md @@ -0,0 +1,74 @@ +# Logging + +> Source: `src/content/docs/general/logging.mdx` +> Canonical URL: https://rivet.dev/docs/general/logging +> Description: Actors provide a built-in way to log complex data to the console. + +--- +Using the context's log object (`c.log`) allows you to log complex data using structured logging. + +Using the actor logging API is completely optional. + +## Log levels + +There are 7 log levels: + +| Level | Call | Description | +| ------ | ------------------------------- | ---------------------------------------------------------------- | +| Fatal | `c.log.fatal(message, ...args);` | Critical errors that prevent core functionality | +| Error | `c.log.error(message, ...args);` | Errors that affect functionality but allow continued operation | +| Warn | `c.log.warn(message, ...args);` | Potentially harmful situations that should be addressed | +| Info | `c.log.info(message, ...args);` | General information about significant events & state changes | +| Debug | `c.log.debug(message, ...args);` | Detailed debugging information, usually used in development | +| Trace | `c.log.trace(message, ...args);` | Very detailed debugging information, usually for tracing flow | +| Silent | N/A | Disables all logging output | + +## Structured logging + +The built-in logging API (using `c.log`) provides structured logging to let you log key-value +pairs instead of raw strings. Structured logs are readable by both machines & +humans to make them easier to parse & search. + +When using `c.log`, the actor's name, key, and actor ID are automatically included in every log output. This makes it easy to filter and trace logs by specific actors in production environments. + +### Examples + +The logging system is built on [Pino](https://getpino.io/#/docs/api?id=logger), a high-performance structured logger for Node.js. + +## Configuration + +### Environment Variables + +You can configure logging behavior using environment variables: + +| Variable | Description | Values | Default | +| -------- | ----------- | ------ | ------- | +| `RIVET_LOG_LEVEL` | Sets the minimum log level to display | `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `silent` | `warn` | +| `RIVET_LOG_TARGET` | Include the module name that logged the message | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_TIMESTAMP` | Include timestamp in log output | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_MESSAGE` | Enable detailed message logging for debugging | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_ERROR_STACK` | Include stack traces in error output | `1` to enable, `0` to disable | `0` | +| `RIVET_LOG_HEADERS` | Log HTTP headers in requests | `1` to enable, `0` to disable | `0` | + +Example: +```bash +RIVET_LOG_LEVEL=debug RIVET_LOG_TARGET=1 RIVET_LOG_TIMESTAMP=1 node server.js +``` + +### Log Level + +You can configure the log level programmatically when setting up your registry: + +### Custom Pino Logger + +You can also provide a custom Pino base logger for more advanced logging configurations: + +If using a custom base logger, you must manually configure your own log level in the Pino logger. + +For more advanced Pino configuration options, see the [Pino API documentation](https://getpino.io/#/docs/api?id=export). + +### Disable Welcome Message + +You can disable the default RivetKit welcome message with: + +_Source doc path: /docs/general/logging_ diff --git a/.agents/skills/rivetkit/reference/general/pool-configuration.md b/.agents/skills/rivetkit/reference/general/pool-configuration.md new file mode 100644 index 0000000..21b00f1 --- /dev/null +++ b/.agents/skills/rivetkit/reference/general/pool-configuration.md @@ -0,0 +1,119 @@ +# Pool Configuration + +> Source: `src/content/docs/general/pool-configuration.mdx` +> Canonical URL: https://rivet.dev/docs/general/pool-configuration +> Description: Reference for runner pool configuration, including drain behavior, actor eviction rate limiting, and serverless-specific options. + +--- +A **runner pool** is the set of runners Rivet manages for a given runner name within a namespace. The pool configuration controls how runners are scaled, drained on version upgrades, and how quickly actors are evicted from drained runners. + +There are two pool kinds: + +- **`normal`** — runners connect to the engine themselves (for example a long-running process started by you, Docker, or Kubernetes). The engine does not start or stop runners. +- **`serverless`** — the engine calls an HTTP endpoint to wake runners on demand. Used by serverless platforms (Vercel, Cloudflare Workers, Freestyle, etc.). See [Runtime Modes](/docs/general/runtime-modes). + +## Setting the Configuration + +Configure a pool from the [Rivet dashboard](https://dashboard.rivet.dev) under your namespace's runner settings. The dashboard is the recommended way to manage pool configuration. + +You can also set pool configuration directly through the API or the TypeScript SDK: + +```typescript SDK @nocheck +import { RivetClient } from "@rivetkit/engine-api-full"; + +const rivet = new RivetClient({ + environment: "https://api.rivet.dev", + token: process.env.RIVET_TOKEN!, +}); + +await rivet.runnerConfigsUpsert("default", { + namespace: "default", + datacenters: { + default: { + serverless: { + url: "https://my-app.example.com/api/rivet", + requestLifespan: 60 * 15, + actorEvictionDelay: 5, + actorEvictionPeriod: 60, + actorEvictionRate: 1, + }, + }, + }, +}); +``` + +```bash curl +curl -X PUT "https://api.rivet.dev/runner-configs/default?namespace=default" \ + -H "Authorization: Bearer $RIVET_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "datacenters": { + "default": { + "serverless": { + "url": "https://my-app.example.com/api/rivet", + "request_lifespan": 900, + "actor_eviction_delay": 5, + "actor_eviction_period": 60, + "actor_eviction_rate": 1 + } + } + } + }' +``` + +The HTTP API uses `snake_case`. The TypeScript SDK uses `camelCase`. The field names below use `camelCase`. + +## Common Options + +These options apply to both `normal` and `serverless` pools. + +| Option | Type | Default | Description | +|---|---|---|---| +| `drainOnVersionUpgrade` | `bool` | `true` | When a new runner version is deployed, stop old runners and migrate their actors. See [Versions & Upgrades](/docs/actors/versions#drain-on-version-upgrade). | +| `actorEvictionDelay` | `u32` (seconds) | `0` | Delay before actor eviction begins after a drain is triggered. Gives clients time to receive the drain signal before migrations start. | +| `actorEvictionPeriod` | `u32` (seconds) | `0` | Window over which evictions are batched. Used together with `actorEvictionRate` to smooth eviction load on the rest of the pool. | +| `actorEvictionRate` | `f32` (actors/sec) | `1.0` | Maximum number of actors evicted per second once eviction is underway. Set higher for fast cutovers, lower to spread reschedule load. | +| `metadata` | `object` | — | Arbitrary JSON metadata attached to the pool. Useful for tagging and dashboards. | + +### Tuning eviction rate limiting + +Eviction kicks in whenever a runner is drained — most commonly during a version upgrade with `drainOnVersionUpgrade: true`, but also when a runner disconnects ungracefully or is replaced. + +A typical tuning starts from: + +- `actorEvictionDelay: 5` — five-second head start so clients see the drain notification before migrations begin. +- `actorEvictionPeriod: 60` — batch over a one-minute window. +- `actorEvictionRate: 1` — evict one actor per second. + +Increase `actorEvictionRate` for small pools where a full cutover finishes in seconds. Decrease it for large pools to avoid bursts of reschedule traffic. + +## Serverless-Only Options + +These options only apply when `kind: "serverless"`. + +| Option | Type | Default | Description | +|---|---|---|---| +| `url` | `string` | — | HTTP endpoint the engine calls to wake a runner. | +| `headers` | `map` | `{}` | Additional headers sent with the wake request (for example an auth token). | +| `requestLifespan` | `u32` (seconds) | — | Total lifespan of a serverless request before drain begins. Must be shorter than your platform's request timeout. | +| `maxConcurrentActors` | `u64` | `1000` | Soft cap on concurrent actors hosted across the pool. | +| `drainGracePeriod` | `u32` (seconds) | `1800` (30 min) | Time a serverless runner reserves at the end of its lifespan for actors to stop gracefully. | +| `metadataPollInterval` | `u64` (ms) | engine default | How often each runner re-fetches pool metadata to detect new versions. | + +### Deprecated options + +The following options still parse for backwards compatibility but should not be used in new configurations: + +- `slotsPerRunner` +- `minRunners` +- `maxRunners` +- `runnersMargin` + +## Related + +- [Runtime Modes](/docs/general/runtime-modes) — runner vs serverless behavior. +- [Versions & Upgrades](/docs/actors/versions) — how `drainOnVersionUpgrade` interacts with version detection. +- [Limits](/docs/actors/limits) — request lifespan and drain grace period limits. +- [Debugging](/docs/actors/debugging) — inspect a pool configuration via the API. + +_Source doc path: /docs/general/pool-configuration_ diff --git a/.agents/skills/rivetkit/reference/general/production-checklist.md b/.agents/skills/rivetkit/reference/general/production-checklist.md new file mode 100644 index 0000000..1ebe257 --- /dev/null +++ b/.agents/skills/rivetkit/reference/general/production-checklist.md @@ -0,0 +1,98 @@ +# Production Checklist + +> Source: `src/content/docs/general/production-checklist.mdx` +> Canonical URL: https://rivet.dev/docs/general/production-checklist +> Description: Checklist for deploying Rivet Actors to production. + +--- +We recommend passing this page to your coding agent to verify your configuration before deploying. + +## Environment + +- **Set `NODE_ENV=production`.** Ensures optimized performance and disables development-only behavior. +- **Ensure log level is not set to debug.** Leave `RIVET_LOG_LEVEL` at its default or explicitly set it to `warn` to avoid excessive logging. See [Logging](/docs/general/logging). +- **Do not set `RIVET_EXPOSE_ERRORS=1` in production.** This exposes internal error details to clients. It is automatically enabled when `NODE_ENV=development`. See [Errors](/docs/actors/errors). + +## Runtime Mode + +- **Configure a runner version.** Required for graceful upgrades and draining of old actors. Applies to both serverless and runner modes. See [Versions & Upgrades](/docs/actors/versions). + +### Serverless + +- **Check platform timeouts.** Rivet handles migration between invocations automatically, but shorter timeouts increase migration frequency. See [Timeouts](/docs/general/runtime-modes#timeouts). +- **Verify `/api/rivet/start` body size limits.** Serverless actor starts carry actor config and preloaded KV or SQLite startup data in the request body. Keep `serverless.maxStartPayloadBytes` and your platform or proxy body limit at **16 MiB or higher**, or lower the preload budget if your platform cannot accept that size. See [Limits](/docs/actors/limits#kv-preloading). +- **Configure max runners.** Go to Settings > Providers > Edit Provider > Max Runners to set the limit. The default is 100,000 runners. This is effectively your max actor count. +- **Verify your platform rate limit accommodates your actor create and wake frequency.** Actor start requests are sent from Rivet's servers, so they all originate from the same IP. Per-IP rate limits will throttle the engine well before they would throttle real end-user traffic. Size your platform's rate limit to your peak actor create and wake rate, not your end-user request rate. +- **Set the per-instance max concurrent actor limit.** Each serverless instance hosts one actor per in-flight `/api/rivet/start` request, so your platform's per-instance concurrency (e.g. GCP Cloud Run `--concurrency`, AWS Lambda reserved concurrency, Vercel `maxDuration` + concurrency) directly caps actors per instance. Pick a value based on per-actor memory and CPU; the platform autoscales out additional instances once existing ones hit the cap. +- **Tune `requestLifespan` to your platform's hard request timeout.** `requestLifespan` (default `3600`, 60 minutes) is the total lifespan of each serverless request before actors migrate to a fresh instance. Set it just below your platform's hard timeout (e.g. `295` for Vercel Hobby, `3595` for Vercel Pro, `840` for Cloud Run's 15-min cap). Configure via [`configurePool`](/docs/general/registry-configuration). See [Timeouts](/docs/general/runtime-modes#timeouts). +- **Tune `drainGracePeriod` to cover graceful actor shutdown.** Time reserved at the end of `requestLifespan` for actors to stop gracefully before the request is forcibly closed. Default is 30 minutes from the engine; lower it for short-lived stateless actors, raise it if your actors do non-trivial cleanup or final SQLite writes. Configure via [`configurePool`](/docs/general/registry-configuration). See [Limits](/docs/actors/limits). + +### Runner + +- **Set a graceful shutdown period of at least 35 minutes.** Runners need up to 30 minutes to drain actors during upgrades, plus buffer for shutdown overhead. In Kubernetes, set `terminationGracePeriodSeconds: 2100` on the pod spec. + +## Actors + +### Design Patterns + +- **Do not use god actors.** Avoid putting all logic into a single actor type. See [Design Patterns](/docs/actors/design-patterns). +- **Do not use actor-per-request patterns.** Avoid creating a new actor for each request. See [Design Patterns](/docs/actors/design-patterns). + +### Lifecycle + +- **Do not rely on `onSleep` for critical cleanup.** `onSleep` is not called during crashes or forced terminations. See [Lifecycle](/docs/actors/lifecycle). + +### State + +- **Verify `c.state` does not grow unbounded.** Avoid using arrays or objects that grow over time in state. Use [SQLite](/docs/actors/sqlite) for unbounded or append-heavy data instead. +- **Verify actor data does not exceed 10 GB.** Contact [enterprise support](https://rivet.dev/sales) if you need more storage. +- **Use input parameters and `createState` for actor initialization.** See [Input Parameters](/docs/actors/input). + +### Events + +- **Use `conn.send()` instead of `c.broadcast()` for private events.** `c.broadcast()` sends to all connected clients. Use `conn.send()` to send events to a specific connection. See [Realtime](/docs/actors/events). + +### Actions + +- **Review action timeout configuration.** The default `actionTimeout` is 60 seconds. Increase it if you have long-running actions like API calls or file processing. See [Actor Configuration](/docs/general/actor-configuration). +- **Review message size limits.** The default `maxIncomingMessageSize` is 64 KiB and `maxOutgoingMessageSize` is 1 MiB. Increase if your actors send or receive large JSON payloads. See [Registry Configuration](/docs/general/registry-configuration). + +### Queues + +- **Review queue limits.** The default `maxQueueSize` is 1,000 messages and `maxQueueMessageSize` is 64 KiB. Increase if you expect burst traffic or large queue payloads. See [Actor Configuration](/docs/general/actor-configuration). +- **Ensure queue handlers are idempotent.** If processing fails before `message.complete()`, the message will be retried. See [Queues](/docs/actors/queues). + +### Workflows + +- **Verify workflows do not generate infinite steps.** Use `ctx.loop` to avoid creating unbounded step histories. See [Workflows](/docs/actors/workflows). + +## Security + +### Authentication + +- **Validate connections in `createConnState` or `onBeforeConnect`.** Do not trust client input without validation. See [Authentication](/docs/actors/authentication). + +### CORS + +- **Configure CORS for production.** Restrict allowed origins instead of allowing all. See [CORS](/docs/general/cors). + +### Tokens (Rivet Cloud) + +- **Use `pk_*` tokens for `RIVET_PUBLIC_ENDPOINT`.** Public tokens are safe to expose to clients. +- **Use `sk_*` tokens for `RIVET_ENDPOINT`.** Secret tokens should only be used server-side. +- **Do not leak your secret token.** Never expose `sk_*` tokens in client-side code, public repositories, or browser environments. See [Endpoints](/docs/general/endpoints). +- **Verify you're connecting to the correct region.** Use the nearest datacenter endpoint (e.g. `api-us-west-1.rivet.dev`) for lowest latency. + +### Access Control + +Access control is only needed if you want granular permissions for different clients. For most use cases, basic authentication in `onBeforeConnect` or `createConnState` is sufficient. + +- **Use deny-by-default rules.** Reject unknown roles in `onBeforeConnect`, action handlers, `canPublish`, and `canSubscribe`. See [Access Control](/docs/actors/access-control). +- **Authorize actions explicitly.** Check the caller's role in each action handler and throw `forbidden` for unauthorized access. +- **Gate event subscriptions and queue publishes.** Use `canSubscribe` and `canPublish` hooks to restrict which clients can subscribe to events or publish to queues. + +## Clients + +- **Dispose connections and/or client when not in use (JavaScript client).** Call `conn.dispose()` or `client.dispose()` when no longer needed to free resources. React and SwiftUI clients handle this automatically. See [Connection Lifecycle](/docs/clients/javascript#connection-lifecycle). + +_Source doc path: /docs/general/production-checklist_ diff --git a/.agents/skills/rivetkit/reference/general/registry-configuration.md b/.agents/skills/rivetkit/reference/general/registry-configuration.md new file mode 100644 index 0000000..3574c4a --- /dev/null +++ b/.agents/skills/rivetkit/reference/general/registry-configuration.md @@ -0,0 +1,32 @@ +# Registry Configuration + +> Source: `src/content/docs/general/registry-configuration.mdx` +> Canonical URL: https://rivet.dev/docs/general/registry-configuration +> Description: This page documents the configuration options available when setting up a RivetKit registry. The registry configuration is passed to the `setup()` function. + +--- +## Example Configurations + +### Basic Setup + +### Connecting to Rivet Engine + +## Starting Your App + +After configuring your registry, start it: + +See [Runtime Modes](/docs/general/runtime-modes) for details on when to use each mode. + +## Environment Variables + +Many configuration options can be set via environment variables. See [Environment Variables](/docs/general/environment-variables) for a complete reference. + +## Configuration Reference + +## Related + +- [Actor Configuration](/docs/general/actor-configuration): Configure individual actors +- [HTTP Server Setup](/docs/general/http-server): Set up HTTP routing and middleware +- [Architecture](/docs/general/architecture): Understand how RivetKit works + +_Source doc path: /docs/general/registry-configuration_ diff --git a/.agents/skills/rivetkit/reference/general/runtime-modes.md b/.agents/skills/rivetkit/reference/general/runtime-modes.md new file mode 100644 index 0000000..43ba986 --- /dev/null +++ b/.agents/skills/rivetkit/reference/general/runtime-modes.md @@ -0,0 +1,99 @@ +# Runtime Modes + +> Source: `src/content/docs/general/runtime-modes.mdx` +> Canonical URL: https://rivet.dev/docs/general/runtime-modes +> Description: RivetKit supports two runtime modes for running your actors: + +--- +- **Serverless**: Default mode. Responds to HTTP requests and scales automatically. +- **Runners**: Background processes without HTTP endpoints. Only needed for advanced scenarios. + +## Serverless + +Serverless is the default and recommended mode. Rivet sends HTTP requests to your backend to run actor logic, allowing your infrastructure to scale automatically. + +### Benefits + +- **Platform support**: Works with serverless platforms (Vercel, Cloudflare Workers, etc.) +- **Scale to zero**: No cost when idle +- **Edge deployments**: Easier to deploy to edge locations +- **Preview deployments**: Integrates with preview deployments on platforms like Vercel and Railway +- **Efficient autoscaling**: Request-based autoscaling can be faster and more efficient than CPU-based autoscaling depending on the platform + +### Example + +See [Server Setup](/docs/general/http-server/) for more configuration options. + +### Architecture + +When a client creates an actor, it sends a request to the Rivet Engine. The engine then calls `GET /api/rivet/start` on your serverless backend to run the actor. + +Serverless architecture diagram + +### Advanced + +#### Endpoints + +Rivet exposes the following endpoints: + +- `GET /api/rivet/metadata`: Validates configuration +- `GET /api/rivet/start`: Runs an actor + +You should never call these endpoints yourself, this is included purely for comprehension of how Rivet works under the hood. + +#### Timeouts + +Serverless platforms like Vercel have function timeouts. Rivet handles this automatically by migrating actors between function invocations, preserving state through `ctx.state`. Write your code as if it runs forever, Rivet handles the rest. + +Read more about [how we handle timeouts](/blog/2025-10-20-how-we-built-websocket-servers-for-vercel-functions/#timeouts-and-failover). + +#### Shutdown Sequence + +Each serverless request has a configurable lifespan (`requestLifespan`, default: 60 minutes). Set this to match your platform's function timeout (e.g. `requestLifespan: 3600` for Vercel Pro). + +When the request nears its lifespan, the engine reserves a grace period (`serverless_drain_grace_period`, default: 10 seconds) at the end to gracefully stop actors. For example, with a 3600-second lifespan, actors begin stopping at 3590 seconds. After the full lifespan elapses, the connection is forcibly closed and any remaining actors are rescheduled. + +See [Limits](/docs/actors/limits#serverless-shutdown) for configuration details. + +## Runners + +Runners run actors as long-running background processes without exposing an HTTP endpoint. + +### When to Use Runners + +- **No HTTP server**: Your app does not or cannot expose an HTTP server +- **No load balancer**: You don't have a load balancer to distribute HTTP requests across your servers +- **Custom scaling**: You have custom scaling requirements + +### Example + +The runner runs in the background, ready to run actors. + +### Architecture + +On startup, your backend calls `registry.startEnvoy()` which opens a persistent connection to the Rivet Engine. When a client creates an actor, the engine sends a command through this connection to start the actor on your backend. + +Runners architecture diagram + +### Configuration + +#### Runner Pool + +Use `RIVET_RUNNER` to assign runners to a pool. This lets you control which runners handle specific actors. + +```bash +RIVET_RUNNER=gpu-workers +``` + +See [Pool Configuration](/docs/general/pool-configuration) for how pools are scaled, drained on version upgrades, and rate-limited during actor eviction. + +## Comparison + +| Mode | Method | Use Case | +|------|--------|----------| +| Auto | `registry.start()` | Simplest setup. Starts server, serves static files, and runs actors. | +| Serverless | `registry.serve()` | Fetch handler for serverless platforms | +| Serverless | `registry.handler()` | Integrating with existing routers (Hono, Elysia, etc.) | +| Runner | `registry.startEnvoy()` | Long-running processes without HTTP endpoints | + +_Source doc path: /docs/general/runtime-modes_ diff --git a/.agents/skills/rivetkit/reference/general/wasm-vs-native-sdk.md b/.agents/skills/rivetkit/reference/general/wasm-vs-native-sdk.md new file mode 100644 index 0000000..18cdd13 --- /dev/null +++ b/.agents/skills/rivetkit/reference/general/wasm-vs-native-sdk.md @@ -0,0 +1,79 @@ +# WASM vs Native SDK + +> Source: `src/content/docs/general/wasm-vs-native-sdk.mdx` +> Canonical URL: https://rivet.dev/docs/general/wasm-vs-native-sdk +> Description: RivetKit runs your actors on a native or a WebAssembly runtime depending on your platform. + +--- +RivetKit ships two runtimes for executing actor logic. Most projects use the +native runtime automatically. Edge and serverless platforms that cannot run +native binaries use the WebAssembly runtime. + +- **Native**: Default. Runs on Node.js and Bun via native bindings. Best performance. +- **WebAssembly (wasm)**: Runs anywhere a `WebAssembly.Module` can be instantiated, including Cloudflare Workers, Supabase Edge Functions, and Deno Deploy. + +## Native runtime + +The native runtime is the default and requires no configuration. It loads +platform-specific native bindings for the best performance and full feature +support on Node.js and Bun. + +## WebAssembly runtime + +Edge platforms run on isolates (V8, Deno) that cannot load native binaries, so +RivetKit provides a WebAssembly build of its core runtime in the +`@rivetkit/rivetkit-wasm` package. You select it with `runtime: "wasm"` and pass +the wasm bindings and binary through the `wasm` option. + +### Recommended: use a platform package + +For supported platforms, use the dedicated package instead of wiring the wasm +runtime by hand. They install the wasm runtime, load the binary, and (on +Cloudflare) provide the outbound WebSocket the engine tunnel needs. + +- **Cloudflare Workers**: [`@rivetkit/cloudflare-workers`](/docs/actors/quickstart/cloudflare) +- **Supabase Edge Functions**: [`@rivetkit/supabase`](/docs/actors/quickstart/supabase) + +```typescript @nocheck +// Cloudflare Workers +import { actor } from "rivetkit"; +import { createHandler } from "@rivetkit/cloudflare-workers"; + +const counter = actor({ state: { count: 0 }, actions: {} }); + +export default createHandler({ use: { counter } }); +``` + +### Manual configuration + +For platforms without a dedicated package, configure the wasm runtime directly. +Pass the bindings from `@rivetkit/rivetkit-wasm` and the wasm binary as +`initInput`. `initInput` accepts a `Uint8Array`, `URL`, `Response`, or a +`WebAssembly.Module`. + +```typescript @nocheck +import { actor, setup } from "rivetkit"; +import * as wasmBindings from "@rivetkit/rivetkit-wasm"; +import wasmModule from "@rivetkit/rivetkit-wasm/rivetkit_wasm_bg.wasm"; + +const counter = actor({ state: { count: 0 }, actions: {} }); + +const registry = setup({ + runtime: "wasm", + wasm: { bindings: wasmBindings, initInput: wasmModule }, + use: { counter }, +}); +``` + +On platforms without an outbound `new WebSocket(url)` constructor (such as +Cloudflare Workers), you must also install a fetch-based `globalThis.WebSocket` +shim so the actor can open its tunnel to the engine. The platform packages handle +this for you, which is why they are recommended. + +## Related + +- [Runtime Modes](/docs/general/runtime-modes) +- [Cloudflare Workers Quickstart](/docs/actors/quickstart/cloudflare) +- [Supabase Functions Quickstart](/docs/actors/quickstart/supabase) + +_Source doc path: /docs/general/wasm-vs-native-sdk_ diff --git a/.agents/skills/rivetkit/reference/self-hosting/configuration.md b/.agents/skills/rivetkit/reference/self-hosting/configuration.md new file mode 100644 index 0000000..a71d16e --- /dev/null +++ b/.agents/skills/rivetkit/reference/self-hosting/configuration.md @@ -0,0 +1,74 @@ +# Configuration + +> Source: `src/content/docs/self-hosting/configuration.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/configuration +> Description: Rivet Engine can be configured through environment variables or configuration files. + +--- +The full JSON Schema for the configuration is available at [/docs/engine-config-schema.json](/docs/engine-config-schema.json). + +## Configuration Sources + +Rivet supports JSON, JSON5, JSONC, YAML, YML, and environment variable configurations. + +**Environment Variables** + +Use the `RIVET__` prefix with `__` as separator to configure properties in the config. For example: set the `RIVET__database__postgres__url` environment variable for `database.postgres.url`. + +**Configuration Paths** + +Configuration files are automatically discovered in platform-specific directories: + +- Linux: `/etc/rivet/config.json` +- macOS: `/Library/Application Support/rivet/config.json` +- Windows: `C:\ProgramData\rivet\config.json` + +**Multiple Files** + +Multiple configuration files in the same directory are loaded and merged together. For example: `/etc/rivet/config.json` and `/etc/rivet/database.json` will be merged together. + +**Override Configuration Path** + +You can override the default configuration path using the `--config` flag: + +```bash +# Load from a specific file +rivet-engine --config /path/to/config.json + +# Load from a directory +rivet-engine --config /etc/rivet + +# Load multiple paths (merged in order) +rivet-engine --config /etc/rivet/base.json --config /etc/rivet/override.json +``` + +## Configuration Reference + +### Pegboard Envoy Load Balancing + +`pegboard.envoy_load_balancer` supports the `hash` strategy for hash-ring-based envoy selection: + +```json +{ + "pegboard": { + "envoy_load_balancer": { + "hash": { + "virtual_nodes": 8, + "samples": 2, + "max_scan": 16, + "use_snapshot_read": true + } + } + } +} +``` + +Use `samples: 1` for a uniform random pick that skips slot reads. Use `samples >= 2` for power-of-K choices over envoy slot counts. Treat `virtual_nodes` as an operational invariant once envoys have registered. + +## Related + +- RivetKit actor runtime persistence lives in SQLite. Existing actor KV data is imported into SQLite the first time an actor wakes on the migrated runtime, then the original KV data is left frozen for downgrade safety. +- [PostgreSQL](/docs/self-hosting/postgres): Configure the experimental PostgreSQL backend +- [File System](/docs/self-hosting/filesystem): Configure file system storage for development + +_Source doc path: /docs/self-hosting/configuration_ diff --git a/.agents/skills/rivetkit/reference/self-hosting/docker-compose.md b/.agents/skills/rivetkit/reference/self-hosting/docker-compose.md new file mode 100644 index 0000000..8f2cea1 --- /dev/null +++ b/.agents/skills/rivetkit/reference/self-hosting/docker-compose.md @@ -0,0 +1,188 @@ +# Docker Compose + +> Source: `src/content/docs/self-hosting/docker-compose.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/docker-compose +> Description: Deploy Rivet Engine with docker-compose for multi-container setups. + +--- +## Quick Start + +### Create docker-compose.yaml + +Create a `docker-compose.yaml` in your project root: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - rivet-data:/data + environment: + RIVET__FILE_SYSTEM__PATH: "/data" + restart: unless-stopped + +volumes: + rivet-data: +``` + +### Start the engine + +```bash +docker-compose up -d +``` + +## Connecting Your Project + +Once the engine is running, add your app as a service in the same Compose file. + +### Create your server + +Follow the [quickstart](/docs/actors/quickstart/backend) to create a working server with actors. + +### Create a Dockerfile + +Create a `Dockerfile` in your project root: + +```dockerfile @nocheck +FROM node:22-slim +WORKDIR /app +COPY package.json pnpm-lock.yaml ./ +RUN corepack enable && pnpm install --frozen-lockfile +COPY . . +RUN pnpm build +CMD ["node", "dist/index.js"] +``` + +### Add your app to docker-compose.yaml + +Update your `docker-compose.yaml` to include your app alongside the engine: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - rivet-data:/data + environment: + RIVET__FILE_SYSTEM__PATH: "/data" + restart: unless-stopped + + my-app: + build: . + environment: + RIVET_ENDPOINT: "http://default:admin@rivet-engine:6420" + depends_on: + - rivet-engine + restart: unless-stopped + +volumes: + rivet-data: +``` + +`RIVET_ENDPOINT` tells your app to connect to the engine as a runner instead of running standalone. The URL uses the format `http://namespace:token@host:port`. Inside the Docker network, your app reaches the engine at `rivet-engine:6420`. See [Endpoints](/docs/general/endpoints) for all options. + +### Start the services + +```bash +docker-compose up -d +``` + +### Register your runner with the engine + +### Dashboard + +1. Open the Rivet Engine dashboard at `http://localhost:6420`. +2. Enter your admin token when prompted. +3. In the namespace sidebar, click **Settings**. +4. Click **Add Provider**, then choose **Custom**. +5. Click **Next** (these settings can be changed later). +6. Click **Next** (you can safely skip the env ar step for Docker Compose). +5. Go to **Confirm Connection**, enter your app endpoint (`http://my-app:6420/api/rivet`), then click **Add**. + +### CLI (curl) + +Register your runner programmatically via the engine API: + +```bash @nocheck +curl -X PUT "http://localhost:6420/runner-configs/default?namespace=default" \ + -H "Content-Type: application/json" \ + -d '{ + "datacenters": { + "default": { + "normal": {} + } + } + }' +``` + +## Configuration + +### Config File + +Mount a JSON configuration file in your `docker-compose.yaml`: + +```yaml +services: + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + volumes: + - ./rivet-config.json:/etc/rivet/config.json:ro + - rivet-data:/data + restart: unless-stopped + +volumes: + rivet-data: +``` + +Create `rivet-config.json` in the same directory as your `docker-compose.yaml`. See the [Configuration](/docs/self-hosting/configuration) docs for all available options and the full [JSON Schema](/docs/engine-config-schema.json). + +```json +{ + "postgres": { + "url": "postgresql://rivet:password@postgres:5432/rivet" + } +} +``` + +### Postgres Setup + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +```yaml +services: + postgres: + image: postgres:15 + environment: + POSTGRES_DB: rivet + POSTGRES_USER: rivet + POSTGRES_PASSWORD: rivet_password + volumes: + - postgres-data:/var/lib/postgresql/data + restart: unless-stopped + + rivet-engine: + image: rivetdev/engine:latest + ports: + - "6420:6420" + environment: + RIVET__POSTGRES__URL: postgresql://rivet:rivet_password@postgres:5432/rivet + depends_on: + - postgres + restart: unless-stopped + +volumes: + postgres-data: +``` + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/docker-compose_ diff --git a/.agents/skills/rivetkit/reference/self-hosting/docker-container.md b/.agents/skills/rivetkit/reference/self-hosting/docker-container.md new file mode 100644 index 0000000..e6983ae --- /dev/null +++ b/.agents/skills/rivetkit/reference/self-hosting/docker-container.md @@ -0,0 +1,150 @@ +# Docker Container + +> Source: `src/content/docs/self-hosting/docker-container.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/docker-container +> Description: Run Rivet Engine in a single Docker container. + +--- +## Quick Start + +### Start the engine + +```bash +docker run -d \ + --name rivet-engine \ + -p 6420:6420 \ + -v rivet-data:/data \ + -e RIVET__FILE_SYSTEM__PATH="/data" \ + rivetdev/engine:latest +``` + +### Verify the engine is running + +```bash +curl http://localhost:6420/health +``` + +## Connecting Your Project + +Once the engine is running, connect your app to it. + +### Create your server + +Follow the [quickstart](/docs/actors/quickstart/backend) to create a working server with actors. + +### Start your app with RIVET_ENDPOINT + +Set `RIVET_ENDPOINT` to tell your app to connect to the engine as a runner instead of running standalone: + +```bash @nocheck +RIVET_ENDPOINT="http://default:admin@host.docker.internal:6420" npm start +``` + +If running your app outside of Docker, use `localhost` instead of `host.docker.internal`: + +```bash @nocheck +RIVET_ENDPOINT="http://default:admin@localhost:6420" npm start +``` + +See [Endpoints](/docs/general/endpoints) for all options. + +### Register your runner with the engine + +### Dashboard + +1. Open the Rivet Engine dashboard at `http://localhost:6420`. +2. Enter your admin token when prompted. +3. In the namespace sidebar, click **Settings**. +4. Click **Add Provider**, then choose **Custom**. +5. Click **Next**. +6. Go to **Confirm Connection**, enter your app endpoint, then click **Add**. + +### CLI (curl) + +Register your runner programmatically via the engine API: + +```bash @nocheck +curl -X PUT "http://localhost:6420/runner-configs/default?namespace=default" \ + -H "Content-Type: application/json" \ + -d '{ + "datacenters": { + "default": { + "normal": {} + } + } + }' +``` + +## Configuration + +### Environment Variables + +Configure Rivet using environment variables: + +```bash +docker run -d \ + --name rivet-engine \ + -p 6420:6420 \ + -v rivet-data:/data \ + -e RIVET__FILE_SYSTEM__PATH="/data" \ + -e RIVET__POSTGRES__URL="postgresql://postgres:password@localhost:5432/db" \ + rivetdev/engine:latest +``` + +### Config File + +Mount a JSON configuration file: + +```bash +docker run -d \ + --name rivet-engine \ + -p 6420:6420 \ + -v rivet-data:/data \ + -v $(pwd)/rivet-config.json:/etc/rivet/config.json:ro \ + rivetdev/engine:latest +``` + +Create `rivet-config.json` in your working directory. See the [Configuration](/docs/self-hosting/configuration) docs for all available options and the full [JSON Schema](/docs/engine-config-schema.json). + +```json +{ + "postgres": { + "url": "postgresql://postgres:password@localhost:5432/db" + } +} +``` + +### Postgres Setup + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +```bash +# Create network +docker network create rivet-net + +# Run PostgreSQL +docker run -d \ + --name postgres \ + --network rivet-net \ + -e POSTGRES_DB=rivet \ + -e POSTGRES_USER=rivet \ + -e POSTGRES_PASSWORD=rivet_password \ + -v postgres-data:/var/lib/postgresql/data \ + postgres:15 + +# Run Rivet Engine +docker run -d \ + --name rivet-engine \ + --network rivet-net \ + -p 6420:6420 \ + -e RIVET__POSTGRES__URL="postgresql://rivet:rivet_password@postgres:5432/rivet" \ + rivetdev/engine +``` + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- Use [Docker Compose](/docs/self-hosting/docker-compose) for multi-container setups +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/docker-container_ diff --git a/.agents/skills/rivetkit/reference/self-hosting/filesystem.md b/.agents/skills/rivetkit/reference/self-hosting/filesystem.md new file mode 100644 index 0000000..30f7bdb --- /dev/null +++ b/.agents/skills/rivetkit/reference/self-hosting/filesystem.md @@ -0,0 +1,47 @@ +# File System + +> Source: `src/content/docs/self-hosting/filesystem.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/filesystem +> Description: The file system backend stores all data on the local disk. This is suitable for single-node deployments, development, and testing. + +--- +For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based); for multi-node deployments, PostgreSQL is the recommended backend today but remains experimental as we evaluate the best fit for scalability and performance, and Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB. + +## Configuration + +```json Configuration-file +{ + "database": { + "file_system": { + "path": "/var/lib/rivet/data" + } + } +} +``` + +```bash Environment-variables +RIVET__database__file_system__path="/var/lib/rivet/data" +``` + +## Default Paths + +If no path is specified, Rivet uses platform-specific default locations: + +- Linux: `~/.local/share/rivet-engine/db` +- macOS: `~/Library/Application Support/rivet-engine/db` +- Windows: `%APPDATA%\rivet-engine\db` + +When running in a container or as a service, the path defaults to `./data/db` relative to the working directory. + +## When to Use File System + +The file system backend is ideal for: + +- Local development +- Single-node deployments +- Testing and prototyping +- Air-gapped environments without database infrastructure + +If you need a production-ready Rivet deployment today, use this backend for smaller single-node setups; for multi-node deployments, PostgreSQL is the recommended backend today though still experimental, and Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +_Source doc path: /docs/self-hosting/filesystem_ diff --git a/.agents/skills/rivetkit/reference/self-hosting/foundationdb.md b/.agents/skills/rivetkit/reference/self-hosting/foundationdb.md new file mode 100644 index 0000000..b8331bb --- /dev/null +++ b/.agents/skills/rivetkit/reference/self-hosting/foundationdb.md @@ -0,0 +1,35 @@ +# FoundationDB (Enterprise) + +> Source: `src/content/docs/self-hosting/foundationdb.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/foundationdb +> Description: FoundationDB is the recommended storage backend for scalable production Rivet deployments. + +--- +FoundationDB requires an enterprise license. Contact [enterprise support](https://rivet.dev/sales) for setup guidance and access. + +## Overview + +FoundationDB is the recommended storage backend for scalable, production-ready Rivet deployments. It is a distributed, ordered key-value store originally built by Apple. + +FoundationDB powers some of the largest infrastructure in the world: + +- **Apple**: iCloud and other Apple services +- **Snowflake**: Cloud data platform metadata layer +- **Datadog**: Observability and monitoring platform +- **Tigris Data**: Globally distributed object storage + +Its strict serializability guarantees, fault tolerance, and ability to scale linearly across nodes make it the ideal backend for Rivet's actor state and orchestration layer. + +## Why FoundationDB + +| | RocksDB (File System) | PostgreSQL | FoundationDB | +|---|---|---|---| +| **Scalability** | Single node | Primary/replica failover | Linear horizontal scaling | +| **Fault tolerance** | None | Primary/replica failover | Automatic recovery with no data loss | +| **Production readiness** | Development and small deployments | Experimental for multi-node | Battle-tested at global scale | + +## Getting Started + +FoundationDB configuration and cluster setup are handled as part of enterprise onboarding. Contact [enterprise support](https://rivet.dev/sales) to get started. + +_Source doc path: /docs/self-hosting/foundationdb_ diff --git a/.agents/skills/rivetkit/reference/self-hosting/install.md b/.agents/skills/rivetkit/reference/self-hosting/install.md new file mode 100644 index 0000000..344be8e --- /dev/null +++ b/.agents/skills/rivetkit/reference/self-hosting/install.md @@ -0,0 +1,32 @@ +# Installing Rivet Engine + +> Source: `src/content/docs/self-hosting/install.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/install +> Description: Install Rivet Engine using Docker, binaries, or a source build. + +--- +For more options: + +- [Docker Container](/docs/self-hosting/docker-container) for persistent storage, configuration, and production setups +- [Docker Compose](/docs/self-hosting/docker-compose) for multi-container deployments with PostgreSQL + +## Docker + +```bash +docker run -p 6420:6420 rivetdev/engine +``` + +## Prebuilt Binaries + + Prebuilt binaries coming soon + +## Build From Source + +```bash +git clone https://github.com/rivet-dev/rivet.git +cd rivet +cargo build --release -p rivet-engine +./target/release/rivet-engine +``` + +_Source doc path: /docs/self-hosting/install_ diff --git a/.agents/skills/rivetkit/reference/self-hosting/kubernetes.md b/.agents/skills/rivetkit/reference/self-hosting/kubernetes.md new file mode 100644 index 0000000..a2c619c --- /dev/null +++ b/.agents/skills/rivetkit/reference/self-hosting/kubernetes.md @@ -0,0 +1,236 @@ +# Kubernetes + +> Source: `src/content/docs/self-hosting/kubernetes.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/kubernetes +> Description: Deploy production-ready Rivet Engine to Kubernetes with PostgreSQL storage. + +--- +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Prerequisites + +- Kubernetes cluster +- `kubectl` configured +- [Metrics server](https://github.com/kubernetes-sigs/metrics-server) (required for HPA) — included by default in most distributions (k3d, GKE, EKS, AKS) + +## Deploy Rivet Engine + + +### Download Manifests + + Download the `self-host/k8s/engine` directory from the Rivet repository: + + ```bash + npx giget@latest gh:rivet-dev/rivet/self-host/k8s/engine rivet-k8s + cd rivet-k8s + ``` + + + +### Configure Engine + + In `02-engine-configmap.yaml`, set `public_url` to your engine's external URL. + + + +### Configure PostgreSQL + + In `11-postgres-secret.yaml`, update the PostgreSQL password. See [Using a Managed PostgreSQL Service](#using-a-managed-postgresql-service) for external databases. + + + +### Configure Admin Token + + Generate a secure admin token and save it somewhere safe: + + ```bash + openssl rand -hex 32 + ``` + + Create the namespace and store the token as a Kubernetes secret: + + ```bash + kubectl create namespace rivet-engine + kubectl -n rivet-engine create secret generic rivet-secrets --from-literal=admin-token=YOUR_TOKEN_HERE + ``` + + + +### Deploy + + ```bash + # Apply all manifests + kubectl apply -f . + + # Wait for all pods to be ready + kubectl -n rivet-engine wait --for=condition=ready pod -l app=nats --timeout=300s + kubectl -n rivet-engine wait --for=condition=ready pod -l app=postgres --timeout=300s + kubectl -n rivet-engine wait --for=condition=ready pod -l app=rivet-engine --timeout=300s + + # Verify all pods are running + kubectl -n rivet-engine get pods + ``` + + + +### Access the Engine + + Visit `/ui` on your `public_url` to access the dashboard. + + +## Connecting Your Project + +### Create your server + +Follow the [quickstart](/docs/actors/quickstart/backend) to create a working server with actors. + +### Create Kubernetes manifests + +Create these manifest files for your app: + +```yaml deployment.yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: rivetkit-app + namespace: your-namespace +spec: + replicas: 1 + selector: + matchLabels: + app: rivetkit-app + template: + metadata: + labels: + app: rivetkit-app + spec: + # Allow enough time for actors to gracefully stop on SIGTERM. + # The runner waits up to 30m for actors to finish. + # Add buffer for runner shutdown overhead after actors stop. + # See: /docs/actors/versions#graceful-shutdown-sigterm + terminationGracePeriodSeconds: 2100 + containers: + - name: rivetkit-app + image: registry.example.com/your-team/rivetkit-app:latest + envFrom: + - secretRef: + name: rivetkit-secrets +``` + +```yaml service.yaml +apiVersion: v1 +kind: Service +metadata: + name: rivetkit-app + namespace: your-namespace +spec: + selector: + app: rivetkit-app + ports: + - name: http + port: 8080 + targetPort: 8080 +``` + +### Configure the endpoint + +Create `rivetkit-secrets.yaml` with `RIVET_ENDPOINT` pointing to the engine. This tells your app to connect as a runner instead of running standalone. See [Endpoints](/docs/general/endpoints) for all options. + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: rivetkit-secrets + namespace: your-namespace +type: Opaque +stringData: + RIVET_ENDPOINT: http://my-app:your-admin-token@your-engine.example.com +``` + +### Deploy your app + +```bash +kubectl apply -f rivetkit-secrets.yaml +kubectl apply -f deployment.yaml +kubectl apply -f service.yaml +``` + +### Register your runner with the engine + +### Dashboard + +1. Open the Rivet Engine dashboard in your browser. +2. Enter your admin token when prompted. +3. In the namespace sidebar, click **Settings**. +4. Click **Add Provider**, then choose **Custom**. +5. Click **Next**. +6. Go to **Confirm Connection**, enter your app endpoint (e.g. `http://rivetkit-app.your-namespace:8080/api/rivet`), then click **Add**. + +### CLI (curl) + +Register your runner programmatically via the engine API: + +```bash @nocheck +curl -X PUT "https://your-engine.example.com/runner-configs/default?namespace=default" \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer your-admin-token" \ + -d '{ + "datacenters": { + "default": { + "normal": {} + } + } + }' +``` + +## Advanced + +### Using a Managed PostgreSQL Service + +If you prefer to use a managed PostgreSQL service (e.g. Amazon RDS, Cloud SQL, Azure Database) instead of the bundled Postgres deployment: + +- Update the `postgres.url` connection string in `02-engine-configmap.yaml` to point to your managed instance +- Delete the bundled PostgreSQL manifests: + - `10-postgres-configmap.yaml` + - `11-postgres-secret.yaml` + - `12-postgres-statefulset.yaml` + - `13-postgres-service.yaml` + +### Applying Configuration Updates + +When making subsequent changes to `02-engine-configmap.yaml`, restart the engine pods to pick up the new configuration: + +```bash +kubectl apply -f 02-engine-configmap.yaml +kubectl -n rivet-engine rollout restart deployment/rivet-engine +``` + +### Ingress and Load Balancer Timeouts + +Rivet uses long-lived WebSocket connections for both client traffic (browsers, SDKs) and envoy traffic (actor hosts connecting back to the engine). Default Ingress and cloud load balancer idle timeouts (typically 30 to 60 seconds) drop these connections and cause reconnect storms. + +Raise the idle / read / send timeout on every Ingress and load balancer in front of the engine to at least 1 hour (`3600` seconds). Examples: + +- **NGINX Ingress** (annotations on the Ingress): + + ```yaml + nginx.ingress.kubernetes.io/proxy-read-timeout: "3600" + nginx.ingress.kubernetes.io/proxy-send-timeout: "3600" + ``` + +- **AWS Load Balancer Controller (ALB)**: + + ```yaml + alb.ingress.kubernetes.io/load-balancer-attributes: idle_timeout.timeout_seconds=3600 + ``` + +- **GCE Ingress (GKE)**: set `timeoutSec: 3600` on the `BackendConfig` referenced by the Service. + +The same guidance applies to the load balancer fronting your RivetKit app, since envoys connect to it over WebSocket. + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all engine config options + +_Source doc path: /docs/self-hosting/kubernetes_ diff --git a/.agents/skills/rivetkit/reference/self-hosting/multi-region.md b/.agents/skills/rivetkit/reference/self-hosting/multi-region.md new file mode 100644 index 0000000..2ecca85 --- /dev/null +++ b/.agents/skills/rivetkit/reference/self-hosting/multi-region.md @@ -0,0 +1,10 @@ +# Multi-Region + +> Source: `src/content/docs/self-hosting/multi-region.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/multi-region +> Description: Rivet Engine supports scaling transparently across multiple regions. + +--- +Documentation coming soon + +_Source doc path: /docs/self-hosting/multi-region_ diff --git a/.agents/skills/rivetkit/reference/self-hosting/postgres.md b/.agents/skills/rivetkit/reference/self-hosting/postgres.md new file mode 100644 index 0000000..e935246 --- /dev/null +++ b/.agents/skills/rivetkit/reference/self-hosting/postgres.md @@ -0,0 +1,192 @@ +# PostgreSQL + +> Source: `src/content/docs/self-hosting/postgres.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/postgres +> Description: Configure PostgreSQL for self-hosted Rivet deployments. + +--- +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Basic Configuration + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://user:password@host:5432/database" + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://user:password@host:5432/database" +``` + +## Managed Postgres Compatibility + +Some hosted PostgreSQL platforms require additional configuration due to platform-specific restrictions. + +### PlanetScale + +Use direct connection (not connection pooler). + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://pscale_api_.:@.pg.psdb.cloud:5432/postgres?sslmode=require", + "unstable_disable_lock_customization": true + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://pscale_api_.:@.pg.psdb.cloud:5432/postgres?sslmode=require" +RIVET__database__postgres__unstable_disable_lock_customization=true +``` + +### Supabase + +Use direct connection on port `5432` (not connection pooler). + +#### Without SSL + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=disable", + "unstable_disable_lock_customization": true + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=disable" +RIVET__database__postgres__unstable_disable_lock_customization=true +``` + +#### With SSL + +Download the root certificate from your Supabase dashboard and specify its path. See [Supabase SSL Enforcement](https://supabase.com/docs/guides/platform/ssl-enforcement) for details. + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=require", + "unstable_disable_lock_customization": true, + "ssl": { + "root_cert_path": "/path/to/supabase-ca.crt" + } + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://postgres:@db..supabase.co:5432/postgres?sslmode=require" +RIVET__database__postgres__unstable_disable_lock_customization=true +RIVET__database__postgres__ssl__root_cert_path="/path/to/supabase-ca.crt" +``` + +## SSL/TLS Support + +To enable SSL for Postgres, add `sslmode=require` to your PostgreSQL connection URL: + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://user:password@host.example.com:5432/database?sslmode=require" + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://user:password@host.example.com:5432/database?sslmode=require" +``` + +The `sslmode` parameter controls TLS usage: + +- `disable`: Do not use TLS +- `prefer`: Use TLS if available, otherwise connect without TLS (default) +- `require`: Require TLS connection (fails if TLS is not available) + +To verify the server certificate against a CA or verify the hostname, use custom SSL certificates (see below). + +### Custom SSL Certificates + +For databases using custom certificate authorities (e.g., Supabase) or requiring client certificate authentication, you can specify certificate paths in the configuration: + +```json Configuration-file +{ + "database": { + "postgres": { + "url": "postgresql://user:password@host:5432/database?sslmode=require", + "ssl": { + "root_cert_path": "/path/to/root-ca.crt", + "client_cert_path": "/path/to/client.crt", + "client_key_path": "/path/to/client.key" + } + } + } +} +``` + +```bash Environment-variables +RIVET__database__postgres__url="postgresql://user:password@host:5432/database?sslmode=require" +RIVET__database__postgres__ssl__root_cert_path="/path/to/root-ca.crt" +RIVET__database__postgres__ssl__client_cert_path="/path/to/client.crt" +RIVET__database__postgres__ssl__client_key_path="/path/to/client.key" +``` + +| Parameter | Description | PostgreSQL Equivalent | +|-----------|-------------|----------------------| +| `root_cert_path` | Path to the root certificate file for verifying the server's certificate | `sslrootcert` | +| `client_cert_path` | Path to the client certificate file for client certificate authentication | `sslcert` | +| `client_key_path` | Path to the client private key file for client certificate authentication | `sslkey` | + +All SSL paths are optional. If not specified, Rivet uses the default system root certificates from Mozilla's root certificate store. + +## Do Not Use Connection Poolers + +Rivet requires direct PostgreSQL connections for session-level features and does not support connection poolers. + +Do not use: + +- PgBouncer +- Supavisor +- AWS RDS Proxy + +## Troubleshooting + +### Permission Denied Errors + +If you see errors like: + +``` +ERROR: permission denied to set parameter "deadlock_timeout" +ERROR: current transaction is aborted, commands ignored until end of transaction block +``` + +Add `unstable_disable_lock_customization: true` to your configuration: + +```json +{ + "database": { + "postgres": { + "url": "postgresql://...", + "unstable_disable_lock_customization": true + } + } +} +``` + +This disables Rivet's attempt to set `lock_timeout = 0` and `deadlock_timeout = 10ms`. Since `lock_timeout` defaults to `0` in PostgreSQL, skipping these settings is safe. Deadlock detection will use the default `1s` timeout instead of `10ms`. + +_Source doc path: /docs/self-hosting/postgres_ diff --git a/.agents/skills/rivetkit/reference/self-hosting/production-checklist.md b/.agents/skills/rivetkit/reference/self-hosting/production-checklist.md new file mode 100644 index 0000000..3cefa5a --- /dev/null +++ b/.agents/skills/rivetkit/reference/self-hosting/production-checklist.md @@ -0,0 +1,53 @@ +# Production Checklist + +> Source: `src/content/docs/self-hosting/production-checklist.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/production-checklist +> Description: Checklist for deploying a self-hosted Rivet Engine to production. + +--- +We recommend passing this page to your coding agent to verify your configuration before deploying. + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +Also review the [general production checklist](/docs/general/production-checklist). + +## Security + +- **Validate that you have an admin token configured.** Generate a strong, random token for engine authentication. See [Configuration](/docs/self-hosting/configuration). +- **Verify your admin token is not exposed publicly.** Do not include the admin token in `RIVET_PUBLIC_ENDPOINT` or anywhere accessible to clients. See [Endpoints](/docs/general/endpoints#public-endpoint). +- **Configure TLS termination.** Ensure connections to the engine are encrypted via a reverse proxy or load balancer. + +## Resources + +- **Set container resource limits.** Recommended at least 1 CPU and 2 GB of RAM per Rivet Engine instance. +- **Configure health checks.** Set up liveness and readiness probes on port `6421` at `/health`. Recommended timeout of 5 seconds. + +## Scaling + +- **Configure autoscaling for the Rivet Engine.** Set target CPU utilization to 70% and memory to 80% to ensure headroom for traffic spikes. In Kubernetes, this is configured via a Horizontal Pod Autoscaler (HPA). +- **Use 2+ engine nodes for redundancy.** Running a single engine node is a single point of failure. Deploy at least two engine instances behind a load balancer. +- **RocksDB only supports a single node.** Do not run multiple RocksDB nodes. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). For multi-node deployments, PostgreSQL is the recommended backend today, though it remains experimental as we evaluate the best fit for scalability and performance. +- **Validate the rate limit on your serverless actor host.** Actor start requests are sent from your engine instances, so they all originate from a small set of IPs. Per-IP rate limits on the actor host will throttle the engine before they would throttle end-user traffic. Size the limit to your peak actor create and wake rate, and configure platform max concurrency (e.g. on GCP Cloud Run) to match your expected concurrent actor count. + +## PostgreSQL + +- **PostgreSQL is recommended for multi-node deployments, but remains experimental.** Validate the deployment carefully before rollout. +- **Configure automated backups.** Set up regular backups for your PostgreSQL database to prevent data loss. +- **Configure failover.** Set up a standby replica with automatic failover to ensure high availability. +- **Use FoundationDB for the most scalable production-ready deployments.** FoundationDB provides the best performance, scalability, and uptime for Rivet. Contact [enterprise support](https://rivet.dev/sales) for FoundationDB guidance. + +## NATS + +- **Use NATS for pub/sub (recommended).** By default, Rivet uses PostgreSQL `LISTEN`/`NOTIFY` for pub/sub which has limited throughput. NATS significantly improves performance for high-traffic deployments. This is not needed if using RocksDB. See [Configuration](/docs/self-hosting/configuration). +- **Deploy 2+ NATS replicas.** Run at least two NATS replicas for high availability. + +## Monitoring + +- **Configure OpenTelemetry.** The Rivet Engine supports exporting traces and metrics via OpenTelemetry. Set `RIVET_OTEL_ENABLED=1` and `RIVET_OTEL_GRPC_ENDPOINT` to your collector endpoint (defaults to `http://localhost:4317`). Adjust `RIVET_OTEL_SAMPLER_RATIO` to control trace sampling (defaults to `0.001`). See [Configuration](/docs/self-hosting/configuration). +- **Set up alerts for critical metrics.** Monitor engine CPU, memory, request latency, and error rates. Configure alerts to notify your team before issues become outages. + +## Enterprise + +- **Contact [enterprise support](https://rivet.dev/sales) for production-ready deployments.** We can help with architecture review, scaling guidance, and FoundationDB support. + +_Source doc path: /docs/self-hosting/production-checklist_ diff --git a/.agents/skills/rivetkit/reference/self-hosting/railway.md b/.agents/skills/rivetkit/reference/self-hosting/railway.md new file mode 100644 index 0000000..c4bb922 --- /dev/null +++ b/.agents/skills/rivetkit/reference/self-hosting/railway.md @@ -0,0 +1,99 @@ +# Railway Deployment + +> Source: `src/content/docs/self-hosting/railway.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/railway +> Description: Railway provides a simple platform for deploying Rivet Engine with automatic scaling and managed infrastructure. + +--- +## Video Tutorial + +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Quick Deploy + +Choose the template that best fits your needs: + +| **Rivet Template** | **Rivet Starter** | +|-------------------|-------------------| +| [![Deploy on Railway](https://railway.com/button.svg)](https://railway.com/deploy/rivet?referralCode=RC7bza&utm_medium=integration&utm_source=template&utm_campaign=generic) | [![Deploy Rivet Starter](https://railway.com/button.svg)](https://railway.com/deploy/rivet-starter) | +| **Blank template** to start fresh | **Complete example** with chat app | +| - Rivet Engine | - Pre-configured Rivet Engine | +| - PostgreSQL database | - Example chat application with Actors | +| - Basic configuration | - PostgreSQL database | +| - Manual setup required | - Rivet Inspector for debugging | +| | - Ready to run immediately | + +You can also use the [Rivet Railway template](https://github.com/rivet-dev/template-railway) as a starting point for your application. + +After deploying either template, you can find the `RIVET__AUTH__ADMIN_TOKEN` under the **Variables** tab in the Railway dashboard. This token is required to access the Rivet Inspector. + +## Manual Deployment + +### Prerequisites + +1. [Railway account](https://railway.app) +2. [Railway CLI](https://docs.railway.app/develop/cli) (optional) + +### Step 1: Create New Project + +```bash +# Using Railway CLI +railway init + +# Or create via dashboard +# https://railway.app/new +``` + +### Step 2: Add Services + +#### Deploy PostgreSQL Database + +1. Click "New Service" → "Database" → "PostgreSQL" +2. Railway automatically provisions and configures PostgreSQL +3. Note the connection string from the service variables + +#### Deploy Rivet Engine + +1. Click "New Service" → "Docker Image" +2. Set image: `rivetdev/engine:latest` +3. Configure environment variables: + - `RIVET__POSTGRES__URL=${{Postgres.DATABASE_URL}}` +4. Configure graceful shutdown (see [Graceful Shutdown](#graceful-shutdown) below) + +### Step 3: Deploy Your Application + +Follow the [Railway Quick Start guide](https://docs.railway.com/quick-start) to deploy your repository: + +1. Connect your GitHub account to Railway +2. Select your repository containing your Rivet application +3. Railway will automatically detect and deploy your application +4. Configure environment variables for your application: + - `RIVET_ENDPOINT=${{Rivet.RAILWAY_PRIVATE_DOMAIN}}` - Points to the Rivet Engine service's private domain + +## WebSocket Timeouts + +Rivet uses long-lived WebSocket connections for both client traffic (browsers, SDKs) and envoy traffic (actor hosts connecting back to the engine). Railway's HTTP proxy supports WebSockets, but you must make sure no app-side timeout cuts them off. + +If you front the engine with your own reverse proxy (NGINX, Caddy, etc.) inside the Railway service, raise its idle / read timeout to at least 1 hour (`3600` seconds). The same guidance applies to the Railway service hosting your RivetKit app, since envoys connect to it over WebSocket. + +## Graceful Shutdown + +By default, Railway kills the old deploy 0 seconds after sending `SIGTERM` (see [Railway's docs](https://docs.railway.com/deployments/reference#singleton-deploys)), so in-flight requests are dropped and state flushes can be interrupted on every deploy. Rivet ships with a `SIGTERM` handler that drains cleanly, but it only gets to run if Railway is configured to give it time. + +Configure the following under **Settings → Deploy** on your service: + +- **Draining seconds** — the grace window between `SIGTERM` and `SIGKILL`. This is how long Rivet has to finish in-flight work and flush state. See [Railway's deployment teardown docs](https://docs.railway.com/deployments/deployment-teardown). + +Set draining seconds in the dashboard, via `drainingSeconds` in config-as-code, or via the `RAILWAY_DEPLOYMENT_DRAINING_SECONDS` service variable. A reasonable value is **60 seconds**. + +If your start command is a wrapper process (for example `npm start`, `yarn start`, `pnpm start`, or a shell script), the wrapper becomes PID 1 and swallows the signal — your app never drains and Railway force-kills it at the end of the window. + +- Invoke your binary directly as the start command (for example `node dist/index.js`, not `npm start`). +- Or run `dumb-init` / `tini` as PID 1 in your Dockerfile so signals forward to your process. + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/railway_ diff --git a/.agents/skills/rivetkit/reference/self-hosting/render.md b/.agents/skills/rivetkit/reference/self-hosting/render.md new file mode 100644 index 0000000..0bc6d6c --- /dev/null +++ b/.agents/skills/rivetkit/reference/self-hosting/render.md @@ -0,0 +1,131 @@ +# Render Deployment + +> Source: `src/content/docs/self-hosting/render.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/render +> Description: Deploy Rivet Engine to Render with managed PostgreSQL and automatic HTTPS, using the experimental PostgreSQL backend. + +--- +PostgreSQL is the recommended backend for multi-node self-hosted deployments today, but it remains experimental. For a production-ready single-node Rivet deployment, use the file system backend (RocksDB-based). Enterprise teams can contact [enterprise support](https://rivet.dev/sales) about FoundationDB for the most scalable production-ready deployment. + +## Prerequisites + +1. A [Render account](https://render.com) +2. A GitHub repository + +## Deploy Rivet Engine + + +### Create the Blueprint Files + + Add these three files to the root of your GitHub repository: + + **render.yaml** + + ```yaml + databases: + - name: rivet-db + plan: basic-256mb + databaseName: rivet + user: rivet + + services: + - type: web + name: rivet-engine + runtime: docker + dockerfilePath: ./Dockerfile.render + plan: starter + healthCheckPath: /health + envVars: + - key: DATABASE_URL + fromDatabase: + name: rivet-db + property: connectionString + - key: RIVET__AUTH__ADMIN_TOKEN + generateValue: true + ``` + + **Dockerfile.render** + + ```dockerfile + FROM rivetdev/engine:latest + + COPY entrypoint.render.sh /entrypoint.render.sh + RUN chmod +x /entrypoint.render.sh + + ENTRYPOINT ["/entrypoint.render.sh"] + ``` + + **entrypoint.render.sh** + + ```bash + #!/bin/sh + + if [ -n "$DATABASE_URL" ]; then + export RIVET__POSTGRES__URL="${DATABASE_URL}?sslmode=disable" + fi + + exec /usr/bin/rivet-engine start + ``` + + Commit and push these files to your repository. + + + +### Deploy to Render + + 1. Go to the [Render Dashboard](https://dashboard.render.com/) + 2. Click **Blueprints** in the left sidebar + 3. Click **New Blueprint Instance** + 4. Connect your GitHub account if you haven't already + 5. Select the repository containing the files from the previous step + 6. Click **Apply** + + Render will automatically create the PostgreSQL database and deploy the Rivet Engine. + + + +### Get Your Admin Token + + 1. Once deployed, go to your **rivet-engine** service in the Render Dashboard + 2. Click the **Environment** tab + 3. Find `RIVET__AUTH__ADMIN_TOKEN` and click the eye icon to reveal the value + 4. Copy this token — you'll need it to access the dashboard + + + +### Access the Rivet Dashboard + + Open your service URL in a browser: + + ``` + https://rivet-engine-xxxx.onrender.com/ui/ + ``` + + Replace `rivet-engine-xxxx` with your actual service name from the Render Dashboard. + + Enter the admin token from the previous step to log in. + + +## WebSocket Timeouts + +Rivet uses long-lived WebSocket connections for both client traffic (browsers, SDKs) and envoy traffic (actor hosts connecting back to the engine). Render's HTTP proxy supports WebSockets, but its default idle timeout will close connections that have no traffic for too long. + +If you front the engine with your own reverse proxy (NGINX, Caddy, etc.) on Render, raise its idle / read timeout to at least 1 hour (`3600` seconds). The same guidance applies to the Render service hosting your RivetKit app, since envoys connect to it over WebSocket. + +## Connecting Your Application + +To connect a RivetKit application to your self-hosted engine, set these environment variables in your app: + +```bash +RIVET_ENDPOINT=https://:@rivet-engine-xxxx.onrender.com +RIVET_PUBLIC_ENDPOINT=https://@rivet-engine-xxxx.onrender.com +``` + +See the [Connect guide](/docs/deploy/custom) for more details on connecting your application. + +## Next Steps + +- Review the [Production Checklist](/docs/self-hosting/production-checklist) before going live +- See [Configuration](/docs/self-hosting/configuration) for all options + +_Source doc path: /docs/self-hosting/render_ diff --git a/.agents/skills/rivetkit/reference/self-hosting/tls.md b/.agents/skills/rivetkit/reference/self-hosting/tls.md new file mode 100644 index 0000000..63573d2 --- /dev/null +++ b/.agents/skills/rivetkit/reference/self-hosting/tls.md @@ -0,0 +1,22 @@ +# TLS & Certificates + +> Source: `src/content/docs/self-hosting/tls.mdx` +> Canonical URL: https://rivet.dev/docs/self-hosting/tls +> Description: How Rivet validates TLS root certificates. + +--- +Public CAs (Let's Encrypt, AWS ACM, and so on) work out of the box. You only need to read this page if you're running behind a corporate or private CA. + +Rivet reads the operating system trust store (`/etc/ssl/certs` on Linux, Keychain on macOS, Schannel on Windows) for all outbound HTTPS. Operator-installed corporate CAs live there and are honored automatically. + +To trust a private CA inside the official `rivetdev/engine` image, extend it the standard Debian way: + +```dockerfile +FROM rivetdev/engine:latest +COPY my-corp-ca.crt /usr/local/share/ca-certificates/ +RUN update-ca-certificates +``` + +Rebuild and redeploy. The same approach works for any machine running a Rivet client: install the CA into the OS trust store and Rivet picks it up. + +_Source doc path: /docs/self-hosting/tls_ diff --git a/.agents/skills/sandbox-agent/SKILL.md b/.agents/skills/sandbox-agent/SKILL.md new file mode 100644 index 0000000..50071ff --- /dev/null +++ b/.agents/skills/sandbox-agent/SKILL.md @@ -0,0 +1,370 @@ +--- +name: "sandbox-agent" +description: "Deploy, configure, and integrate Sandbox Agent - a universal API for orchestrating AI coding agents (Claude Code, Codex, OpenCode, Amp) in sandboxed environments. Use when setting up sandbox-agent server locally or in cloud sandboxes (E2B, Daytona, Docker), creating and managing agent sessions via SDK or API, streaming agent events and handling human-in-the-loop interactions, building chat UIs for coding agents, or understanding the universal schema for agent responses." +--- + +# Sandbox Agent + +Sandbox Agent provides a universal API for orchestrating AI coding agents in sandboxed environments. + +## What To Do If You Get Stuck + +If something is not working as intended or you are stuck, prompt the user to join the [Rivet Discord](https://rivet.dev/discord) or file an issue on [GitHub](https://github.com/rivet-dev/sandbox-agent/issues) to report an issue and get help. + +Provide the user with a pre-generated report with: + +- Symptoms + - If this is happening in local dev, deployed, or both + - The error you're seeing + - Relevant source code related to this +- What you've tried to solve it +- Environment + - Sandbox Agent version + - SDK in use (TypeScript, Python, or HTTP) + - Agent in use (Claude Code, Codex, OpenCode, Amp, Mock) + - Sandbox provider (E2B, Daytona, Docker, local) + +## Quickstart + +### Install skill (optional) + +#### npx + +```bash +npx skills add rivet-dev/skills -s sandbox-agent +``` + +#### bunx + +```bash +bunx skills add rivet-dev/skills -s sandbox-agent +``` + +### Set environment variables + +Each coding agent requires API keys to connect to their respective LLM providers. + +#### Local shell + +```bash +export ANTHROPIC_API_KEY="sk-ant-..." +export OPENAI_API_KEY="sk-..." +``` + +#### E2B + +```typescript +import { Sandbox } from "@e2b/code-interpreter"; + +const envs: Record = {}; +if (process.env.ANTHROPIC_API_KEY) envs.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; +if (process.env.OPENAI_API_KEY) envs.OPENAI_API_KEY = process.env.OPENAI_API_KEY; + +const sandbox = await Sandbox.create({ envs }); +``` + +#### Daytona + +```typescript +import { Daytona } from "@daytonaio/sdk"; + +const envVars: Record = {}; +if (process.env.ANTHROPIC_API_KEY) envVars.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; +if (process.env.OPENAI_API_KEY) envVars.OPENAI_API_KEY = process.env.OPENAI_API_KEY; + +const daytona = new Daytona(); +const sandbox = await daytona.create({ + snapshot: "sandbox-agent-ready", + envVars, +}); +``` + +#### Docker + +```bash +docker run -p 2468:2468 \ + -e ANTHROPIC_API_KEY="sk-ant-..." \ + -e OPENAI_API_KEY="sk-..." \ + rivetdev/sandbox-agent:0.4.2-full \ + server --no-token --host 0.0.0.0 --port 2468 +``` + +#### Extracting API keys from current machine + +Use `sandbox-agent credentials extract-env --export` to extract your existing API keys (Anthropic, OpenAI, etc.) from local Claude Code or Codex config files. + +#### Testing without API keys + +Use the `mock` agent for SDK and integration testing without provider credentials. + +#### Multi-tenant and per-user billing + +For per-tenant token tracking, budget enforcement, or usage-based billing, see [LLM Credentials](/llm-credentials) for gateway options like OpenRouter, LiteLLM, and Portkey. + +### Run the server + +#### curl + +Install and run the binary directly. + +```bash +curl -fsSL https://releases.rivet.dev/sandbox-agent/0.4.x/install.sh | sh +sandbox-agent server --no-token --host 0.0.0.0 --port 2468 +``` + +#### npx + +Run without installing globally. + +```bash +npx @sandbox-agent/cli@0.4.x server --no-token --host 0.0.0.0 --port 2468 +``` + +#### bunx + +Run without installing globally. + +```bash +bunx @sandbox-agent/cli@0.4.x server --no-token --host 0.0.0.0 --port 2468 +``` + +#### npm i -g + +Install globally, then run. + +```bash +npm install -g @sandbox-agent/cli@0.4.x +sandbox-agent server --no-token --host 0.0.0.0 --port 2468 +``` + +#### bun add -g + +Install globally, then run. + +```bash +bun add -g @sandbox-agent/cli@0.4.x +# Allow Bun to run postinstall scripts for native binaries (required for SandboxAgent.start()). +bun pm -g trust @sandbox-agent/cli-linux-x64 @sandbox-agent/cli-linux-arm64 @sandbox-agent/cli-darwin-arm64 @sandbox-agent/cli-darwin-x64 @sandbox-agent/cli-win32-x64 +sandbox-agent server --no-token --host 0.0.0.0 --port 2468 +``` + +#### Node.js (local) + +For local development, use `SandboxAgent.start()` to spawn and manage the server as a subprocess. + +```bash +npm install sandbox-agent@0.4.x +``` + +```typescript +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.start(); +``` + +#### Bun (local) + +For local development, use `SandboxAgent.start()` to spawn and manage the server as a subprocess. + +```bash +bun add sandbox-agent@0.4.x +# Allow Bun to run postinstall scripts for native binaries (required for SandboxAgent.start()). +bun pm trust @sandbox-agent/cli-linux-x64 @sandbox-agent/cli-linux-arm64 @sandbox-agent/cli-darwin-arm64 @sandbox-agent/cli-darwin-x64 @sandbox-agent/cli-win32-x64 +``` + +```typescript +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.start(); +``` + +#### Build from source + +If you're running from source instead of the installed CLI. + +```bash +cargo run -p sandbox-agent -- server --no-token --host 0.0.0.0 --port 2468 +``` + +Binding to `0.0.0.0` allows the server to accept connections from any network interface, which is required when running inside a sandbox where clients connect remotely. + +#### Configuring token + +Tokens are usually not required. Most sandbox providers (E2B, Daytona, etc.) already secure networking at the infrastructure layer. + +If you expose the server publicly, use `--token "$SANDBOX_TOKEN"` to require authentication: + +```bash +sandbox-agent server --token "$SANDBOX_TOKEN" --host 0.0.0.0 --port 2468 +``` + +Then pass the token when connecting: + +#### TypeScript + +```typescript +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://your-server:2468", + token: process.env.SANDBOX_TOKEN, +}); +``` + +#### curl + +```bash +curl "http://your-server:2468/v1/health" \ + -H "Authorization: Bearer $SANDBOX_TOKEN" +``` + +#### CLI + +```bash +sandbox-agent --token "$SANDBOX_TOKEN" api agents list \ + --endpoint http://your-server:2468 +``` + +#### CORS + +If you're calling the server from a browser, see the [CORS configuration guide](/cors). + +### Install agents (optional) + +To preinstall agents: + +```bash +sandbox-agent install-agent --all +``` + +If agents are not installed up front, they are lazily installed when creating a session. + +### Install desktop dependencies (optional, Linux only) + +If you want to use `/v1/desktop/*`, install the desktop runtime packages first: + +```bash +sandbox-agent install desktop --yes +``` + +Then use `GET /v1/desktop/status` or `sdk.getDesktopStatus()` to verify the runtime is ready before calling desktop screenshot or input APIs. + +### Create a session + +```typescript +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", +}); + +const session = await sdk.createSession({ + agent: "claude", + sessionInit: { + cwd: "/", + mcpServers: [], + }, +}); + +console.log(session.id); +``` + +### Send a message + +```typescript +const result = await session.prompt([ + { type: "text", text: "Summarize the repository and suggest next steps." }, +]); + +console.log(result.stopReason); +``` + +### Read events + +```typescript +const off = session.onEvent((event) => { + console.log(event.sender, event.payload); +}); + +const page = await sdk.getEvents({ + sessionId: session.id, + limit: 50, +}); + +console.log(page.items.length); +off(); +``` + +### Test with Inspector + +Open the Inspector UI at `/ui/` on your server (for example, `http://localhost:2468/ui/`) to inspect sessions and events in a GUI. + +![Sandbox Agent Inspector](https://sandboxagent.dev/docs/images/inspector.png) + +## Next steps + +- [Session Persistence](/session-persistence) — Configure in-memory, Rivet Actor state, IndexedDB, SQLite, and Postgres persistence. + +- [Deploy to a Sandbox](/deploy/local) — Deploy your agent to E2B, Daytona, Docker, Vercel, or Cloudflare. + +- [SDK Overview](/sdk-overview) — Use the latest TypeScript SDK API. + +## Reference Map + +### Agents + +- [Amp](references/agents/amp.md) +- [Claude](references/agents/claude.md) +- [Codex](references/agents/codex.md) +- [Cursor](references/agents/cursor.md) +- [OpenCode](references/agents/opencode.md) +- [Pi](references/agents/pi.md) + +### AI + +- [llms.txt](references/ai/llms-txt.md) +- [skill.md](references/ai/skill.md) + +### Deploy + +- [Agent Computer](references/deploy/agentcomputer.md) +- [BoxLite](references/deploy/boxlite.md) +- [Cloudflare](references/deploy/cloudflare.md) +- [ComputeSDK](references/deploy/computesdk.md) +- [Daytona](references/deploy/daytona.md) +- [Docker](references/deploy/docker.md) +- [E2B](references/deploy/e2b.md) +- [Local](references/deploy/local.md) +- [Modal](references/deploy/modal.md) +- [Vercel](references/deploy/vercel.md) + +### General + +- [Agent Sessions](references/agent-sessions.md) +- [Architecture](references/architecture.md) +- [Attachments](references/attachments.md) +- [CLI Reference](references/cli.md) +- [Common Software](references/common-software.md) +- [Computer Use](references/computer-use.md) +- [CORS Configuration](references/cors.md) +- [Custom Tools](references/custom-tools.md) +- [Daemon](references/daemon.md) +- [File System](references/file-system.md) +- [Inspector](references/inspector.md) +- [LLM Credentials](references/llm-credentials.md) +- [Manage Sessions](references/manage-sessions.md) +- [MCP](references/mcp-config.md) +- [Multiplayer](references/multiplayer.md) +- [Observability](references/observability.md) +- [OpenCode Compatibility](references/opencode-compatibility.md) +- [Orchestration Architecture](references/orchestration-architecture.md) +- [Persisting Sessions](references/session-persistence.md) +- [Processes](references/processes.md) +- [Quickstart](references/quickstart.md) +- [React Components](references/react-components.md) +- [SDK Overview](references/sdk-overview.md) +- [Security](references/security.md) +- [Session Restoration](references/session-restoration.md) +- [Skills](references/skills-config.md) +- [Telemetry](references/telemetry.md) +- [Troubleshooting](references/troubleshooting.md) diff --git a/.agents/skills/sandbox-agent/references/agent-sessions.md b/.agents/skills/sandbox-agent/references/agent-sessions.md new file mode 100644 index 0000000..038d1b2 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/agent-sessions.md @@ -0,0 +1,263 @@ +# Agent Sessions + +> Source: `docs/agent-sessions.mdx` +> Canonical URL: https://sandboxagent.dev/docs/agent-sessions +> Description: Create sessions, prompt agents, and inspect event history. + +--- +Sessions are the unit of interaction with an agent. Create one session per task, send prompts, and consume event history. + +For SDK-based flows, sessions can be restored after runtime/session loss when persistence is enabled. +See [Session Restoration](/session-restoration). + +## Create a session + +```ts +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", +}); + +const session = await sdk.createSession({ + agent: "codex", + cwd: "/", +}); + +console.log(session.id, session.agentSessionId); +``` + +## Send a prompt + +```ts +const response = await session.prompt([ + { type: "text", text: "Summarize the repository structure." }, +]); + +console.log(response.stopReason); +``` + +## Subscribe to live events + +```ts +const unsubscribe = session.onEvent((event) => { + console.log(event.eventIndex, event.sender, event.payload); +}); + +await session.prompt([ + { type: "text", text: "Explain the main entrypoints." }, +]); + +unsubscribe(); +``` + +### Event types + +Each event's `payload` contains a session update. The `sessionUpdate` field identifies the type. + +#### agent_message_chunk + +Streamed text or content from the agent's response. + +```json +{ + "sessionUpdate": "agent_message_chunk", + "content": { "type": "text", "text": "Here's how the repository is structured..." } +} +``` + +#### agent_thought_chunk + +Internal reasoning from the agent (chain-of-thought / extended thinking). + +```json +{ + "sessionUpdate": "agent_thought_chunk", + "content": { "type": "text", "text": "I should start by looking at the project structure..." } +} +``` + +#### user_message_chunk + +Echo of the user's prompt being processed. + +```json +{ + "sessionUpdate": "user_message_chunk", + "content": { "type": "text", "text": "Summarize the repository structure." } +} +``` + +#### tool_call + +The agent invoked a tool (file edit, terminal command, etc.). + +```json +{ + "sessionUpdate": "tool_call", + "toolCallId": "tc_abc123", + "title": "Read file", + "status": "in_progress", + "rawInput": { "path": "/src/index.ts" } +} +``` + +#### tool_call_update + +Progress or result update for an in-progress tool call. + +```json +{ + "sessionUpdate": "tool_call_update", + "toolCallId": "tc_abc123", + "status": "completed", + "content": [{ "type": "text", "text": "import express from 'express';\n..." }] +} +``` + +#### plan + +The agent's execution plan for the current task. + +```json +{ + "sessionUpdate": "plan", + "entries": [ + { "content": "Read the project structure", "status": "completed" }, + { "content": "Identify main entrypoints", "status": "in_progress" }, + { "content": "Write summary", "status": "pending" } + ] +} +``` + +#### usage_update + +Token usage metrics for the current turn. + +```json +{ + "sessionUpdate": "usage_update" +} +``` + +#### session_info_update + +Session metadata changed (e.g. agent-generated title). + +```json +{ + "sessionUpdate": "session_info_update", + "title": "Repository structure analysis" +} +``` + +## Fetch persisted event history + +```ts +const page = await sdk.getEvents({ + sessionId: session.id, + limit: 50, +}); + +for (const event of page.items) { + console.log(event.id, event.createdAt, event.sender); +} +``` + +## List and load sessions + +```ts +const sessions = await sdk.listSessions({ limit: 20 }); + +for (const item of sessions.items) { + console.log(item.id, item.agent, item.createdAt); +} + +if (sessions.items.length > 0) { + const loaded = await sdk.resumeSession(sessions.items[0]!.id); + await loaded.prompt([{ type: "text", text: "Continue." }]); +} +``` + +## Configure model, mode, and thought level + +Set the model, mode, or thought level on a session at creation time or after: + +```ts +// At creation time +const session = await sdk.createSession({ + agent: "codex", + model: "gpt-5.3-codex", + mode: "auto", + thoughtLevel: "high", +}); +``` + +```ts +// After creation +await session.setModel("gpt-5.2-codex"); +await session.setMode("full-access"); +await session.setThoughtLevel("medium"); +``` + +Query available modes: + +```ts +const modes = await session.getModes(); +console.log(modes?.currentModeId, modes?.availableModes); +``` + +### Advanced config options + +For config options beyond model, mode, and thought level, use `getConfigOptions` to discover what the agent supports and `setConfigOption` to set any option by ID: + +```ts +const options = await session.getConfigOptions(); +for (const opt of options) { + console.log(opt.id, opt.category, opt.type); +} +``` + +```ts +await session.setConfigOption("some-agent-option", "value"); +``` + +## Handle permission requests + +For agents that request tool-use permissions, register a permission listener and reply with `once`, `always`, or `reject`: + +```ts +const session = await sdk.createSession({ + agent: "claude", + mode: "default", +}); + +session.onPermissionRequest((request) => { + console.log(request.toolCall.title, request.availableReplies); + void session.respondPermission(request.id, "once"); +}); + +await session.prompt([ + { type: "text", text: "Create ./permission-example.txt with the text hello." }, +]); +``` + +### Auto-approving permissions + +To auto-approve all permission requests, respond with `"once"` or `"always"` in your listener: + +```ts +session.onPermissionRequest((request) => { + void session.respondPermission(request.id, "always"); +}); +``` + +See `examples/permissions/src/index.ts` for a complete permissions example that works with Claude and Codex. + +Some agents like Claude allow configuring permission behavior through modes (e.g. `bypassPermissions`, `acceptEdits`). We recommend leaving the mode as `default` and handling permission decisions explicitly in `onPermissionRequest` instead. + +## Destroy a session + +```ts +await sdk.destroySession(session.id); +``` diff --git a/.agents/skills/sandbox-agent/references/agents/amp.md b/.agents/skills/sandbox-agent/references/agents/amp.md new file mode 100644 index 0000000..623a7ac --- /dev/null +++ b/.agents/skills/sandbox-agent/references/agents/amp.md @@ -0,0 +1,22 @@ +# Amp + +> Source: `docs/agents/amp.mdx` +> Canonical URL: https://sandboxagent.dev/docs/agents/amp +> Description: Use Amp as a sandbox agent. + +--- +## Usage + +```typescript +const session = await client.createSession({ + agent: "amp", +}); +``` + +## Capabilities + +| Category | Values | +|----------|--------| +| **Models** | `amp-default` | +| **Modes** | `default`, `bypass` | +| **Thought levels** | Unsupported | diff --git a/.agents/skills/sandbox-agent/references/agents/claude.md b/.agents/skills/sandbox-agent/references/agents/claude.md new file mode 100644 index 0000000..2467590 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/agents/claude.md @@ -0,0 +1,49 @@ +# Claude + +> Source: `docs/agents/claude.mdx` +> Canonical URL: https://sandboxagent.dev/docs/agents/claude +> Description: Use Claude Code as a sandbox agent. + +--- +## Usage + +```typescript +const session = await client.createSession({ + agent: "claude", +}); +``` + +## Capabilities + +| Category | Values | +|----------|--------| +| **Models** | `default`, `sonnet`, `opus`, `haiku` | +| **Modes** | `default`, `acceptEdits`, `plan`, `dontAsk`, `bypassPermissions` | +| **Thought levels** | Unsupported | + +## Configuring effort level + +Claude does not support changing effort level after a session starts. Configure it in the filesystem before creating the session. + +```ts +import { mkdir, writeFile } from "node:fs/promises"; +import path from "node:path"; + +const cwd = "/path/to/workspace"; +await mkdir(path.join(cwd, ".claude"), { recursive: true }); +await writeFile( + path.join(cwd, ".claude", "settings.json"), + JSON.stringify({ effortLevel: "high" }, null, 2), +); + +const session = await client.createSession({ + agent: "claude", + cwd, +}); +``` + +#### Supported settings file locations (highest precedence last) + +1. `~/.claude/settings.json` +2. `/.claude/settings.json` +3. `/.claude/settings.local.json` diff --git a/.agents/skills/sandbox-agent/references/agents/codex.md b/.agents/skills/sandbox-agent/references/agents/codex.md new file mode 100644 index 0000000..0f5708a --- /dev/null +++ b/.agents/skills/sandbox-agent/references/agents/codex.md @@ -0,0 +1,22 @@ +# Codex + +> Source: `docs/agents/codex.mdx` +> Canonical URL: https://sandboxagent.dev/docs/agents/codex +> Description: Use OpenAI Codex as a sandbox agent. + +--- +## Usage + +```typescript +const session = await client.createSession({ + agent: "codex", +}); +``` + +## Capabilities + +| Category | Values | +|----------|--------| +| **Models** | `gpt-5.3-codex` (default), `gpt-5.3-codex-spark`, `gpt-5.2-codex`, `gpt-5.1-codex-max`, `gpt-5.2`, `gpt-5.1-codex-mini` | +| **Modes** | `read-only` (default), `auto`, `full-access` | +| **Thought levels** | `low`, `medium`, `high` (default), `xhigh` | diff --git a/.agents/skills/sandbox-agent/references/agents/cursor.md b/.agents/skills/sandbox-agent/references/agents/cursor.md new file mode 100644 index 0000000..77ab320 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/agents/cursor.md @@ -0,0 +1,34 @@ +# Cursor + +> Source: `docs/agents/cursor.mdx` +> Canonical URL: https://sandboxagent.dev/docs/agents/cursor +> Description: Use Cursor as a sandbox agent. + +--- +## Usage + +```typescript +const session = await client.createSession({ + agent: "cursor", +}); +``` + +## Capabilities + +| Category | Values | +|----------|--------| +| **Models** | See below | +| **Modes** | Unsupported | +| **Thought levels** | Unsupported | + +#### All models + +| Group | Models | +|-------|--------| +| **Auto** | `auto` | +| **Composer** | `composer-1.5`, `composer-1` | +| **GPT-5.3 Codex** | `gpt-5.3-codex`, `gpt-5.3-codex-low`, `gpt-5.3-codex-high`, `gpt-5.3-codex-xhigh`, `gpt-5.3-codex-fast`, `gpt-5.3-codex-low-fast`, `gpt-5.3-codex-high-fast`, `gpt-5.3-codex-xhigh-fast` | +| **GPT-5.2** | `gpt-5.2`, `gpt-5.2-high`, `gpt-5.2-codex`, `gpt-5.2-codex-low`, `gpt-5.2-codex-high`, `gpt-5.2-codex-xhigh`, `gpt-5.2-codex-fast`, `gpt-5.2-codex-low-fast`, `gpt-5.2-codex-high-fast`, `gpt-5.2-codex-xhigh-fast` | +| **GPT-5.1** | `gpt-5.1-high`, `gpt-5.1-codex-max`, `gpt-5.1-codex-max-high` | +| **Claude** | `opus-4.6-thinking` (default), `opus-4.6`, `opus-4.5`, `opus-4.5-thinking`, `sonnet-4.5`, `sonnet-4.5-thinking` | +| **Other** | `gemini-3-pro`, `gemini-3-flash`, `grok` | diff --git a/.agents/skills/sandbox-agent/references/agents/opencode.md b/.agents/skills/sandbox-agent/references/agents/opencode.md new file mode 100644 index 0000000..e309a4a --- /dev/null +++ b/.agents/skills/sandbox-agent/references/agents/opencode.md @@ -0,0 +1,31 @@ +# OpenCode + +> Source: `docs/agents/opencode.mdx` +> Canonical URL: https://sandboxagent.dev/docs/agents/opencode +> Description: Use OpenCode as a sandbox agent. + +--- +## Usage + +```typescript +const session = await client.createSession({ + agent: "opencode", +}); +``` + +## Capabilities + +| Category | Values | +|----------|--------| +| **Models** | See below | +| **Modes** | `build` (default), `plan` | +| **Thought levels** | Unsupported | + +#### All models + +| Provider | Models | +|----------|--------| +| **Anthropic** | `anthropic/claude-3-5-haiku-20241022`, `anthropic/claude-3-5-haiku-latest`, `anthropic/claude-3-5-sonnet-20240620`, `anthropic/claude-3-5-sonnet-20241022`, `anthropic/claude-3-7-sonnet-20250219`, `anthropic/claude-3-7-sonnet-latest`, `anthropic/claude-3-haiku-20240307`, `anthropic/claude-3-opus-20240229`, `anthropic/claude-3-sonnet-20240229`, `anthropic/claude-haiku-4-5`, `anthropic/claude-haiku-4-5-20251001`, `anthropic/claude-opus-4-0`, `anthropic/claude-opus-4-1`, `anthropic/claude-opus-4-1-20250805`, `anthropic/claude-opus-4-20250514`, `anthropic/claude-opus-4-5`, `anthropic/claude-opus-4-5-20251101`, `anthropic/claude-opus-4-6`, `anthropic/claude-sonnet-4-0`, `anthropic/claude-sonnet-4-20250514`, `anthropic/claude-sonnet-4-5`, `anthropic/claude-sonnet-4-5-20250929` | +| **OpenAI** | `openai/gpt-5.1-codex`, `openai/gpt-5.1-codex-max`, `openai/gpt-5.1-codex-mini`, `openai/gpt-5.2`, `openai/gpt-5.2-codex`, `openai/gpt-5.3-codex` | +| **Cerebras** | `cerebras/gpt-oss-120b`, `cerebras/qwen-3-235b-a22b-instruct-2507`, `cerebras/zai-glm-4.7` | +| **OpenCode Zen** | `opencode/big-pickle`, `opencode/claude-3-5-haiku`, `opencode/claude-haiku-4-5`, `opencode/claude-opus-4-1`, `opencode/claude-opus-4-5`, `opencode/claude-opus-4-6`, `opencode/claude-sonnet-4`, `opencode/claude-sonnet-4-5`, `opencode/gemini-3-flash`, `opencode/gemini-3-pro` (default), `opencode/glm-4.6`, `opencode/glm-4.7`, `opencode/gpt-5`, `opencode/gpt-5-codex`, `opencode/gpt-5-nano`, `opencode/gpt-5.1`, `opencode/gpt-5.1-codex`, `opencode/gpt-5.1-codex-max`, `opencode/gpt-5.1-codex-mini`, `opencode/gpt-5.2`, `opencode/gpt-5.2-codex`, `opencode/kimi-k2`, `opencode/kimi-k2-thinking`, `opencode/kimi-k2.5`, `opencode/kimi-k2.5-free`, `opencode/minimax-m2.1`, `opencode/minimax-m2.1-free`, `opencode/trinity-large-preview-free` | diff --git a/.agents/skills/sandbox-agent/references/agents/pi.md b/.agents/skills/sandbox-agent/references/agents/pi.md new file mode 100644 index 0000000..c43d218 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/agents/pi.md @@ -0,0 +1,22 @@ +# Pi + +> Source: `docs/agents/pi.mdx` +> Canonical URL: https://sandboxagent.dev/docs/agents/pi +> Description: Use Pi as a sandbox agent. + +--- +## Usage + +```typescript +const session = await client.createSession({ + agent: "pi", +}); +``` + +## Capabilities + +| Category | Values | +|----------|--------| +| **Models** | `default` | +| **Modes** | Unsupported | +| **Thought levels** | Unsupported | diff --git a/.agents/skills/sandbox-agent/references/ai/llms-txt.md b/.agents/skills/sandbox-agent/references/ai/llms-txt.md new file mode 100644 index 0000000..d4ace0e --- /dev/null +++ b/.agents/skills/sandbox-agent/references/ai/llms-txt.md @@ -0,0 +1,17 @@ +# llms.txt + +> Source: `docs/ai/llms-txt.mdx` +> Canonical URL: https://sandboxagent.dev/docs/ai/llms-txt +> Description: LLM-friendly documentation manifests. + +--- +Mintlify publishes `llms.txt` and `llms-full.txt` for this documentation site. + +Access them at: + +``` +https://sandboxagent.dev/docs/llms.txt +https://sandboxagent.dev/docs/llms-full.txt +``` + +If you run a reverse proxy in front of the docs, forward `/llms.txt` and `/llms-full.txt` to Mintlify. diff --git a/.agents/skills/sandbox-agent/references/ai/skill.md b/.agents/skills/sandbox-agent/references/ai/skill.md new file mode 100644 index 0000000..ed955e1 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/ai/skill.md @@ -0,0 +1,31 @@ +# skill.md + +> Source: `docs/ai/skill.mdx` +> Canonical URL: https://sandboxagent.dev/docs/ai/skill +> Description: Agent skill manifest for this documentation. + +--- +Mintlify hosts a `skill.md` file for this documentation site. + +Access it at: + +``` +https://sandboxagent.dev/docs/skill.md +``` + +To add it to an agent using the Skills CLI: + +#### npx + +```bash +npx skills add rivet-dev/skills -s sandbox-agent +``` + +#### bunx + +```bash +bunx skills add rivet-dev/skills -s sandbox-agent +``` + +If you run a reverse proxy in front of the docs, make sure `/skill.md` and `/.well-known/skills/*` +are forwarded to Mintlify. diff --git a/.agents/skills/sandbox-agent/references/architecture.md b/.agents/skills/sandbox-agent/references/architecture.md new file mode 100644 index 0000000..4358707 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/architecture.md @@ -0,0 +1,65 @@ +# Architecture + +> Source: `docs/architecture.mdx` +> Canonical URL: https://sandboxagent.dev/docs/architecture +> Description: How the Sandbox Agent server, SDK, and agent processes fit together. + +--- +Sandbox Agent is a lightweight HTTP server that runs **inside** a sandbox. It: + +- **Agent management**: Installs, spawns, and stops coding agent processes +- **Sessions**: Routes prompts to agents and streams events back in real time +- **Sandbox APIs**: Filesystem, process, and terminal access for the sandbox environment + +## Components + +```mermaid +flowchart LR + CLIENT["Your App"] + + subgraph SANDBOX["Sandbox"] + direction TB + SERVER["Sandbox Agent Server"] + AGENT["Agent Process
(Claude, Codex, etc.)"] + SERVER --> AGENT + end + + CLIENT -->|"SDK (HTTP)"| SERVER +``` + +- **Your app**: Uses the `sandbox-agent` TypeScript SDK to talk to the server over HTTP. +- **Sandbox**: An isolated runtime (local process, Docker, E2B, Daytona, Vercel, Cloudflare). +- **Sandbox Agent server**: A single binary inside the sandbox that manages agent lifecycles, routes prompts, streams events, and exposes filesystem/process/terminal APIs. +- **Agent process**: A coding agent (Claude Code, Codex, etc.) spawned by the server. Each session maps to one agent process. + +## What `SandboxAgent.start()` does + +1. **Provision**: The provider creates a sandbox (starts a container, creates a VM, etc.) +2. **Install**: The Sandbox Agent binary is installed inside the sandbox +3. **Boot**: The server starts listening on an HTTP port +4. **Health check**: The SDK waits for `/v1/health` to respond +5. **Ready**: The SDK returns a connected client + +For the `local` provider, provisioning is a no-op and the server runs as a local subprocess. + +### Server recovery + +If the server process stops, the SDK automatically calls the provider's `ensureServer()` after 3 consecutive health-check failures. Most built-in providers implement this. Custom providers can add `ensureServer(sandboxId)` to their `SandboxProvider` object. + +## Server HTTP API + +See the [HTTP API reference](/api-reference) for the full list of server endpoints. + +## Agent installation + +Agents are installed lazily on first use. To avoid the cold-start delay, pre-install them: + +```bash +sandbox-agent install-agent --all +``` + +The `rivetdev/sandbox-agent:0.4.2-full` Docker image ships with all agents pre-installed. + +## Production-ready agent orchestration + +For production deployments, see [Orchestration Architecture](/orchestration-architecture) for recommended topology, backend requirements, and session persistence patterns. diff --git a/.agents/skills/sandbox-agent/references/attachments.md b/.agents/skills/sandbox-agent/references/attachments.md new file mode 100644 index 0000000..257f378 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/attachments.md @@ -0,0 +1,57 @@ +# Attachments + +> Source: `docs/attachments.mdx` +> Canonical URL: https://sandboxagent.dev/docs/attachments +> Description: Upload files into the sandbox and reference them in prompts. + +--- +Use the filesystem API to upload files, then include file references in prompt content. + +### Upload a file + +```ts TypeScript +import { SandboxAgent } from "sandbox-agent"; +import fs from "node:fs"; + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", +}); + +const buffer = await fs.promises.readFile("./data.csv"); + +const upload = await sdk.writeFsFile( + { path: "./uploads/data.csv" }, + buffer, +); + +console.log(upload.path); +``` + +```bash cURL +curl -X PUT "http://127.0.0.1:2468/v1/fs/file?path=./uploads/data.csv" \ + --data-binary @./data.csv +``` + +The upload response returns the absolute path. + +### Reference the file in a prompt + +```ts TypeScript +const session = await sdk.createSession({ agent: "mock" }); + +await session.prompt([ + { type: "text", text: "Please analyze the attached CSV." }, + { + type: "resource_link", + name: "data.csv", + uri: "file:///home/sandbox/uploads/data.csv", + mimeType: "text/csv", + }, +]); +``` + +## Notes + +- Use absolute file URIs in `resource_link` blocks. +- If `mimeType` is omitted, the agent/runtime may infer a default. +- Support for non-text resources depends on each agent's prompt capabilities. diff --git a/.agents/skills/sandbox-agent/references/cli.md b/.agents/skills/sandbox-agent/references/cli.md new file mode 100644 index 0000000..bec4bb5 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/cli.md @@ -0,0 +1,299 @@ +# CLI Reference + +> Source: `docs/cli.mdx` +> Canonical URL: https://sandboxagent.dev/docs/cli +> Description: CLI reference for sandbox-agent. + +--- +Global flags (available on all commands): + +- `-t, --token `: require/use bearer auth +- `-n, --no-token`: disable auth + +## server + +Run the HTTP server. + +```bash +sandbox-agent server [OPTIONS] +``` + +| Option | Default | Description | +|--------|---------|-------------| +| `-H, --host ` | `127.0.0.1` | Host to bind | +| `-p, --port ` | `2468` | Port to bind | +| `-O, --cors-allow-origin ` | - | Allowed CORS origin (repeatable) | +| `-M, --cors-allow-method ` | all | Allowed CORS method (repeatable) | +| `-A, --cors-allow-header ` | all | Allowed CORS header (repeatable) | +| `-C, --cors-allow-credentials` | false | Enable CORS credentials | +| `--no-telemetry` | false | Disable anonymous telemetry | + +```bash +sandbox-agent server --port 3000 +``` + +Notes: + +- Server logs are redirected to files by default. +- Set `SANDBOX_AGENT_LOG_STDOUT=1` to force stdout/stderr logging. +- Use `SANDBOX_AGENT_LOG_DIR` to override log directory. + +## install + +Install first-party runtime dependencies. + +### install desktop + +Install the Linux desktop runtime packages required by `/v1/desktop/*`. + +```bash +sandbox-agent install desktop [OPTIONS] +``` + +| Option | Description | +|--------|-------------| +| `--yes` | Skip the confirmation prompt | +| `--print-only` | Print the package-manager command without executing it | +| `--package-manager ` | Override package-manager detection | +| `--no-fonts` | Skip the default DejaVu font package | + +```bash +sandbox-agent install desktop --yes +sandbox-agent install desktop --print-only +``` + +Notes: + +- Supported on Linux only. +- The command detects `apt`, `dnf`, or `apk`. +- If the host is not already running as root, the command requires `sudo`. + +## install-agent + +Install or reinstall a single agent, or every supported agent with `--all`. + +```bash +sandbox-agent install-agent [] [OPTIONS] +``` + +| Option | Description | +|--------|-------------| +| `--all` | Install every supported agent | +| `-r, --reinstall` | Force reinstall | +| `--agent-version ` | Override agent package version (conflicts with `--all`) | +| `--agent-process-version ` | Override agent process version (conflicts with `--all`) | + +Examples: + +```bash +sandbox-agent install-agent claude --reinstall +sandbox-agent install-agent --all +``` + +### Custom Pi implementation path + +If you use a forked/custom `pi` binary with `pi-acp`, you can override what executable gets launched. + +#### Option 1: explicit command override (recommended) + +Set `PI_ACP_PI_COMMAND` in the environment where `sandbox-agent` runs: + +```bash +PI_ACP_PI_COMMAND=/absolute/path/to/your/pi-fork sandbox-agent server +``` + +This is forwarded to `pi-acp`, which uses it instead of looking up `pi` on `PATH`. + +#### Option 2: PATH override + +Put your custom `pi` first on `PATH` before starting `sandbox-agent`: + +```bash +export PATH="/path/to/custom-pi-dir:$PATH" +sandbox-agent server +``` + +#### Option 3: symlink override + +Point `pi` to your custom binary via symlink in a directory that is early on `PATH`: + +```bash +ln -sf /absolute/path/to/your/pi-fork /usr/local/bin/pi +``` + +Then start `sandbox-agent` normally. + +## opencode (experimental) + +Start/reuse daemon and run `opencode attach` against `/opencode`. + +```bash +sandbox-agent opencode [OPTIONS] +``` + +| Option | Default | Description | +|--------|---------|-------------| +| `-H, --host ` | `127.0.0.1` | Daemon host | +| `-p, --port ` | `2468` | Daemon port | +| `--session-title ` | - | Reserved option (currently no-op) | +| `--yolo` | false | OpenCode attach mode flag | + +```bash +sandbox-agent opencode +``` + +## daemon + +Manage the background daemon. + +### daemon start + +```bash +sandbox-agent daemon start [OPTIONS] +``` + +| Option | Default | Description | +|--------|---------|-------------| +| `-H, --host ` | `127.0.0.1` | Host | +| `-p, --port ` | `2468` | Port | +| `--upgrade` | false | Use ensure-running + upgrade behavior | + +```bash +sandbox-agent daemon start +sandbox-agent daemon start --upgrade +``` + +### daemon stop + +```bash +sandbox-agent daemon stop [OPTIONS] +``` + +| Option | Default | Description | +|--------|---------|-------------| +| `-H, --host ` | `127.0.0.1` | Host | +| `-p, --port ` | `2468` | Port | + +### daemon status + +```bash +sandbox-agent daemon status [OPTIONS] +``` + +| Option | Default | Description | +|--------|---------|-------------| +| `-H, --host ` | `127.0.0.1` | Host | +| `-p, --port ` | `2468` | Port | + +## credentials + +### credentials extract + +```bash +sandbox-agent credentials extract [OPTIONS] +``` + +| Option | Description | +|--------|-------------| +| `-a, --agent ` | Filter by `claude`, `codex`, `opencode`, or `amp` | +| `-p, --provider ` | Filter by provider | +| `-d, --home-dir ` | Override home dir | +| `--no-oauth` | Skip OAuth sources | +| `-r, --reveal` | Show full credential values | + +```bash +sandbox-agent credentials extract --agent claude --reveal +``` + +### credentials extract-env + +```bash +sandbox-agent credentials extract-env [OPTIONS] +``` + +| Option | Description | +|--------|-------------| +| `-e, --export` | Prefix output with `export` | +| `-d, --home-dir ` | Override home dir | +| `--no-oauth` | Skip OAuth sources | + +```bash +eval "$(sandbox-agent credentials extract-env --export)" +``` + +## api + +API subcommands for scripting. + +Shared option: + +| Option | Default | Description | +|--------|---------|-------------| +| `-e, --endpoint ` | `http://127.0.0.1:2468` | Target server | + +### api agents + +```bash +sandbox-agent api agents list [--endpoint ] +sandbox-agent api agents report [--endpoint ] +sandbox-agent api agents install [--reinstall] [--endpoint ] +``` + +#### api agents list + +List all agents and their install status. + +```bash +sandbox-agent api agents list +``` + +#### api agents report + +Emit a JSON report of available models, modes, and thought levels for every agent, grouped by category. + +```bash +sandbox-agent api agents report --endpoint http://127.0.0.1:2468 | jq . +``` + +Example output: + +```json +{ + "generatedAtMs": 1740000000000, + "endpoint": "http://127.0.0.1:2468", + "agents": [ + { + "id": "claude", + "installed": true, + "models": { + "currentValue": "default", + "values": [ + { "value": "default", "name": "Default" }, + { "value": "sonnet", "name": "Sonnet" }, + { "value": "opus", "name": "Opus" }, + { "value": "haiku", "name": "Haiku" } + ] + }, + "modes": { + "currentValue": "default", + "values": [ + { "value": "default", "name": "Default" }, + { "value": "acceptEdits", "name": "Accept Edits" }, + { "value": "plan", "name": "Plan" }, + { "value": "dontAsk", "name": "Don't Ask" }, + { "value": "bypassPermissions", "name": "Bypass Permissions" } + ] + }, + "thoughtLevels": { "values": [] } + } + ] +} +``` + +See individual agent pages (e.g. [Claude](/agents/claude), [Codex](/agents/codex)) for supported models, modes, and thought levels. + +#### api agents install + +```bash +sandbox-agent api agents install codex --reinstall +``` diff --git a/.agents/skills/sandbox-agent/references/common-software.md b/.agents/skills/sandbox-agent/references/common-software.md new file mode 100644 index 0000000..3c56954 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/common-software.md @@ -0,0 +1,508 @@ +# Common Software + +> Source: `docs/common-software.mdx` +> Canonical URL: https://sandboxagent.dev/docs/common-software +> Description: Install browsers, languages, databases, and other tools inside the sandbox. + +--- +The sandbox runs a Debian/Ubuntu base image. You can install software with `apt-get` via the [Process API](/processes) or by customizing your Docker image. This page covers commonly needed packages and how to install them. + +## Browsers + +### Chromium + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "chromium", "chromium-sandbox"], +}); + +// Launch headless +await sdk.runProcess({ + command: "chromium", + args: ["--headless", "--no-sandbox", "--disable-gpu", "https://example.com"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","chromium","chromium-sandbox"]}' +``` + +Use `--no-sandbox` when running Chromium inside a container. The container itself provides isolation. + +### Firefox + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "firefox-esr"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","firefox-esr"]}' +``` + +### Playwright browsers + +Playwright bundles its own browser binaries. Install the Playwright CLI and let it download browsers for you. + +```ts TypeScript +await sdk.runProcess({ + command: "npx", + args: ["playwright", "install", "--with-deps", "chromium"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"npx","args":["playwright","install","--with-deps","chromium"]}' +``` + +--- + +## Languages and runtimes + +### Node.js + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "nodejs", "npm"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","nodejs","npm"]}' +``` + +For a specific version, use [nvm](https://github.com/nvm-sh/nvm): + +```ts TypeScript +await sdk.runProcess({ + command: "bash", + args: ["-c", "curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash && . ~/.nvm/nvm.sh && nvm install 22"], +}); +``` + +### Python + +Python 3 is typically pre-installed. To add pip and common packages: + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "python3", "python3-pip", "python3-venv"], +}); + +await sdk.runProcess({ + command: "pip3", + args: ["install", "numpy", "pandas", "matplotlib"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","python3","python3-pip","python3-venv"]}' + +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"pip3","args":["install","numpy","pandas","matplotlib"]}' +``` + +### Go + +```ts TypeScript +await sdk.runProcess({ + command: "bash", + args: ["-c", "curl -fsSL https://go.dev/dl/go1.23.6.linux-amd64.tar.gz | tar -C /usr/local -xz"], +}); + +// Add to PATH for subsequent commands +await sdk.runProcess({ + command: "bash", + args: ["-c", "export PATH=$PATH:/usr/local/go/bin && go version"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"bash","args":["-c","curl -fsSL https://go.dev/dl/go1.23.6.linux-amd64.tar.gz | tar -C /usr/local -xz"]}' +``` + +### Rust + +```ts TypeScript +await sdk.runProcess({ + command: "bash", + args: ["-c", "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"bash","args":["-c","curl --proto =https --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y"]}' +``` + +### Java (OpenJDK) + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "default-jdk"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","default-jdk"]}' +``` + +### Ruby + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "ruby-full"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","ruby-full"]}' +``` + +--- + +## Databases + +### PostgreSQL + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "postgresql", "postgresql-client"], +}); + +// Start the service +const proc = await sdk.createProcess({ + command: "bash", + args: ["-c", "su - postgres -c 'pg_ctlcluster 15 main start'"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","postgresql","postgresql-client"]}' +``` + +### SQLite + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "sqlite3"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","sqlite3"]}' +``` + +### Redis + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "redis-server"], +}); + +const proc = await sdk.createProcess({ + command: "redis-server", + args: ["--daemonize", "no"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","redis-server"]}' + +curl -X POST "http://127.0.0.1:2468/v1/processes" \ + -H "Content-Type: application/json" \ + -d '{"command":"redis-server","args":["--daemonize","no"]}' +``` + +### MySQL / MariaDB + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "mariadb-server", "mariadb-client"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","mariadb-server","mariadb-client"]}' +``` + +--- + +## Build tools + +### Essential build toolchain + +Most compiled software needs the standard build toolchain: + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "build-essential", "cmake", "pkg-config"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","build-essential","cmake","pkg-config"]}' +``` + +This installs `gcc`, `g++`, `make`, `cmake`, and related tools. + +--- + +## Desktop applications + +These require the [Computer Use](/computer-use) desktop to be started first. + +### LibreOffice + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "libreoffice"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","libreoffice"]}' +``` + +### GIMP + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "gimp"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","gimp"]}' +``` + +### VLC + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "vlc"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","vlc"]}' +``` + +### VS Code (code-server) + +```ts TypeScript +await sdk.runProcess({ + command: "bash", + args: ["-c", "curl -fsSL https://code-server.dev/install.sh | sh"], +}); + +const proc = await sdk.createProcess({ + command: "code-server", + args: ["--bind-addr", "0.0.0.0:8080", "--auth", "none"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"bash","args":["-c","curl -fsSL https://code-server.dev/install.sh | sh"]}' + +curl -X POST "http://127.0.0.1:2468/v1/processes" \ + -H "Content-Type: application/json" \ + -d '{"command":"code-server","args":["--bind-addr","0.0.0.0:8080","--auth","none"]}' +``` + +--- + +## CLI tools + +### Git + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "git"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","git"]}' +``` + +### Docker + +```ts TypeScript +await sdk.runProcess({ + command: "bash", + args: ["-c", "curl -fsSL https://get.docker.com | sh"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"bash","args":["-c","curl -fsSL https://get.docker.com | sh"]}' +``` + +### jq + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "jq"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","jq"]}' +``` + +### tmux + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "tmux"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","tmux"]}' +``` + +--- + +## Media and graphics + +### FFmpeg + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "ffmpeg"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","ffmpeg"]}' +``` + +### ImageMagick + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "imagemagick"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","imagemagick"]}' +``` + +### Poppler (PDF utilities) + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "poppler-utils"], +}); + +// Convert PDF to images +await sdk.runProcess({ + command: "pdftoppm", + args: ["-png", "document.pdf", "output"], +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","poppler-utils"]}' +``` + +--- + +## Pre-installing in a Docker image + +For production use, install software in your Dockerfile instead of at runtime. This avoids repeated downloads and makes startup faster. + +```dockerfile +FROM ubuntu:22.04 + +RUN apt-get update && apt-get install -y \ + chromium \ + firefox-esr \ + nodejs npm \ + python3 python3-pip \ + git curl wget \ + build-essential \ + sqlite3 \ + ffmpeg \ + imagemagick \ + jq \ + && rm -rf /var/lib/apt/lists/* + +RUN pip3 install numpy pandas matplotlib +``` + +See [Docker deployment](/deploy/docker) for how to use custom images with Sandbox Agent. diff --git a/.agents/skills/sandbox-agent/references/computer-use.md b/.agents/skills/sandbox-agent/references/computer-use.md new file mode 100644 index 0000000..d5d3492 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/computer-use.md @@ -0,0 +1,809 @@ +# Computer Use + +> Source: `docs/computer-use.mdx` +> Canonical URL: https://sandboxagent.dev/docs/computer-use +> Description: Control a virtual desktop inside the sandbox with mouse, keyboard, screenshots, recordings, and live streaming. + +--- +Sandbox Agent provides a managed virtual desktop (Xvfb + openbox) that you can control programmatically. This is useful for browser automation, GUI testing, and AI computer-use workflows. + +## Start and stop + +```ts TypeScript +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", +}); + +const status = await sdk.startDesktop({ + width: 1920, + height: 1080, + dpi: 96, +}); + +console.log(status.state); // "active" +console.log(status.display); // ":99" + +// When done +await sdk.stopDesktop(); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/desktop/start" \ + -H "Content-Type: application/json" \ + -d '{"width":1920,"height":1080,"dpi":96}' + +curl -X POST "http://127.0.0.1:2468/v1/desktop/stop" +``` + +All fields in the start request are optional. Defaults are 1440x900 at 96 DPI. + +### Start request options + +| Field | Type | Default | Description | +|-------|------|---------|-------------| +| `width` | number | 1440 | Desktop width in pixels | +| `height` | number | 900 | Desktop height in pixels | +| `dpi` | number | 96 | Display DPI | +| `displayNum` | number | 99 | Starting X display number. The runtime probes from this number upward to find an available display. | +| `stateDir` | string | (auto) | Desktop state directory for home, logs, recordings | +| `streamVideoCodec` | string | `"vp8"` | WebRTC video codec (`vp8`, `vp9`, `h264`) | +| `streamAudioCodec` | string | `"opus"` | WebRTC audio codec (`opus`, `g722`) | +| `streamFrameRate` | number | 30 | Streaming frame rate (1-60) | +| `webrtcPortRange` | string | `"59050-59070"` | UDP port range for WebRTC media | +| `recordingFps` | number | 30 | Default recording FPS when not specified in `startDesktopRecording` (1-60) | + +The streaming and recording options configure defaults for the desktop session. They take effect when streaming or recording is started later. + +```ts TypeScript +const status = await sdk.startDesktop({ + width: 1920, + height: 1080, + streamVideoCodec: "h264", + streamFrameRate: 60, + webrtcPortRange: "59100-59120", + recordingFps: 15, +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/desktop/start" \ + -H "Content-Type: application/json" \ + -d '{ + "width": 1920, + "height": 1080, + "streamVideoCodec": "h264", + "streamFrameRate": 60, + "webrtcPortRange": "59100-59120", + "recordingFps": 15 + }' +``` + +## Status + +```ts TypeScript +const status = await sdk.getDesktopStatus(); +console.log(status.state); // "inactive" | "active" | "failed" | ... +``` + +```bash cURL +curl "http://127.0.0.1:2468/v1/desktop/status" +``` + +## Screenshots + +Capture the full desktop or a specific region. Optionally include the cursor position. + +```ts TypeScript +// Full screenshot (PNG by default) +const png = await sdk.takeDesktopScreenshot(); + +// JPEG at 70% quality, half scale +const jpeg = await sdk.takeDesktopScreenshot({ + format: "jpeg", + quality: 70, + scale: 0.5, +}); + +// Include cursor overlay +const withCursor = await sdk.takeDesktopScreenshot({ + showCursor: true, +}); + +// Region screenshot +const region = await sdk.takeDesktopRegionScreenshot({ + x: 100, + y: 100, + width: 400, + height: 300, +}); +``` + +```bash cURL +curl "http://127.0.0.1:2468/v1/desktop/screenshot" --output screenshot.png + +curl "http://127.0.0.1:2468/v1/desktop/screenshot?format=jpeg&quality=70&scale=0.5" \ + --output screenshot.jpg + +# Include cursor overlay +curl "http://127.0.0.1:2468/v1/desktop/screenshot?show_cursor=true" \ + --output with_cursor.png + +curl "http://127.0.0.1:2468/v1/desktop/screenshot/region?x=100&y=100&width=400&height=300" \ + --output region.png +``` + +### Screenshot options + +| Param | Type | Default | Description | +|-------|------|---------|-------------| +| `format` | string | `"png"` | Output format: `png`, `jpeg`, or `webp` | +| `quality` | number | 85 | Compression quality (1-100, JPEG/WebP only) | +| `scale` | number | 1.0 | Scale factor (0.1-1.0) | +| `showCursor` | boolean | `false` | Composite a crosshair at the cursor position | + +When `showCursor` is enabled, the cursor position is captured at the moment of the screenshot and a red crosshair is drawn at that location. This is useful for AI agents that need to see where the cursor is in the screenshot. + +## Mouse + +```ts TypeScript +// Get current position +const pos = await sdk.getDesktopMousePosition(); +console.log(pos.x, pos.y); + +// Move +await sdk.moveDesktopMouse({ x: 500, y: 300 }); + +// Click (left by default) +await sdk.clickDesktop({ x: 500, y: 300 }); + +// Right click +await sdk.clickDesktop({ x: 500, y: 300, button: "right" }); + +// Double click +await sdk.clickDesktop({ x: 500, y: 300, clickCount: 2 }); + +// Drag +await sdk.dragDesktopMouse({ + startX: 100, startY: 100, + endX: 400, endY: 400, +}); + +// Scroll +await sdk.scrollDesktop({ x: 500, y: 300, deltaY: -3 }); +``` + +```bash cURL +curl "http://127.0.0.1:2468/v1/desktop/mouse/position" + +curl -X POST "http://127.0.0.1:2468/v1/desktop/mouse/click" \ + -H "Content-Type: application/json" \ + -d '{"x":500,"y":300}' + +curl -X POST "http://127.0.0.1:2468/v1/desktop/mouse/drag" \ + -H "Content-Type: application/json" \ + -d '{"startX":100,"startY":100,"endX":400,"endY":400}' + +curl -X POST "http://127.0.0.1:2468/v1/desktop/mouse/scroll" \ + -H "Content-Type: application/json" \ + -d '{"x":500,"y":300,"deltaY":-3}' +``` + +## Keyboard + +```ts TypeScript +// Type text +await sdk.typeDesktopText({ text: "Hello, world!" }); + +// Press a key with modifiers +await sdk.pressDesktopKey({ + key: "c", + modifiers: { ctrl: true }, +}); + +// Low-level key down/up +await sdk.keyDownDesktop({ key: "Shift_L" }); +await sdk.keyUpDesktop({ key: "Shift_L" }); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/desktop/keyboard/type" \ + -H "Content-Type: application/json" \ + -d '{"text":"Hello, world!"}' + +curl -X POST "http://127.0.0.1:2468/v1/desktop/keyboard/press" \ + -H "Content-Type: application/json" \ + -d '{"key":"c","modifiers":{"ctrl":true}}' +``` + +## Clipboard + +Read and write the X11 clipboard programmatically. + +```ts TypeScript +// Read clipboard +const clipboard = await sdk.getDesktopClipboard(); +console.log(clipboard.text); + +// Read primary selection (mouse-selected text) +const primary = await sdk.getDesktopClipboard({ selection: "primary" }); + +// Write to clipboard +await sdk.setDesktopClipboard({ text: "Pasted via API" }); + +// Write to both clipboard and primary selection +await sdk.setDesktopClipboard({ + text: "Synced text", + selection: "both", +}); +``` + +```bash cURL +curl "http://127.0.0.1:2468/v1/desktop/clipboard" + +curl "http://127.0.0.1:2468/v1/desktop/clipboard?selection=primary" + +curl -X POST "http://127.0.0.1:2468/v1/desktop/clipboard" \ + -H "Content-Type: application/json" \ + -d '{"text":"Pasted via API"}' + +curl -X POST "http://127.0.0.1:2468/v1/desktop/clipboard" \ + -H "Content-Type: application/json" \ + -d '{"text":"Synced text","selection":"both"}' +``` + +The `selection` parameter controls which X11 selection to read or write: + +| Value | Description | +|-------|-------------| +| `clipboard` (default) | The standard clipboard (Ctrl+C / Ctrl+V) | +| `primary` | The primary selection (text selected with the mouse) | +| `both` | Write to both clipboard and primary selection (write only) | + +## Display and windows + +```ts TypeScript +const display = await sdk.getDesktopDisplayInfo(); +console.log(display.resolution); // { width: 1920, height: 1080, dpi: 96 } + +const { windows } = await sdk.listDesktopWindows(); +for (const win of windows) { + console.log(win.title, win.x, win.y, win.width, win.height); +} +``` + +```bash cURL +curl "http://127.0.0.1:2468/v1/desktop/display/info" + +curl "http://127.0.0.1:2468/v1/desktop/windows" +``` + +The windows endpoint filters out noise automatically: window manager internals (Openbox), windows with empty titles, and tiny helper windows (under 120x80) are excluded. The currently active/focused window is always included regardless of filters. + +### Focused window + +Get the currently focused window without listing all windows. + +```ts TypeScript +const focused = await sdk.getDesktopFocusedWindow(); +console.log(focused.title, focused.id); +``` + +```bash cURL +curl "http://127.0.0.1:2468/v1/desktop/windows/focused" +``` + +Returns 404 if no window currently has focus. + +### Window management + +Focus, move, and resize windows by their X11 window ID. + +```ts TypeScript +const { windows } = await sdk.listDesktopWindows(); +const win = windows[0]; + +// Bring window to foreground +await sdk.focusDesktopWindow(win.id); + +// Move window +await sdk.moveDesktopWindow(win.id, { x: 100, y: 50 }); + +// Resize window +await sdk.resizeDesktopWindow(win.id, { width: 1280, height: 720 }); +``` + +```bash cURL +# Focus a window +curl -X POST "http://127.0.0.1:2468/v1/desktop/windows/12345/focus" + +# Move a window +curl -X POST "http://127.0.0.1:2468/v1/desktop/windows/12345/move" \ + -H "Content-Type: application/json" \ + -d '{"x":100,"y":50}' + +# Resize a window +curl -X POST "http://127.0.0.1:2468/v1/desktop/windows/12345/resize" \ + -H "Content-Type: application/json" \ + -d '{"width":1280,"height":720}' +``` + +All three endpoints return the updated window info so you can verify the operation took effect. The window manager may adjust the requested position or size. + +## App launching + +Launch applications or open files/URLs on the desktop without needing to shell out. + +```ts TypeScript +// Launch an app by name +const result = await sdk.launchDesktopApp({ + app: "firefox", + args: ["--private"], +}); +console.log(result.processId); // "proc_7" + +// Launch and wait for the window to appear +const withWindow = await sdk.launchDesktopApp({ + app: "xterm", + wait: true, +}); +console.log(withWindow.windowId); // "12345" or null if timed out + +// Open a URL with the default handler +const opened = await sdk.openDesktopTarget({ + target: "https://example.com", +}); +console.log(opened.processId); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/desktop/launch" \ + -H "Content-Type: application/json" \ + -d '{"app":"firefox","args":["--private"]}' + +curl -X POST "http://127.0.0.1:2468/v1/desktop/launch" \ + -H "Content-Type: application/json" \ + -d '{"app":"xterm","wait":true}' + +curl -X POST "http://127.0.0.1:2468/v1/desktop/open" \ + -H "Content-Type: application/json" \ + -d '{"target":"https://example.com"}' +``` + +The returned `processId` can be used with the [Process API](/processes) to read logs (`GET /v1/processes/{id}/logs`) or stop the application (`POST /v1/processes/{id}/stop`). + +When `wait` is `true`, the API polls for up to 5 seconds for a window to appear. If the window appears, its ID is returned in `windowId`. If it times out, `windowId` is `null` but the process is still running. + +**Launch/Open vs the Process API:** Both `launch` and `open` are convenience wrappers around the [Process API](/processes). They create managed processes (with `owner: "desktop"`) that you can inspect, log, and stop through the same Process endpoints. The difference is that `launch` validates the binary exists in PATH first and can optionally wait for a window to appear, while `open` delegates to the system default handler (`xdg-open`). Use the Process API directly when you need full control over command, environment, working directory, or restart policies. + +## Recording + +Record the desktop to MP4. + +```ts TypeScript +const recording = await sdk.startDesktopRecording({ fps: 30 }); +console.log(recording.id); + +// ... do things ... + +const stopped = await sdk.stopDesktopRecording(); + +// List all recordings +const { recordings } = await sdk.listDesktopRecordings(); + +// Download +const mp4 = await sdk.downloadDesktopRecording(recording.id); + +// Clean up +await sdk.deleteDesktopRecording(recording.id); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/desktop/recording/start" \ + -H "Content-Type: application/json" \ + -d '{"fps":30}' + +curl -X POST "http://127.0.0.1:2468/v1/desktop/recording/stop" + +curl "http://127.0.0.1:2468/v1/desktop/recordings" + +curl "http://127.0.0.1:2468/v1/desktop/recordings/rec_1/download" --output recording.mp4 + +curl -X DELETE "http://127.0.0.1:2468/v1/desktop/recordings/rec_1" +``` + +## Desktop processes + +The desktop runtime manages several background processes (Xvfb, openbox, neko, ffmpeg). These are all registered with the general [Process API](/processes) under the `desktop` owner, so you can inspect logs, check status, and troubleshoot using the same tools you use for any other managed process. + +```ts TypeScript +// List all processes, including desktop-owned ones +const { processes } = await sdk.listProcesses(); + +const desktopProcs = processes.filter((p) => p.owner === "desktop"); +for (const p of desktopProcs) { + console.log(p.id, p.command, p.status); +} + +// Read logs from a specific desktop process +const logs = await sdk.getProcessLogs(desktopProcs[0].id, { tail: 50 }); +for (const entry of logs.entries) { + console.log(entry.stream, atob(entry.data)); +} +``` + +```bash cURL +# List all processes (desktop processes have owner: "desktop") +curl "http://127.0.0.1:2468/v1/processes" + +# Get logs from a specific desktop process +curl "http://127.0.0.1:2468/v1/processes/proc_1/logs?tail=50" +``` + +The desktop status endpoint also includes a summary of running processes: + +```ts TypeScript +const status = await sdk.getDesktopStatus(); +for (const proc of status.processes) { + console.log(proc.name, proc.pid, proc.running); +} +``` + +```bash cURL +curl "http://127.0.0.1:2468/v1/desktop/status" +# Response includes: processes: [{ name: "Xvfb", pid: 123, running: true }, ...] +``` + +| Process | Role | Restart policy | +|---------|------|---------------| +| Xvfb | Virtual X11 framebuffer | Auto-restart while desktop is active | +| openbox | Window manager | Auto-restart while desktop is active | +| neko | WebRTC streaming server (started by `startDesktopStream`) | No auto-restart | +| ffmpeg | Screen recorder (started by `startDesktopRecording`) | No auto-restart | + +## Live streaming + +Start a WebRTC stream for real-time desktop viewing in a browser. + +```ts TypeScript +await sdk.startDesktopStream(); + +// Check stream status +const status = await sdk.getDesktopStreamStatus(); +console.log(status.active); // true +console.log(status.processId); // "proc_5" + +// Connect via the React DesktopViewer component or +// use the WebSocket signaling endpoint directly +// at ws://127.0.0.1:2468/v1/desktop/stream/signaling + +await sdk.stopDesktopStream(); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/desktop/stream/start" + +# Check stream status +curl "http://127.0.0.1:2468/v1/desktop/stream/status" + +# Connect to ws://127.0.0.1:2468/v1/desktop/stream/signaling for WebRTC signaling + +curl -X POST "http://127.0.0.1:2468/v1/desktop/stream/stop" +``` + +For a drop-in React component, see [React Components](/react-components). + +## API reference + +### Endpoints + +| Method | Path | Description | +|--------|------|-------------| +| `POST` | `/v1/desktop/start` | Start the desktop runtime | +| `POST` | `/v1/desktop/stop` | Stop the desktop runtime | +| `GET` | `/v1/desktop/status` | Get desktop runtime status | +| `GET` | `/v1/desktop/screenshot` | Capture full desktop screenshot | +| `GET` | `/v1/desktop/screenshot/region` | Capture a region screenshot | +| `GET` | `/v1/desktop/mouse/position` | Get current mouse position | +| `POST` | `/v1/desktop/mouse/move` | Move the mouse | +| `POST` | `/v1/desktop/mouse/click` | Click the mouse | +| `POST` | `/v1/desktop/mouse/down` | Press mouse button down | +| `POST` | `/v1/desktop/mouse/up` | Release mouse button | +| `POST` | `/v1/desktop/mouse/drag` | Drag from one point to another | +| `POST` | `/v1/desktop/mouse/scroll` | Scroll at a position | +| `POST` | `/v1/desktop/keyboard/type` | Type text | +| `POST` | `/v1/desktop/keyboard/press` | Press a key with optional modifiers | +| `POST` | `/v1/desktop/keyboard/down` | Press a key down (hold) | +| `POST` | `/v1/desktop/keyboard/up` | Release a key | +| `GET` | `/v1/desktop/display/info` | Get display info | +| `GET` | `/v1/desktop/windows` | List visible windows | +| `GET` | `/v1/desktop/windows/focused` | Get focused window info | +| `POST` | `/v1/desktop/windows/{id}/focus` | Focus a window | +| `POST` | `/v1/desktop/windows/{id}/move` | Move a window | +| `POST` | `/v1/desktop/windows/{id}/resize` | Resize a window | +| `GET` | `/v1/desktop/clipboard` | Read clipboard contents | +| `POST` | `/v1/desktop/clipboard` | Write to clipboard | +| `POST` | `/v1/desktop/launch` | Launch an application | +| `POST` | `/v1/desktop/open` | Open a file or URL | +| `POST` | `/v1/desktop/recording/start` | Start recording | +| `POST` | `/v1/desktop/recording/stop` | Stop recording | +| `GET` | `/v1/desktop/recordings` | List recordings | +| `GET` | `/v1/desktop/recordings/{id}` | Get recording metadata | +| `GET` | `/v1/desktop/recordings/{id}/download` | Download recording | +| `DELETE` | `/v1/desktop/recordings/{id}` | Delete recording | +| `POST` | `/v1/desktop/stream/start` | Start WebRTC streaming | +| `POST` | `/v1/desktop/stream/stop` | Stop WebRTC streaming | +| `GET` | `/v1/desktop/stream/status` | Get stream status | +| `GET` | `/v1/desktop/stream/signaling` | WebSocket for WebRTC signaling | + +### TypeScript SDK methods + +| Method | Returns | Description | +|--------|---------|-------------| +| `startDesktop(request?)` | `DesktopStatusResponse` | Start the desktop | +| `stopDesktop()` | `DesktopStatusResponse` | Stop the desktop | +| `getDesktopStatus()` | `DesktopStatusResponse` | Get desktop status | +| `takeDesktopScreenshot(query?)` | `Uint8Array` | Capture screenshot | +| `takeDesktopRegionScreenshot(query)` | `Uint8Array` | Capture region screenshot | +| `getDesktopMousePosition()` | `DesktopMousePositionResponse` | Get mouse position | +| `moveDesktopMouse(request)` | `DesktopMousePositionResponse` | Move mouse | +| `clickDesktop(request)` | `DesktopMousePositionResponse` | Click mouse | +| `mouseDownDesktop(request)` | `DesktopMousePositionResponse` | Mouse button down | +| `mouseUpDesktop(request)` | `DesktopMousePositionResponse` | Mouse button up | +| `dragDesktopMouse(request)` | `DesktopMousePositionResponse` | Drag mouse | +| `scrollDesktop(request)` | `DesktopMousePositionResponse` | Scroll | +| `typeDesktopText(request)` | `DesktopActionResponse` | Type text | +| `pressDesktopKey(request)` | `DesktopActionResponse` | Press key | +| `keyDownDesktop(request)` | `DesktopActionResponse` | Key down | +| `keyUpDesktop(request)` | `DesktopActionResponse` | Key up | +| `getDesktopDisplayInfo()` | `DesktopDisplayInfoResponse` | Get display info | +| `listDesktopWindows()` | `DesktopWindowListResponse` | List windows | +| `getDesktopFocusedWindow()` | `DesktopWindowInfo` | Get focused window | +| `focusDesktopWindow(id)` | `DesktopWindowInfo` | Focus a window | +| `moveDesktopWindow(id, request)` | `DesktopWindowInfo` | Move a window | +| `resizeDesktopWindow(id, request)` | `DesktopWindowInfo` | Resize a window | +| `getDesktopClipboard(query?)` | `DesktopClipboardResponse` | Read clipboard | +| `setDesktopClipboard(request)` | `DesktopActionResponse` | Write clipboard | +| `launchDesktopApp(request)` | `DesktopLaunchResponse` | Launch an app | +| `openDesktopTarget(request)` | `DesktopOpenResponse` | Open file/URL | +| `startDesktopRecording(request?)` | `DesktopRecordingInfo` | Start recording | +| `stopDesktopRecording()` | `DesktopRecordingInfo` | Stop recording | +| `listDesktopRecordings()` | `DesktopRecordingListResponse` | List recordings | +| `getDesktopRecording(id)` | `DesktopRecordingInfo` | Get recording | +| `downloadDesktopRecording(id)` | `Uint8Array` | Download recording | +| `deleteDesktopRecording(id)` | `void` | Delete recording | +| `startDesktopStream()` | `DesktopStreamStatusResponse` | Start streaming | +| `stopDesktopStream()` | `DesktopStreamStatusResponse` | Stop streaming | +| `getDesktopStreamStatus()` | `DesktopStreamStatusResponse` | Stream status | + +## Customizing the desktop environment + +The desktop runs inside the sandbox filesystem, so you can customize it using the [File System](/file-system) API before or after starting the desktop. The desktop HOME directory is located at `~/.local/state/sandbox-agent/desktop/home` (or `$XDG_STATE_HOME/sandbox-agent/desktop/home` if `XDG_STATE_HOME` is set). + +All configuration files below are written to paths relative to this HOME directory. + +### Window manager (openbox) + +The desktop uses [openbox](http://openbox.org/) as its window manager. You can customize its behavior, theme, and keyboard shortcuts by writing an `rc.xml` config file. + +```ts TypeScript +const openboxConfig = ` + + + Clearlooks + NLIMC + DejaVu Sans10 + + 1 + + + + +`; + +await sdk.mkdirFs({ path: "~/.local/state/sandbox-agent/desktop/home/.config/openbox" }); +await sdk.writeFsFile( + { path: "~/.local/state/sandbox-agent/desktop/home/.config/openbox/rc.xml" }, + openboxConfig, +); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/fs/mkdir?path=~/.local/state/sandbox-agent/desktop/home/.config/openbox" + +curl -X PUT "http://127.0.0.1:2468/v1/fs/file?path=~/.local/state/sandbox-agent/desktop/home/.config/openbox/rc.xml" \ + -H "Content-Type: application/octet-stream" \ + --data-binary @rc.xml +``` + +### Autostart programs + +Openbox runs scripts in `~/.config/openbox/autostart` on startup. Use this to launch applications, set the background, or configure the environment. + +```ts TypeScript +const autostart = `#!/bin/sh +# Set a solid background color +xsetroot -solid "#1e1e2e" & + +# Launch a terminal +xterm -geometry 120x40+50+50 & + +# Launch a browser +firefox --no-remote & +`; + +await sdk.mkdirFs({ path: "~/.local/state/sandbox-agent/desktop/home/.config/openbox" }); +await sdk.writeFsFile( + { path: "~/.local/state/sandbox-agent/desktop/home/.config/openbox/autostart" }, + autostart, +); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/fs/mkdir?path=~/.local/state/sandbox-agent/desktop/home/.config/openbox" + +curl -X PUT "http://127.0.0.1:2468/v1/fs/file?path=~/.local/state/sandbox-agent/desktop/home/.config/openbox/autostart" \ + -H "Content-Type: application/octet-stream" \ + --data-binary @autostart.sh +``` + +The autostart script runs when openbox starts, which happens during `startDesktop()`. Write the autostart file before calling `startDesktop()` for it to take effect. + +### Background + +There is no wallpaper set by default (the background is the X root window default). You can set it using `xsetroot` in the autostart script (as shown above), or use `feh` if you need an image: + +```ts TypeScript +// Upload a wallpaper image +import fs from "node:fs"; + +const wallpaper = await fs.promises.readFile("./wallpaper.png"); +await sdk.writeFsFile( + { path: "~/.local/state/sandbox-agent/desktop/home/wallpaper.png" }, + wallpaper, +); + +// Set the autostart to apply it +const autostart = `#!/bin/sh +feh --bg-fill ~/wallpaper.png & +`; + +await sdk.mkdirFs({ path: "~/.local/state/sandbox-agent/desktop/home/.config/openbox" }); +await sdk.writeFsFile( + { path: "~/.local/state/sandbox-agent/desktop/home/.config/openbox/autostart" }, + autostart, +); +``` + +```bash cURL +curl -X PUT "http://127.0.0.1:2468/v1/fs/file?path=~/.local/state/sandbox-agent/desktop/home/wallpaper.png" \ + -H "Content-Type: application/octet-stream" \ + --data-binary @wallpaper.png + +curl -X PUT "http://127.0.0.1:2468/v1/fs/file?path=~/.local/state/sandbox-agent/desktop/home/.config/openbox/autostart" \ + -H "Content-Type: application/octet-stream" \ + --data-binary @autostart.sh +``` + +`feh` is not installed by default. Install it via the [Process API](/processes) before starting the desktop: `await sdk.runProcess({ command: "apt-get", args: ["install", "-y", "feh"] })`. + +### Fonts + +Only `fonts-dejavu-core` is installed by default. To add more fonts, install them with your system package manager or copy font files into the sandbox: + +```ts TypeScript +// Install a font package +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "fonts-noto", "fonts-liberation"], +}); + +// Or copy a custom font file +import fs from "node:fs"; + +const font = await fs.promises.readFile("./CustomFont.ttf"); +await sdk.mkdirFs({ path: "~/.local/state/sandbox-agent/desktop/home/.local/share/fonts" }); +await sdk.writeFsFile( + { path: "~/.local/state/sandbox-agent/desktop/home/.local/share/fonts/CustomFont.ttf" }, + font, +); + +// Rebuild the font cache +await sdk.runProcess({ command: "fc-cache", args: ["-fv"] }); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","fonts-noto","fonts-liberation"]}' + +curl -X POST "http://127.0.0.1:2468/v1/fs/mkdir?path=~/.local/state/sandbox-agent/desktop/home/.local/share/fonts" + +curl -X PUT "http://127.0.0.1:2468/v1/fs/file?path=~/.local/state/sandbox-agent/desktop/home/.local/share/fonts/CustomFont.ttf" \ + -H "Content-Type: application/octet-stream" \ + --data-binary @CustomFont.ttf + +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"fc-cache","args":["-fv"]}' +``` + +### Cursor theme + +```ts TypeScript +await sdk.runProcess({ + command: "apt-get", + args: ["install", "-y", "dmz-cursor-theme"], +}); + +const xresources = `Xcursor.theme: DMZ-White\nXcursor.size: 24\n`; +await sdk.writeFsFile( + { path: "~/.local/state/sandbox-agent/desktop/home/.Xresources" }, + xresources, +); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"apt-get","args":["install","-y","dmz-cursor-theme"]}' + +curl -X PUT "http://127.0.0.1:2468/v1/fs/file?path=~/.local/state/sandbox-agent/desktop/home/.Xresources" \ + -H "Content-Type: application/octet-stream" \ + --data-binary 'Xcursor.theme: DMZ-White\nXcursor.size: 24' +``` + +Run `xrdb -merge ~/.Xresources` (via the autostart or process API) after writing the file for changes to take effect. + +### Shell and terminal + +No terminal emulator or shell is launched by default. Add one to the openbox autostart: + +```sh +# In ~/.config/openbox/autostart +xterm -geometry 120x40+50+50 & +``` + +To use a different shell, set the `SHELL` environment variable in your Dockerfile or install your preferred shell and configure the terminal to use it. + +### GTK theme + +Applications using GTK will pick up settings from `~/.config/gtk-3.0/settings.ini`: + +```ts TypeScript +const gtkSettings = `[Settings] +gtk-theme-name=Adwaita +gtk-icon-theme-name=Adwaita +gtk-font-name=DejaVu Sans 10 +gtk-cursor-theme-name=DMZ-White +gtk-cursor-theme-size=24 +`; + +await sdk.mkdirFs({ path: "~/.local/state/sandbox-agent/desktop/home/.config/gtk-3.0" }); +await sdk.writeFsFile( + { path: "~/.local/state/sandbox-agent/desktop/home/.config/gtk-3.0/settings.ini" }, + gtkSettings, +); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/fs/mkdir?path=~/.local/state/sandbox-agent/desktop/home/.config/gtk-3.0" + +curl -X PUT "http://127.0.0.1:2468/v1/fs/file?path=~/.local/state/sandbox-agent/desktop/home/.config/gtk-3.0/settings.ini" \ + -H "Content-Type: application/octet-stream" \ + --data-binary @settings.ini +``` + +### Summary of configuration paths + +All paths are relative to the desktop HOME directory (`~/.local/state/sandbox-agent/desktop/home`). + +| What | Path | Notes | +|------|------|-------| +| Openbox config | `.config/openbox/rc.xml` | Window manager theme, keybindings, behavior | +| Autostart | `.config/openbox/autostart` | Shell script run on desktop start | +| Custom fonts | `.local/share/fonts/` | TTF/OTF files, run `fc-cache -fv` after | +| Cursor theme | `.Xresources` | Requires `xrdb -merge` to apply | +| GTK 3 settings | `.config/gtk-3.0/settings.ini` | Theme, icons, fonts for GTK apps | +| Wallpaper | Any path, referenced from autostart | Requires `feh` or similar tool | diff --git a/.agents/skills/sandbox-agent/references/cors.md b/.agents/skills/sandbox-agent/references/cors.md new file mode 100644 index 0000000..c8fdebf --- /dev/null +++ b/.agents/skills/sandbox-agent/references/cors.md @@ -0,0 +1,52 @@ +# CORS Configuration + +> Source: `docs/cors.mdx` +> Canonical URL: https://sandboxagent.dev/docs/cors +> Description: Configure CORS for browser-based applications. + +--- +When calling the Sandbox Agent server from a browser, CORS (Cross-Origin Resource Sharing) controls which origins can make requests. + +## Default Behavior + +By default, no CORS origins are allowed. You must explicitly specify origins for browser-based applications: + +```bash +sandbox-agent server \ + --cors-allow-origin "http://localhost:5173" +``` + +The built-in Inspector UI at `/ui/` is served from the same origin as the server, so it does not require CORS configuration. + +## Options + +| Flag | Description | +|------|-------------| +| `--cors-allow-origin` | Origins to allow | +| `--cors-allow-method` | HTTP methods to allow (defaults to all if not specified) | +| `--cors-allow-header` | Headers to allow (defaults to all if not specified) | +| `--cors-allow-credentials` | Allow credentials (cookies, authorization headers) | + +## Multiple Origins + +Specify the flag multiple times to allow multiple origins: + +```bash +sandbox-agent server \ + --cors-allow-origin "http://localhost:5173" \ + --cors-allow-origin "http://localhost:3000" +``` + +## Restricting Methods and Headers + +By default, all methods and headers are allowed. To restrict them: + +```bash +sandbox-agent server \ + --cors-allow-origin "https://your-app.com" \ + --cors-allow-method "GET" \ + --cors-allow-method "POST" \ + --cors-allow-header "Authorization" \ + --cors-allow-header "Content-Type" \ + --cors-allow-credentials +``` diff --git a/.agents/skills/sandbox-agent/references/custom-tools.md b/.agents/skills/sandbox-agent/references/custom-tools.md new file mode 100644 index 0000000..6034e7f --- /dev/null +++ b/.agents/skills/sandbox-agent/references/custom-tools.md @@ -0,0 +1,149 @@ +# Custom Tools + +> Source: `docs/custom-tools.mdx` +> Canonical URL: https://sandboxagent.dev/docs/custom-tools +> Description: Give agents custom tools inside the sandbox using MCP servers or skills. + +--- +There are two common patterns for sandbox-local custom tooling: + +| | MCP Server | Skill | +|---|---|---| +| **How it works** | Agent connects to an MCP server (`mcpServers`) | Agent follows `SKILL.md` instructions and runs scripts | +| **Best for** | Typed tool calls and structured protocols | Lightweight task-specific guidance | +| **Requires** | MCP server process (stdio/http/sse) | Script + `SKILL.md` | + +## Option A: MCP server (stdio) + +### Write and bundle your MCP server + +```ts src/mcp-server.ts +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { z } from "zod"; + +const server = new McpServer({ name: "rand", version: "1.0.0" }); + +server.tool( + "random_number", + "Generate a random integer between min and max", + { + min: z.number(), + max: z.number(), + }, + async ({ min, max }) => ({ + content: [{ type: "text", text: String(Math.floor(Math.random() * (max - min + 1)) + min) }], + }), +); + +await server.connect(new StdioServerTransport()); +``` + +```bash +npx esbuild src/mcp-server.ts --bundle --format=cjs --platform=node --target=node18 --outfile=dist/mcp-server.cjs +``` + +### Upload it into the sandbox + +```ts +import { SandboxAgent } from "sandbox-agent"; +import fs from "node:fs"; + +const sdk = await SandboxAgent.connect({ baseUrl: "http://127.0.0.1:2468" }); +const content = await fs.promises.readFile("./dist/mcp-server.cjs"); + +await sdk.writeFsFile({ path: "/opt/mcp/custom-tools/mcp-server.cjs" }, content); +``` + +```bash +curl -X PUT "http://127.0.0.1:2468/v1/fs/file?path=/opt/mcp/custom-tools/mcp-server.cjs" \ + --data-binary @./dist/mcp-server.cjs +``` + +### Register MCP config and create a session + +```ts +await sdk.setMcpConfig( + { + directory: "/workspace", + mcpName: "customTools", + }, + { + type: "local", + command: "node", + args: ["/opt/mcp/custom-tools/mcp-server.cjs"], + }, +); + +const session = await sdk.createSession({ + agent: "claude", + cwd: "/workspace", +}); + +await session.prompt([ + { type: "text", text: "Use the random_number tool with min=1 and max=10." }, +]); +``` + +## Option B: Skills + +### Write script + skill file + +```ts src/random-number.ts +const min = Number(process.argv[2]); +const max = Number(process.argv[3]); + +if (Number.isNaN(min) || Number.isNaN(max)) { + console.error("Usage: random-number "); + process.exit(1); +} + +console.log(Math.floor(Math.random() * (max - min + 1)) + min); +``` + +````md SKILL.md +--- +name: random-number +description: Generate a random integer between min and max. +--- + +Run: + +```bash +node /opt/skills/random-number/random-number.cjs +``` +```` + +```bash +npx esbuild src/random-number.ts --bundle --format=cjs --platform=node --target=node18 --outfile=dist/random-number.cjs +``` + +### Upload files + +```ts +import fs from "node:fs"; + +const script = await fs.promises.readFile("./dist/random-number.cjs"); +await sdk.writeFsFile({ path: "/opt/skills/random-number/random-number.cjs" }, script); + +const skill = await fs.promises.readFile("./SKILL.md"); +await sdk.writeFsFile({ path: "/opt/skills/random-number/SKILL.md" }, skill); +``` + +### Use in a session + +```ts +const session = await sdk.createSession({ + agent: "claude", + cwd: "/workspace", +}); + +await session.prompt([ + { type: "text", text: "Use the random-number skill to pick a number from 1 to 100." }, +]); +``` + +## Notes + +- The sandbox runtime must include Node.js (or your chosen runtime). +- For persistent skill-source wiring by directory, see [Skills](/skills-config). diff --git a/.agents/skills/sandbox-agent/references/daemon.md b/.agents/skills/sandbox-agent/references/daemon.md new file mode 100644 index 0000000..afc3260 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/daemon.md @@ -0,0 +1,71 @@ +# Daemon + +> Source: `docs/daemon.mdx` +> Canonical URL: https://sandboxagent.dev/docs/daemon +> Description: Background daemon lifecycle and management. + +--- +The sandbox-agent daemon is a background server process. Commands like `sandbox-agent opencode` and `gigacode` can ensure it is running. + +## How it works + +1. A daemon-aware command checks for a healthy daemon at host/port. +2. If missing, it starts one in the background and records PID/version files. +3. Subsequent checks can compare build/version and restart when required. + +## Auto-upgrade behavior + +- `sandbox-agent opencode` and `gigacode` use ensure-running behavior with upgrade checks. +- `sandbox-agent daemon start` uses direct start by default. +- `sandbox-agent daemon start --upgrade` uses ensure-running behavior (including version check/restart). + +## Managing the daemon + +### Start + +```bash +sandbox-agent daemon start [OPTIONS] +``` + +| Option | Default | Description | +|--------|---------|-------------| +| `-H, --host ` | `127.0.0.1` | Host | +| `-p, --port ` | `2468` | Port | +| `--upgrade` | false | Use ensure-running + upgrade behavior | + +```bash +sandbox-agent daemon start +sandbox-agent daemon start --upgrade +``` + +### Stop + +```bash +sandbox-agent daemon stop [OPTIONS] +``` + +| Option | Default | Description | +|--------|---------|-------------| +| `-H, --host ` | `127.0.0.1` | Host | +| `-p, --port ` | `2468` | Port | + +### Status + +```bash +sandbox-agent daemon status [OPTIONS] +``` + +| Option | Default | Description | +|--------|---------|-------------| +| `-H, --host ` | `127.0.0.1` | Host | +| `-p, --port ` | `2468` | Port | + +## Files + +Daemon state is stored under the sandbox-agent data directory (for example `~/.local/share/sandbox-agent/daemon/`): + +| File | Purpose | +|------|---------| +| `daemon-{host}-{port}.pid` | PID of running daemon | +| `daemon-{host}-{port}.version` | Build/version marker | +| `daemon-{host}-{port}.log` | Daemon stdout/stderr log | diff --git a/.agents/skills/sandbox-agent/references/deploy/agentcomputer.md b/.agents/skills/sandbox-agent/references/deploy/agentcomputer.md new file mode 100644 index 0000000..77e794b --- /dev/null +++ b/.agents/skills/sandbox-agent/references/deploy/agentcomputer.md @@ -0,0 +1,62 @@ +# Agent Computer + +> Source: `docs/deploy/agentcomputer.mdx` +> Canonical URL: https://sandboxagent.dev/docs/deploy/agentcomputer +> Description: Run Sandbox Agent on Agent Computer managed workers. + +--- +## Prerequisites + +- `COMPUTER_API_KEY` or `AGENTCOMPUTER_API_KEY` +- An Agent Computer managed-worker image, or default machine source, that already has your coding agent authenticated + +The platform image already includes Sandbox Agent, Claude Code, and Codex. Agent credentials still live inside the machine, so make sure your image or workspace bootstrap has already handled agent login. + +## TypeScript example + +```bash +npm install sandbox-agent@0.4.x +``` + +```typescript +import { SandboxAgent } from "sandbox-agent"; +import { agentcomputer } from "sandbox-agent/agentcomputer"; + +const sdk = await SandboxAgent.start({ + sandbox: agentcomputer(), +}); + +try { + const health = await sdk.getHealth(); + console.log(health.status); + console.log(sdk.inspectorUrl); + + const agents = await sdk.listAgents(); + console.log(agents.agents.map((agent) => agent.id)); +} finally { + await sdk.destroySandbox(); +} +``` + +The `agentcomputer` provider creates a managed-worker computer, waits until browser access is ready, and routes SDK requests through the machine's authenticated web host. `sdk.inspectorUrl` is already a browser-ready URL, so it opens the built-in Inspector directly. + +By default, the provider creates: + +- `runtimeFamily: "managed-worker"` +- `usePlatformDefault: true` + +Pass `create` when you want to override the handle, workspace name, or other machine-create settings: + +```typescript +const sdk = await SandboxAgent.start({ + sandbox: agentcomputer({ + create: { + handle: "sandbox-agent-demo", + workspaceName: "sandbox-agent-demo", + usePlatformDefault: false, + }, + }), +}); +``` + +Set `apiUrl` when you are targeting a self-hosted or local Agent Computer API instead of `https://api.computer.agentcomputer.ai`. diff --git a/.agents/skills/sandbox-agent/references/deploy/boxlite.md b/.agents/skills/sandbox-agent/references/deploy/boxlite.md new file mode 100644 index 0000000..9ccf431 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/deploy/boxlite.md @@ -0,0 +1,69 @@ +# BoxLite + +> Source: `docs/deploy/boxlite.mdx` +> Canonical URL: https://sandboxagent.dev/docs/deploy/boxlite +> Description: Run Sandbox Agent inside a BoxLite micro-VM. + +--- +BoxLite is a local-first micro-VM sandbox — no cloud account needed. +See [BoxLite docs](https://docs.boxlite.ai) for platform requirements (KVM on Linux, Apple Silicon on macOS). + +## Prerequisites + +- `@boxlite-ai/boxlite` installed (requires KVM or Apple Hypervisor) +- Docker (to build the base image) +- `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` + +## Base image + +Build a Docker image with Sandbox Agent pre-installed, then export it as an OCI layout +that BoxLite can load directly (BoxLite has its own image store separate from Docker): + +```dockerfile +FROM node:22-bookworm-slim +RUN apt-get update && apt-get install -y curl ca-certificates && rm -rf /var/lib/apt/lists/* +RUN curl -fsSL https://releases.rivet.dev/sandbox-agent/0.4.x/install.sh | sh +RUN sandbox-agent install-agent claude +RUN sandbox-agent install-agent codex +``` + +```bash +docker build -t sandbox-agent-boxlite . +mkdir -p oci-image +docker save sandbox-agent-boxlite | tar -xf - -C oci-image +``` + +## TypeScript example + +```typescript +import { SimpleBox } from "@boxlite-ai/boxlite"; +import { SandboxAgent } from "sandbox-agent"; + +const env: Record = {}; +if (process.env.ANTHROPIC_API_KEY) env.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; +if (process.env.OPENAI_API_KEY) env.OPENAI_API_KEY = process.env.OPENAI_API_KEY; + +const box = new SimpleBox({ + rootfsPath: "./oci-image", + env, + ports: [{ hostPort: 3000, guestPort: 3000 }], + diskSizeGb: 4, +}); + +await box.exec("sh", "-c", + "nohup sandbox-agent server --no-token --host 0.0.0.0 --port 3000 >/tmp/sandbox-agent.log 2>&1 &" +); + +const baseUrl = "http://localhost:3000"; +const sdk = await SandboxAgent.connect({ baseUrl }); + +const session = await sdk.createSession({ agent: "claude" }); +const off = session.onEvent((event) => { + console.log(event.sender, event.payload); +}); + +await session.prompt([{ type: "text", text: "Summarize this repository" }]); +off(); + +await box.stop(); +``` diff --git a/.agents/skills/sandbox-agent/references/deploy/cloudflare.md b/.agents/skills/sandbox-agent/references/deploy/cloudflare.md new file mode 100644 index 0000000..7e9faa5 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/deploy/cloudflare.md @@ -0,0 +1,188 @@ +# Cloudflare + +> Source: `docs/deploy/cloudflare.mdx` +> Canonical URL: https://sandboxagent.dev/docs/deploy/cloudflare +> Description: Deploy Sandbox Agent inside a Cloudflare Sandbox. + +--- +## Prerequisites + +- Cloudflare account with Workers paid plan +- Docker for local `wrangler dev` +- `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` + +Cloudflare Sandbox SDK is beta. See [Sandbox SDK docs](https://developers.cloudflare.com/sandbox/). + +## Quick start + +```bash +npm create cloudflare@latest -- my-sandbox --template=cloudflare/sandbox-sdk/examples/minimal +cd my-sandbox +``` + +## Dockerfile + +```dockerfile +FROM cloudflare/sandbox:0.7.0 + +RUN curl -fsSL https://releases.rivet.dev/sandbox-agent/0.4.x/install.sh | sh +RUN sandbox-agent install-agent claude && sandbox-agent install-agent codex + +EXPOSE 8000 +``` + +## TypeScript example (with provider) + +For standalone scripts, use the `cloudflare` provider: + +```bash +npm install sandbox-agent@0.4.x @cloudflare/sandbox +``` + +```typescript +import { SandboxAgent } from "sandbox-agent"; +import { cloudflare } from "sandbox-agent/cloudflare"; + +const sdk = await SandboxAgent.start({ + sandbox: cloudflare(), +}); + +try { + const session = await sdk.createSession({ agent: "codex" }); + const response = await session.prompt([ + { type: "text", text: "Summarize this repository" }, + ]); + console.log(response.stopReason); +} finally { + await sdk.destroySandbox(); +} +``` + +The `cloudflare` provider uses `containerFetch` under the hood, automatically stripping `AbortSignal` to avoid dropped streaming updates. + +## TypeScript example (Durable Objects) + +For Workers with Durable Objects, use `SandboxAgent.connect(...)` with a custom `fetch` backed by `sandbox.containerFetch(...)`: + +```typescript +import { getSandbox, type Sandbox } from "@cloudflare/sandbox"; +import { Hono } from "hono"; +import { SandboxAgent } from "sandbox-agent"; + +export { Sandbox } from "@cloudflare/sandbox"; + +type Bindings = { + Sandbox: DurableObjectNamespace; + ASSETS: Fetcher; + ANTHROPIC_API_KEY?: string; + OPENAI_API_KEY?: string; +}; + +const app = new Hono<{ Bindings: Bindings }>(); +const PORT = 8000; + +async function isServerRunning(sandbox: Sandbox): Promise { + try { + const result = await sandbox.exec(`curl -sf http://localhost:${PORT}/v1/health`); + return result.success; + } catch { + return false; + } +} + +async function getReadySandbox(name: string, env: Bindings): Promise { + const sandbox = getSandbox(env.Sandbox, name); + if (!(await isServerRunning(sandbox))) { + const envVars: Record = {}; + if (env.ANTHROPIC_API_KEY) envVars.ANTHROPIC_API_KEY = env.ANTHROPIC_API_KEY; + if (env.OPENAI_API_KEY) envVars.OPENAI_API_KEY = env.OPENAI_API_KEY; + await sandbox.setEnvVars(envVars); + await sandbox.startProcess(`sandbox-agent server --no-token --host 0.0.0.0 --port ${PORT}`); + } + return sandbox; +} + +app.post("/sandbox/:name/prompt", async (c) => { + const sandbox = await getReadySandbox(c.req.param("name"), c.env); + + const sdk = await SandboxAgent.connect({ + fetch: (input, init) => + sandbox.containerFetch( + input as Request | string | URL, + { + ...(init ?? {}), + // Avoid passing AbortSignal through containerFetch; it can drop streamed session updates. + signal: undefined, + }, + PORT, + ), + }); + + const session = await sdk.createSession({ agent: "codex" }); + const response = await session.prompt([{ type: "text", text: "Summarize this repository" }]); + await sdk.destroySession(session.id); + await sdk.dispose(); + + return c.json(response); +}); + +app.all("/sandbox/:name/proxy/*", async (c) => { + const sandbox = await getReadySandbox(c.req.param("name"), c.env); + const wildcard = c.req.param("*"); + const path = wildcard ? `/${wildcard}` : "/"; + const query = new URL(c.req.raw.url).search; + + return sandbox.containerFetch(new Request(`http://localhost${path}${query}`, c.req.raw), PORT); +}); + +app.all("*", (c) => c.env.ASSETS.fetch(c.req.raw)); + +export default app; +``` + +This keeps all Sandbox Agent calls inside the Cloudflare sandbox routing path and does not require a `baseUrl`. + +## Troubleshooting streaming updates + +If you only receive: +- the outbound prompt request +- the final `{ stopReason: "end_turn" }` response + +then the streamed update channel dropped. In Cloudflare sandbox paths, this is typically caused by forwarding `AbortSignal` from SDK fetch init into `containerFetch(...)`. + +Fix: + +```ts +const sdk = await SandboxAgent.connect({ + fetch: (input, init) => + sandbox.containerFetch( + input as Request | string | URL, + { + ...(init ?? {}), + // Avoid passing AbortSignal through containerFetch; it can drop streamed session updates. + signal: undefined, + }, + PORT, + ), +}); +``` + +This keeps prompt completion behavior the same, but restores streamed text/tool updates. + +## Local development + +```bash +npm run dev +``` + +Test health: + +```bash +curl http://localhost:8787/sandbox/demo/proxy/v1/health +``` + +## Production deployment + +```bash +wrangler deploy +``` diff --git a/.agents/skills/sandbox-agent/references/deploy/computesdk.md b/.agents/skills/sandbox-agent/references/deploy/computesdk.md new file mode 100644 index 0000000..5abe939 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/deploy/computesdk.md @@ -0,0 +1,83 @@ +# ComputeSDK + +> Source: `docs/deploy/computesdk.mdx` +> Canonical URL: https://sandboxagent.dev/docs/deploy/computesdk +> Description: Deploy Sandbox Agent using ComputeSDK's provider-agnostic sandbox API. + +--- +[ComputeSDK](https://computesdk.com) provides a unified interface for managing sandboxes across multiple providers. Write once, deploy anywhere by changing environment variables. + +## Prerequisites + +- `COMPUTESDK_API_KEY` from [console.computesdk.com](https://console.computesdk.com) +- Provider API key (one of: `E2B_API_KEY`, `DAYTONA_API_KEY`, `VERCEL_TOKEN`, `MODAL_TOKEN_ID` + `MODAL_TOKEN_SECRET`, `BLAXEL_API_KEY`, `CSB_API_KEY`) +- `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` + +## TypeScript example + +```bash +npm install sandbox-agent@0.4.x computesdk +``` + +```typescript +import { SandboxAgent } from "sandbox-agent"; +import { computesdk } from "sandbox-agent/computesdk"; + +const envs: Record = {}; +if (process.env.ANTHROPIC_API_KEY) envs.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; +if (process.env.OPENAI_API_KEY) envs.OPENAI_API_KEY = process.env.OPENAI_API_KEY; + +const sdk = await SandboxAgent.start({ + sandbox: computesdk({ + create: { + envs, + image: process.env.COMPUTESDK_IMAGE, + templateId: process.env.COMPUTESDK_TEMPLATE_ID, + }, + }), +}); + +try { + const session = await sdk.createSession({ agent: "claude" }); + const response = await session.prompt([ + { type: "text", text: "Summarize this repository" }, + ]); + console.log(response.stopReason); +} finally { + await sdk.destroySandbox(); +} +``` + +The `computesdk` provider handles sandbox creation, Sandbox Agent installation, agent setup, and server startup automatically. ComputeSDK routes to your configured provider behind the scenes. +The `create` option now forwards the full ComputeSDK sandbox-create payload, including provider-specific fields such as `image` and `templateId` when the selected provider supports them. + +Before calling `SandboxAgent.start()`, configure ComputeSDK with your provider: + +```typescript +import { compute } from "computesdk"; + +compute.setConfig({ + provider: "e2b", // or auto-detect via detectProvider() + computesdkApiKey: process.env.COMPUTESDK_API_KEY, +}); +``` + +## Supported providers + +ComputeSDK auto-detects your provider from environment variables: + +| Provider | Environment Variables | +|----------|----------------------| +| E2B | `E2B_API_KEY` | +| Daytona | `DAYTONA_API_KEY` | +| Vercel | `VERCEL_TOKEN` or `VERCEL_OIDC_TOKEN` | +| Modal | `MODAL_TOKEN_ID` + `MODAL_TOKEN_SECRET` | +| Blaxel | `BLAXEL_API_KEY` | +| CodeSandbox | `CSB_API_KEY` | + +## Notes + +- **Provider resolution**: Set `COMPUTESDK_PROVIDER` to force a specific provider, or let ComputeSDK auto-detect from API keys. +- `sandbox.runCommand(..., { background: true })` keeps the server running while your app continues. +- `sandbox.getUrl({ port })` returns a public URL for the sandbox port. +- Always destroy the sandbox when done to avoid leaking resources. diff --git a/.agents/skills/sandbox-agent/references/deploy/daytona.md b/.agents/skills/sandbox-agent/references/deploy/daytona.md new file mode 100644 index 0000000..d4509fa --- /dev/null +++ b/.agents/skills/sandbox-agent/references/deploy/daytona.md @@ -0,0 +1,70 @@ +# Daytona + +> Source: `docs/deploy/daytona.mdx` +> Canonical URL: https://sandboxagent.dev/docs/deploy/daytona +> Description: Run Sandbox Agent in a Daytona workspace. + +--- +Daytona Tier 3+ is required for access to common model provider endpoints. +See [Daytona network limits](https://www.daytona.io/docs/en/network-limits/). + +## Prerequisites + +- `DAYTONA_API_KEY` +- `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` + +## TypeScript example + +```bash +npm install sandbox-agent@0.4.x @daytonaio/sdk +``` + +```typescript +import { SandboxAgent } from "sandbox-agent"; +import { daytona } from "sandbox-agent/daytona"; + +const envVars: Record = {}; +if (process.env.ANTHROPIC_API_KEY) envVars.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; +if (process.env.OPENAI_API_KEY) envVars.OPENAI_API_KEY = process.env.OPENAI_API_KEY; + +const sdk = await SandboxAgent.start({ + sandbox: daytona({ + create: { envVars }, + }), +}); + +try { + const session = await sdk.createSession({ agent: "claude" }); + const response = await session.prompt([ + { type: "text", text: "Summarize this repository" }, + ]); + console.log(response.stopReason); +} finally { + await sdk.destroySandbox(); +} +``` + +The `daytona` provider uses the `rivetdev/sandbox-agent:0.4.2-full` image by default and starts the server automatically. + +## Using snapshots for faster startup + +```typescript +import { Daytona, Image } from "@daytonaio/sdk"; + +const daytona = new Daytona(); +const SNAPSHOT = "sandbox-agent-ready"; + +const hasSnapshot = await daytona.snapshot.get(SNAPSHOT).then(() => true, () => false); + +if (!hasSnapshot) { + await daytona.snapshot.create({ + name: SNAPSHOT, + image: Image.base("ubuntu:22.04").runCommands( + "apt-get update && apt-get install -y curl ca-certificates", + "curl -fsSL https://releases.rivet.dev/sandbox-agent/0.4.x/install.sh | sh", + "sandbox-agent install-agent claude", + "sandbox-agent install-agent codex", + ), + }); +} +``` diff --git a/.agents/skills/sandbox-agent/references/deploy/docker.md b/.agents/skills/sandbox-agent/references/deploy/docker.md new file mode 100644 index 0000000..d101ab4 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/deploy/docker.md @@ -0,0 +1,108 @@ +# Docker + +> Source: `docs/deploy/docker.mdx` +> Canonical URL: https://sandboxagent.dev/docs/deploy/docker +> Description: Build and run Sandbox Agent in a Docker container. + +--- +Docker is not recommended for production isolation of untrusted workloads. Use dedicated sandbox providers (E2B, Daytona, etc.) for stronger isolation. + +## Quick start + +Run the published full image with all supported agents pre-installed: + +```bash +docker run --rm -p 3000:3000 \ + -e ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" \ + -e OPENAI_API_KEY="$OPENAI_API_KEY" \ + rivetdev/sandbox-agent:0.4.2-full \ + server --no-token --host 0.0.0.0 --port 3000 +``` + +The `0.4.2-full` tag pins the exact version. The moving `full` tag is also published for contributors who want the latest full image. + +If you also want the desktop API inside the container, install desktop dependencies before starting the server: + +```bash +docker run --rm -p 3000:3000 \ + -e ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" \ + -e OPENAI_API_KEY="$OPENAI_API_KEY" \ + node:22-bookworm-slim sh -c "\ + apt-get update && \ + DEBIAN_FRONTEND=noninteractive apt-get install -y curl ca-certificates bash libstdc++6 && \ + rm -rf /var/lib/apt/lists/* && \ + curl -fsSL https://releases.rivet.dev/sandbox-agent/0.4.x/install.sh | sh && \ + sandbox-agent install desktop --yes && \ + sandbox-agent server --no-token --host 0.0.0.0 --port 3000" +``` + +In a Dockerfile: + +```dockerfile +RUN sandbox-agent install desktop --yes +``` + +## TypeScript with dockerode + +```typescript +import Docker from "dockerode"; +import { SandboxAgent } from "sandbox-agent"; + +const docker = new Docker(); +const PORT = 3000; + +const container = await docker.createContainer({ + Image: "rivetdev/sandbox-agent:0.4.2-full", + Cmd: ["server", "--no-token", "--host", "0.0.0.0", "--port", `${PORT}`], + Env: [ + `ANTHROPIC_API_KEY=${process.env.ANTHROPIC_API_KEY}`, + `OPENAI_API_KEY=${process.env.OPENAI_API_KEY}`, + `CODEX_API_KEY=${process.env.CODEX_API_KEY}`, + ].filter(Boolean), + ExposedPorts: { [`${PORT}/tcp`]: {} }, + HostConfig: { + AutoRemove: true, + PortBindings: { [`${PORT}/tcp`]: [{ HostPort: `${PORT}` }] }, + }, +}); + +await container.start(); + +const baseUrl = `http://127.0.0.1:${PORT}`; +const sdk = await SandboxAgent.connect({ baseUrl }); + +const session = await sdk.createSession({ agent: "codex" }); +await session.prompt([{ type: "text", text: "Summarize this repository." }]); +``` + +## Building a custom image with everything preinstalled + +If you need to extend your own base image, install Sandbox Agent and preinstall every supported agent in one step: + +```dockerfile +FROM node:22-bookworm-slim + +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash ca-certificates curl git && \ + rm -rf /var/lib/apt/lists/* + +RUN curl -fsSL https://releases.rivet.dev/sandbox-agent/0.4.x/install.sh | sh && \ + sandbox-agent install-agent --all + +RUN useradd -m -s /bin/bash sandbox +USER sandbox +WORKDIR /home/sandbox + +EXPOSE 2468 +ENTRYPOINT ["sandbox-agent"] +CMD ["server", "--host", "0.0.0.0", "--port", "2468"] +``` + +## Building from source + +```bash +docker build -f docker/release/linux-x86_64.Dockerfile -t sandbox-agent-build . +docker run --rm -v "$PWD/artifacts:/artifacts" sandbox-agent-build +``` + +Binary output: `./artifacts/sandbox-agent-x86_64-unknown-linux-musl`. diff --git a/.agents/skills/sandbox-agent/references/deploy/e2b.md b/.agents/skills/sandbox-agent/references/deploy/e2b.md new file mode 100644 index 0000000..d23e111 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/deploy/e2b.md @@ -0,0 +1,54 @@ +# E2B + +> Source: `docs/deploy/e2b.mdx` +> Canonical URL: https://sandboxagent.dev/docs/deploy/e2b +> Description: Deploy Sandbox Agent inside an E2B sandbox. + +--- +## Prerequisites + +- `E2B_API_KEY` +- `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` + +## TypeScript example + +```bash +npm install sandbox-agent@0.4.x @e2b/code-interpreter +``` + +```typescript +import { SandboxAgent } from "sandbox-agent"; +import { e2b } from "sandbox-agent/e2b"; + +const envs: Record = {}; +if (process.env.ANTHROPIC_API_KEY) envs.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; +if (process.env.OPENAI_API_KEY) envs.OPENAI_API_KEY = process.env.OPENAI_API_KEY; +const template = process.env.E2B_TEMPLATE; + +const sdk = await SandboxAgent.start({ + sandbox: e2b({ + template, + create: { envs }, + }), +}); + +try { + const session = await sdk.createSession({ agent: "claude" }); + const response = await session.prompt([ + { type: "text", text: "Summarize this repository" }, + ]); + console.log(response.stopReason); +} finally { + await sdk.destroySandbox(); +} +``` + +The `e2b` provider handles sandbox creation, Sandbox Agent installation, agent setup, and server startup automatically. Sandboxes pause by default instead of being deleted, and reconnecting with the same `sandboxId` resumes them automatically. + +Pass `template` when you want to start from a custom E2B template alias or template ID. E2B base-image selection happens when you build the template, then `sandbox-agent/e2b` uses that template at sandbox creation time. + +## Faster cold starts + +For faster startup, create a custom E2B template with Sandbox Agent and target agents pre-installed. +Build System 2.0 also lets you choose the template's base image in code. +See [E2B Custom Templates](https://e2b.dev/docs/sandbox-template) and [E2B Base Images](https://e2b.dev/docs/template/base-image). diff --git a/.agents/skills/sandbox-agent/references/deploy/local.md b/.agents/skills/sandbox-agent/references/deploy/local.md new file mode 100644 index 0000000..8578c11 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/deploy/local.md @@ -0,0 +1,71 @@ +# Local + +> Source: `docs/deploy/local.mdx` +> Canonical URL: https://sandboxagent.dev/docs/deploy/local +> Description: Run Sandbox Agent locally for development. + +--- +For local development, run Sandbox Agent directly on your machine. + +## With the CLI + +```bash +# Install +curl -fsSL https://releases.rivet.dev/sandbox-agent/0.4.x/install.sh | sh + +# Run +sandbox-agent server --no-token --host 127.0.0.1 --port 2468 +``` + +Or with npm/Bun: + +#### npx + +```bash +npx @sandbox-agent/cli@0.4.x server --no-token --host 127.0.0.1 --port 2468 +``` + +#### bunx + +```bash +bunx @sandbox-agent/cli@0.4.x server --no-token --host 127.0.0.1 --port 2468 +``` + +## With the TypeScript SDK + +The SDK can spawn and manage the server as a subprocess using the `local` provider: + +```typescript +import { SandboxAgent } from "sandbox-agent"; +import { local } from "sandbox-agent/local"; + +const sdk = await SandboxAgent.start({ + sandbox: local(), +}); + +const session = await sdk.createSession({ + agent: "claude", +}); + +await session.prompt([ + { type: "text", text: "Summarize this repository." }, +]); + +await sdk.destroySandbox(); +``` + +This starts the server on an available local port and connects automatically. + +Pass options to customize the local provider: + +```typescript +const sdk = await SandboxAgent.start({ + sandbox: local({ + port: 3000, + log: "inherit", + env: { + ANTHROPIC_API_KEY: process.env.MY_ANTHROPIC_KEY, + }, + }), +}); +``` diff --git a/.agents/skills/sandbox-agent/references/deploy/modal.md b/.agents/skills/sandbox-agent/references/deploy/modal.md new file mode 100644 index 0000000..ddb741a --- /dev/null +++ b/.agents/skills/sandbox-agent/references/deploy/modal.md @@ -0,0 +1,57 @@ +# Modal + +> Source: `docs/deploy/modal.mdx` +> Canonical URL: https://sandboxagent.dev/docs/deploy/modal +> Description: Deploy Sandbox Agent inside a Modal sandbox. + +--- +## Prerequisites + +- `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET` from [modal.com/settings](https://modal.com/settings) +- `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` + +## TypeScript example + +```bash +npm install sandbox-agent@0.4.x modal +``` + +```typescript +import { SandboxAgent } from "sandbox-agent"; +import { modal } from "sandbox-agent/modal"; + +const secrets: Record = {}; +if (process.env.ANTHROPIC_API_KEY) secrets.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; +if (process.env.OPENAI_API_KEY) secrets.OPENAI_API_KEY = process.env.OPENAI_API_KEY; +const baseImage = process.env.MODAL_BASE_IMAGE ?? "node:22-slim"; + +const sdk = await SandboxAgent.start({ + sandbox: modal({ + image: baseImage, + create: { secrets }, + }), +}); + +try { + const session = await sdk.createSession({ agent: "claude" }); + const response = await session.prompt([ + { type: "text", text: "Summarize this repository" }, + ]); + console.log(response.stopReason); +} finally { + await sdk.destroySandbox(); +} +``` + +The `modal` provider handles app creation, image building, sandbox provisioning, agent installation, server startup, and tunnel networking automatically. +Set `image` to change the base Docker image before Sandbox Agent and its agent binaries are layered on top. You can also pass a prebuilt Modal `Image` object. + +## Faster cold starts + +Modal caches image layers, so the Dockerfile commands that install `curl` and `sandbox-agent` only run on the first build. Subsequent sandbox creates reuse the cached image. + +## Notes + +- Modal sandboxes use [gVisor](https://gvisor.dev/) for strong isolation. +- Ports are exposed via encrypted tunnels (`encryptedPorts`). The provider uses `sb.tunnels()` to get the public HTTPS URL. +- Environment variables (API keys) are passed as Modal [Secrets](https://modal.com/docs/guide/secrets) for security. diff --git a/.agents/skills/sandbox-agent/references/deploy/vercel.md b/.agents/skills/sandbox-agent/references/deploy/vercel.md new file mode 100644 index 0000000..641aa42 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/deploy/vercel.md @@ -0,0 +1,52 @@ +# Vercel + +> Source: `docs/deploy/vercel.mdx` +> Canonical URL: https://sandboxagent.dev/docs/deploy/vercel +> Description: Deploy Sandbox Agent inside a Vercel Sandbox. + +--- +## Prerequisites + +- `VERCEL_OIDC_TOKEN` or `VERCEL_ACCESS_TOKEN` +- `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` + +## TypeScript example + +```bash +npm install sandbox-agent@0.4.x @vercel/sandbox +``` + +```typescript +import { SandboxAgent } from "sandbox-agent"; +import { vercel } from "sandbox-agent/vercel"; + +const env: Record = {}; +if (process.env.ANTHROPIC_API_KEY) env.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; +if (process.env.OPENAI_API_KEY) env.OPENAI_API_KEY = process.env.OPENAI_API_KEY; + +const sdk = await SandboxAgent.start({ + sandbox: vercel({ + create: { + runtime: "node24", + env, + }, + }), +}); + +try { + const session = await sdk.createSession({ agent: "claude" }); + const response = await session.prompt([ + { type: "text", text: "Summarize this repository" }, + ]); + console.log(response.stopReason); +} finally { + await sdk.destroySandbox(); +} +``` + +The `vercel` provider handles sandbox creation, Sandbox Agent installation, agent setup, and server startup automatically. + +## Authentication + +Vercel Sandboxes support OIDC token auth (recommended) and access-token auth. +See [Vercel Sandbox docs](https://vercel.com/docs/functions/sandbox). diff --git a/.agents/skills/sandbox-agent/references/file-system.md b/.agents/skills/sandbox-agent/references/file-system.md new file mode 100644 index 0000000..40952f1 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/file-system.md @@ -0,0 +1,144 @@ +# File System + +> Source: `docs/file-system.mdx` +> Canonical URL: https://sandboxagent.dev/docs/file-system +> Description: Read, write, and manage files inside the sandbox. + +--- +The filesystem API lets you list, read, write, move, and delete files inside the sandbox, plus upload tar archives in batch. + +## Path resolution + +- Absolute paths are used as-is. +- Relative paths resolve from the server process working directory. +- Requests that attempt to escape allowed roots are rejected by the server. + +## List entries + +```ts TypeScript +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", +}); + +const entries = await sdk.listFsEntries({ + path: "./workspace", +}); + +console.log(entries); +``` + +```bash cURL +curl -X GET "http://127.0.0.1:2468/v1/fs/entries?path=./workspace" +``` + +## Read and write files + +`PUT /v1/fs/file` writes raw bytes. `GET /v1/fs/file` returns raw bytes. + +```ts TypeScript +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", +}); + +await sdk.writeFsFile({ path: "./notes.txt" }, "hello"); + +const bytes = await sdk.readFsFile({ path: "./notes.txt" }); +const text = new TextDecoder().decode(bytes); + +console.log(text); +``` + +```bash cURL +curl -X PUT "http://127.0.0.1:2468/v1/fs/file?path=./notes.txt" \ + --data-binary "hello" + +curl -X GET "http://127.0.0.1:2468/v1/fs/file?path=./notes.txt" \ + --output ./notes.txt +``` + +## Create directories + +```ts TypeScript +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", +}); + +await sdk.mkdirFs({ path: "./data" }); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/fs/mkdir?path=./data" +``` + +## Move, delete, and stat + +```ts TypeScript +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", +}); + +await sdk.moveFs({ + from: "./notes.txt", + to: "./notes-old.txt", + overwrite: true, +}); + +const stat = await sdk.statFs({ path: "./notes-old.txt" }); +await sdk.deleteFsEntry({ path: "./notes-old.txt" }); + +console.log(stat); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/fs/move" \ + -H "Content-Type: application/json" \ + -d '{"from":"./notes.txt","to":"./notes-old.txt","overwrite":true}' + +curl -X GET "http://127.0.0.1:2468/v1/fs/stat?path=./notes-old.txt" + +curl -X DELETE "http://127.0.0.1:2468/v1/fs/entry?path=./notes-old.txt" +``` + +## Batch upload (tar) + +Batch upload accepts `application/x-tar` and extracts into the destination directory. + +```ts TypeScript +import { SandboxAgent } from "sandbox-agent"; +import fs from "node:fs"; +import path from "node:path"; +import tar from "tar"; + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", +}); + +const archivePath = path.join(process.cwd(), "skills.tar"); +await tar.c({ + cwd: "./skills", + file: archivePath, +}, ["."]); + +const tarBuffer = await fs.promises.readFile(archivePath); +const result = await sdk.uploadFsBatch(tarBuffer, { + path: "./skills", +}); + +console.log(result); +``` + +```bash cURL +tar -cf skills.tar -C ./skills . + +curl -X POST "http://127.0.0.1:2468/v1/fs/upload-batch?path=./skills" \ + -H "Content-Type: application/x-tar" \ + --data-binary @skills.tar +``` diff --git a/.agents/skills/sandbox-agent/references/inspector.md b/.agents/skills/sandbox-agent/references/inspector.md new file mode 100644 index 0000000..edc6b72 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/inspector.md @@ -0,0 +1,66 @@ +# Inspector + +> Source: `docs/inspector.mdx` +> Canonical URL: https://sandboxagent.dev/docs/inspector +> Description: Debug and inspect agent sessions with the Inspector UI. + +--- +The Inspector is a web UI for inspecting Sandbox Agent sessions. Use it to view events, inspect payloads, and troubleshoot behavior. + +![Sandbox Agent Inspector](https://sandboxagent.dev/docs/images/inspector.png) + +## Open the Inspector + +The Inspector is served at `/ui/` on your Sandbox Agent server. +For example, if your server runs at `http://localhost:2468`, open `http://localhost:2468/ui/`. + +You can also generate a pre-filled Inspector URL from the SDK: + +```typescript +import { buildInspectorUrl } from "sandbox-agent"; + +const url = buildInspectorUrl({ + baseUrl: "http://127.0.0.1:2468", +}); + +console.log(url); +// http://127.0.0.1:2468/ui/ +``` + +## Features + +- Session list +- Event stream view +- Event JSON inspector +- Prompt testing +- Request/response debugging +- Interactive permission prompts (approve, always-allow, or reject tool-use requests) +- Desktop panel for status, remediation, start/stop, and screenshot refresh +- Process management (create, stop, kill, delete, view logs) +- Interactive PTY terminal for tty processes +- One-shot command execution + +## When to use + +- Development: validate session behavior quickly +- Debugging: inspect raw event payloads +- Integration work: compare UI behavior with SDK/API calls + +## Process terminal + +The Inspector includes an embedded Ghostty-based terminal for interactive tty +processes. The UI uses the SDK's high-level `connectProcessTerminal(...)` +wrapper via the shared `@sandbox-agent/react` `ProcessTerminal` component. + +## Desktop panel + +The `Desktop` panel shows the current desktop runtime state, missing dependencies, +the suggested install command, last error details, process/log paths, and the +latest captured screenshot. + +Use it to: + +- Check whether desktop dependencies are installed +- Start or stop the managed desktop runtime +- Refresh desktop status +- Capture a fresh screenshot on demand diff --git a/.agents/skills/sandbox-agent/references/llm-credentials.md b/.agents/skills/sandbox-agent/references/llm-credentials.md new file mode 100644 index 0000000..379c1f8 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/llm-credentials.md @@ -0,0 +1,241 @@ +# LLM Credentials + +> Source: `docs/llm-credentials.mdx` +> Canonical URL: https://sandboxagent.dev/docs/llm-credentials +> Description: Strategies for providing LLM provider credentials to agents. + +--- +Sandbox Agent needs LLM provider credentials (Anthropic, OpenAI, etc.) to run agent sessions. + +## Configuration + +Pass credentials via `spawn.env` when starting a sandbox. Each call to `SandboxAgent.start()` can use different credentials: + +```typescript +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.start({ + spawn: { + env: { + ANTHROPIC_API_KEY: "sk-ant-...", + OPENAI_API_KEY: "sk-...", + }, + }, +}); +``` + +Each agent requires credentials from a specific provider. Sandbox Agent checks environment variables (including those passed via `spawn.env`) and host config files: + +| Agent | Provider | Environment variables | Config files | +|-------|----------|----------------------|--------------| +| Claude Code | Anthropic | `ANTHROPIC_API_KEY`, `CLAUDE_API_KEY` | `~/.claude.json`, `~/.claude/.credentials.json` | +| Amp | Anthropic | `ANTHROPIC_API_KEY`, `CLAUDE_API_KEY` | `~/.amp/config.json` | +| Codex | OpenAI | `OPENAI_API_KEY`, `CODEX_API_KEY` | `~/.codex/auth.json` | +| OpenCode | Anthropic or OpenAI | `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` | `~/.local/share/opencode/auth.json` | +| Mock | None | - | - | + +## Credential strategies + +LLM credentials are passed into the sandbox as environment variables. The agent and everything inside the sandbox has access to the token, so it's important to choose the right strategy for how you provision and scope these credentials. + +| Strategy | Who pays | Cost attribution | Best for | +|----------|----------|-----------------|----------| +| **Per-tenant gateway** (recommended) | Your organization, billed back per tenant | Per-tenant keys with budgets | Multi-tenant SaaS, usage-based billing | +| **Bring your own key** | Each user (usage-based) | Per-user by default | Dev environments, internal tools | +| **Shared API key** | Your organization | None (single bill) | Single-tenant apps, internal platforms | +| **Personal subscription** | Each user (existing subscription) | Per-user by default | Local dev, internal tools where users have Claude or Codex subscriptions | + +### Per-tenant gateway (recommended) + +Route LLM traffic through a gateway that mints per-tenant API keys, each with its own spend tracking and budget limits. + +```mermaid +graph LR + B[Your Backend] -->|tenant key| S[Sandbox] + S -->|LLM requests| G[Gateway] + G -->|scoped key| P[LLM Provider] +``` + +Your backend issues a scoped key per tenant, then passes it to the sandbox. This is the typical pattern when using sandbox providers (E2B, Daytona, Docker). + +```typescript expandable +import { SandboxAgent } from "sandbox-agent"; + +async function createTenantSandbox(tenantId: string) { + // Issue a scoped key for this tenant via OpenRouter + const res = await fetch("https://openrouter.ai/api/v1/keys", { + method: "POST", + headers: { + Authorization: `Bearer ${process.env.OPENROUTER_PROVISIONING_KEY}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + name: `tenant-${tenantId}`, + limit: 50, + limitResetType: "monthly", + }), + }); + const { key } = await res.json(); + + // Start a sandbox with the tenant's scoped key + const sdk = await SandboxAgent.start({ + spawn: { + env: { + OPENAI_API_KEY: key, // OpenRouter uses OpenAI-compatible endpoints + }, + }, + }); + + const session = await sdk.createSession({ + agent: "claude", + sessionInit: { cwd: "/workspace" }, + }); + + return { sdk, session }; +} +``` + +#### Security + +Recommended for multi-tenant applications. Each tenant gets a scoped key with its own budget, so exfiltration only exposes that tenant's allowance. + +#### Use cases + +- **Multi-tenant SaaS**: per-tenant spend tracking and budget limits +- **Production apps**: exposed to end users who need isolated credentials +- **Usage-based billing**: each tenant pays for their own consumption + +#### Choosing a gateway + +#### OpenRouter provisioned keys + +Managed service, zero infrastructure. [OpenRouter](https://openrouter.ai/docs/features/provisioning-api-keys) provides per-tenant API keys with spend tracking and budget limits via their Provisioning API. Pass the tenant key to Sandbox Agent as `OPENAI_API_KEY` (OpenRouter uses OpenAI-compatible endpoints). + +```bash +# Create a key for a tenant with a $50/month budget +curl https://openrouter.ai/api/v1/keys \ + -H "Authorization: Bearer $PROVISIONING_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "tenant-acme", + "limit": 50, + "limitResetType": "monthly" + }' +``` + +Easiest to set up but not open-source. See [OpenRouter pricing](https://openrouter.ai/docs/framework/pricing) for details. + +#### LiteLLM proxy + +Self-hosted, open-source (MIT). [LiteLLM](https://github.com/BerriAI/litellm) is an OpenAI-compatible proxy with hierarchical budgets (org, team, user, key), virtual keys, and spend tracking. Requires Python + PostgreSQL. + +```bash +# Create a team (tenant) with a $500 budget +curl http://litellm:4000/team/new \ + -H "Authorization: Bearer $LITELLM_MASTER_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "team_alias": "tenant-acme", + "max_budget": 500 + }' + +# Generate a key for that team +curl http://litellm:4000/key/generate \ + -H "Authorization: Bearer $LITELLM_MASTER_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "team_id": "team-abc123", + "max_budget": 100 + }' +``` + +Full control with no vendor lock-in. Organization-level features require an enterprise license. + +#### Portkey gateway + +Self-hosted, open-source (Apache 2.0). [Portkey](https://github.com/Portkey-AI/gateway) is a lightweight OpenAI-compatible gateway supporting 200+ providers. Single binary, no database required. Create virtual keys with per-tenant budget limits and pass them to Sandbox Agent. + +Lightest operational footprint of the self-hosted options. Observability and analytics require the managed platform or your own tooling. + +To bill tenants for LLM usage, use [Stripe token billing](https://docs.stripe.com/billing/token-billing) (integrates natively with OpenRouter) or query your gateway's spend API and feed usage into your billing system. + +### Bring your own key + +Each user provides their own API key. Users are billed directly by the LLM provider with no additional infrastructure needed. + +Pass the user's key via `spawn.env`: + +```typescript +const sdk = await SandboxAgent.start({ + spawn: { + env: { + ANTHROPIC_API_KEY: userProvidedKey, + }, + }, +}); +``` + +#### Security + +API keys are typically long-lived. The key is visible to the agent and anything running inside the sandbox, so exfiltration is possible. This is usually acceptable for developer-facing tools where the user owns the key. + +#### Use cases + +- **Developer tools**: each user manages their own API key +- **Internal platforms**: users already have LLM provider accounts +- **Per-user billing**: no extra infrastructure needed + +### Shared credentials + +A single organization-wide API key is used for all sessions. All token usage appears on one bill with no per-user or per-tenant cost attribution. + +```typescript +const sdk = await SandboxAgent.start({ + spawn: { + env: { + ANTHROPIC_API_KEY: process.env.ORG_ANTHROPIC_KEY!, + OPENAI_API_KEY: process.env.ORG_OPENAI_KEY!, + }, + }, +}); +``` + +If you need to track or limit spend per tenant, use a per-tenant gateway instead. + +#### Security + +Not recommended for anything other than internal tooling. A single exfiltrated key exposes your organization's entire LLM budget. If you need org-paid credentials for external users, use a per-tenant gateway with scoped keys instead. + +#### Use cases + +- **Single-tenant apps**: small number of users, one bill +- **Prototyping**: cost attribution not needed yet +- **Simplicity over security**: acceptable when exfiltration risk is low + +### Personal subscription + +If the user is signed into Claude Code or Codex on the host machine, Sandbox Agent automatically picks up their OAuth tokens. No configuration is needed. + +#### Remote sandboxes + +Extract credentials locally and pass them to a remote sandbox via `spawn.env`: + +```bash +$ sandbox-agent credentials extract-env +ANTHROPIC_API_KEY=sk-ant-... +CLAUDE_API_KEY=sk-ant-... +OPENAI_API_KEY=sk-... +CODEX_API_KEY=sk-... +``` + +Use `-e` to prefix with `export` for shell sourcing. + +#### Security + +Personal subscriptions use OAuth tokens with a limited lifespan. These are the same credentials used when running an agent normally on the host. If a token is exfiltrated from the sandbox, the exposure window is short. + +#### Use cases + +- **Local development**: users are already signed into Claude Code or Codex +- **Internal tools**: every user has their own subscription +- **Prototyping**: no key management needed diff --git a/.agents/skills/sandbox-agent/references/manage-sessions.md b/.agents/skills/sandbox-agent/references/manage-sessions.md new file mode 100644 index 0000000..ec0ff5e --- /dev/null +++ b/.agents/skills/sandbox-agent/references/manage-sessions.md @@ -0,0 +1,260 @@ +# Manage Sessions + +> Source: `docs/manage-sessions.mdx` +> Canonical URL: https://sandboxagent.dev/docs/manage-sessions +> Description: Persist and replay agent transcripts across connections. + +--- +Sandbox Agent stores sessions in memory only. When the server restarts or the sandbox is destroyed, all session data is lost. It's your responsibility to persist events to your own database. + +## Recommended approach + +1. Store events to your database as they arrive +2. On reconnect, get the last event's `sequence` and pass it as `offset` +3. The API returns events where `sequence > offset` + +This prevents duplicate writes and lets you recover from disconnects. + +## Receiving Events + +Two ways to receive events: streaming (recommended) or polling. + +### Streaming + +Use streaming for real-time events with automatic reconnection support. + +```typescript +import { SandboxAgentClient } from "sandbox-agent"; + +const client = new SandboxAgentClient({ + baseUrl: "http://127.0.0.1:2468", + agent: "mock", +}); + +// Get offset from last stored event (0 returns all events) +const lastEvent = await db.getLastEvent("my-session"); +const offset = lastEvent?.sequence ?? 0; + +// Stream from where you left off +for await (const event of client.streamEvents("my-session", { offset })) { + await db.insertEvent("my-session", event); +} +``` + +### Polling + +If you can't use streaming, poll the events endpoint: + +```typescript +const lastEvent = await db.getLastEvent("my-session"); +let offset = lastEvent?.sequence ?? 0; + +while (true) { + const { events } = await client.getEvents("my-session", { + offset, + limit: 100 + }); + + for (const event of events) { + await db.insertEvent("my-session", event); + offset = event.sequence; + } + + await sleep(1000); +} +``` + +## Database options + +Choose where to persist events based on your requirements. For most use cases, we recommend Rivet Actors. + +| | Durable | Real-time | Multiplayer | Scaling | Throughput | Complexity | +|---------|:-------:|:---------:|:-----------:|---------|------------|------------| +| Rivet Actors | ✓ | ✓ | ✓ | Auto-sharded, one actor per session | Millions of concurrent sessions | Zero infrastructure | +| PostgreSQL | ✓ | | | Manual sharding | Connection pool limited | Connection pools, migrations | +| Redis | | ✓ | | Redis Cluster | High, in-memory | Memory management, Sentinel for failover | + +### Rivet Actors + +For production workloads, [Rivet Actors](https://rivet.gg) provide a managed solution for: + +- **Persistent state**: Events survive crashes and restarts +- **Real-time streaming**: Built-in WebSocket support for clients +- **Horizontal scaling**: Run thousands of concurrent sessions +- **Observability**: Built-in logging and metrics + +#### Actor + +```typescript +import { actor } from "rivetkit"; +import { Daytona } from "@daytonaio/sdk"; +import { SandboxAgent, SandboxAgentClient, AgentEvent } from "sandbox-agent"; + +interface CodingSessionState { + sandboxId: string; + baseUrl: string; + sessionId: string; + events: AgentEvent[]; +} + +interface CodingSessionVars { + client: SandboxAgentClient; +} + +const daytona = new Daytona(); + +const codingSession = actor({ + createState: async (): Promise => { + const sandbox = await daytona.create({ + snapshot: "sandbox-agent-ready", + envVars: { + ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY, + OPENAI_API_KEY: process.env.OPENAI_API_KEY, + }, + autoStopInterval: 0, + }); + + await sandbox.process.executeCommand( + "nohup sandbox-agent server --no-token --host 0.0.0.0 --port 3000 &" + ); + + const baseUrl = (await sandbox.getSignedPreviewUrl(3000)).url; + const sessionId = crypto.randomUUID(); + + return { + sandboxId: sandbox.id, + baseUrl, + sessionId, + events: [], + }; + }, + + createVars: async (c): Promise => { + const client = new SandboxAgentClient({ + baseUrl: c.state.baseUrl, + agent: "mock", +}); + await client.createSession(c.state.sessionId, { agent: "claude" }); + return { client }; + }, + + onDestroy: async (c) => { + const sandbox = await daytona.get(c.state.sandboxId); + await sandbox.delete(); + }, + + run: async (c) => { + for await (const event of c.vars.client.streamEvents(c.state.sessionId)) { + c.state.events.push(event); + c.broadcast("agentEvent", event); + } + }, + + actions: { + postMessage: async (c, message: string) => { + await c.vars.client.postMessage(c.state.sessionId, message); + }, + + getTranscript: (c) => c.state.events, + }, +}); +``` + +#### Client + +```typescript TypeScript +import { createClient } from "rivetkit/client"; + +const client = createClient(); +const session = client.codingSession.getOrCreate(["my-session"]); + +const conn = session.connect(); +conn.on("agentEvent", (event) => { + console.log(event.type, event.data); +}); + +await conn.postMessage("Create a new React component for user profiles"); + +const transcript = await conn.getTranscript(); +``` + +```typescript React +import { createRivetKit } from "@rivetkit/react"; + +const { useActor } = createRivetKit(); + +function CodingSession() { + const [messages, setMessages] = useState([]); + const session = useActor({ name: "codingSession", key: ["my-session"] }); + + session.useEvent("agentEvent", (event) => { + setMessages((prev) => [...prev, event]); + }); + + const sendPrompt = async (prompt: string) => { + await session.connection?.postMessage(prompt); + }; + + return ( +
+ {messages.map((msg, i) => ( +
{JSON.stringify(msg)}
+ ))} + +
+ ); +} +``` + +### PostgreSQL + +```sql +CREATE TABLE agent_events ( + event_id TEXT PRIMARY KEY, + session_id TEXT NOT NULL, + native_session_id TEXT, + sequence INTEGER NOT NULL, + time TIMESTAMPTZ NOT NULL, + type TEXT NOT NULL, + source TEXT NOT NULL, + synthetic BOOLEAN NOT NULL DEFAULT FALSE, + data JSONB NOT NULL, + UNIQUE(session_id, sequence) +); + +CREATE INDEX idx_events_session ON agent_events(session_id, sequence); +``` + +### Redis + +```typescript +// Append event to list +await redis.rpush(`session:${sessionId}`, JSON.stringify(event)); + +// Get events from offset +const events = await redis.lrange(`session:${sessionId}`, offset, -1); +``` + +## Handling disconnects + +The event stream may disconnect due to network issues. Handle reconnection gracefully: + +```typescript +async function streamWithRetry(sessionId: string) { + while (true) { + try { + const lastEvent = await db.getLastEvent(sessionId); + const offset = lastEvent?.sequence ?? 0; + + for await (const event of client.streamEvents(sessionId, { offset })) { + await db.insertEvent(sessionId, event); + } + } catch (error) { + console.error("Stream disconnected, reconnecting...", error); + await sleep(1000); + } + } +} +``` diff --git a/.agents/skills/sandbox-agent/references/mcp-config.md b/.agents/skills/sandbox-agent/references/mcp-config.md new file mode 100644 index 0000000..6ef5db3 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/mcp-config.md @@ -0,0 +1,82 @@ +# MCP + +> Source: `docs/mcp-config.mdx` +> Canonical URL: https://sandboxagent.dev/docs/mcp-config +> Description: Configure MCP servers for agent sessions. + +--- +MCP (Model Context Protocol) servers extend agents with tools and external context. + +## Configuring MCP servers + +The HTTP config endpoints let you store/retrieve MCP server configs by directory + name. + +```ts +// Create MCP config +await sdk.setMcpConfig( + { + directory: "/workspace", + mcpName: "github", + }, + { + type: "remote", + url: "https://example.com/mcp", + }, +); + +// Create a session using the configured MCP servers +const session = await sdk.createSession({ + agent: "claude", + cwd: "/workspace", +}); + +await session.prompt([ + { type: "text", text: "Use available MCP servers to help with this task." }, +]); + +// List MCP configs +const config = await sdk.getMcpConfig({ + directory: "/workspace", + mcpName: "github", +}); + +console.log(config.type); + +// Delete MCP config +await sdk.deleteMcpConfig({ + directory: "/workspace", + mcpName: "github", +}); +``` + +## Config fields + +### Local server + +| Field | Description | +|---|---| +| `type` | `local` | +| `command` | executable path | +| `args` | array of CLI args | +| `env` | environment variable map | +| `cwd` | working directory | +| `enabled` | enable/disable server | +| `timeoutMs` | timeout override | + +### Remote server + +| Field | Description | +|---|---| +| `type` | `remote` | +| `url` | MCP server URL | +| `transport` | `http` or `sse` | +| `headers` | static headers map | +| `bearerTokenEnvVar` | env var name to inject in auth header | +| `envHeaders` | header name to env var map | +| `oauth` | optional OAuth config object | +| `enabled` | enable/disable server | +| `timeoutMs` | timeout override | + +## Custom MCP servers + +To bundle and upload your own MCP server into the sandbox, see [Custom Tools](/custom-tools). diff --git a/.agents/skills/sandbox-agent/references/multiplayer.md b/.agents/skills/sandbox-agent/references/multiplayer.md new file mode 100644 index 0000000..79f0272 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/multiplayer.md @@ -0,0 +1,144 @@ +# Multiplayer + +> Source: `docs/multiplayer.mdx` +> Canonical URL: https://sandboxagent.dev/docs/multiplayer +> Description: Use Rivet Actors to coordinate shared sessions. + +--- +For multiplayer orchestration, use [Rivet Actors](https://rivet.dev/docs/actors). + +Recommended model: + +- One actor per collaborative workspace/thread. +- The actor owns Sandbox Agent session lifecycle and persistence. +- Clients connect to the actor and receive realtime broadcasts. + +Use [actor keys](https://rivet.dev/docs/actors/keys) to map each workspace to one actor, [events](https://rivet.dev/docs/actors/events) for realtime updates, and [lifecycle hooks](https://rivet.dev/docs/actors/lifecycle) for cleanup. + +## Example + +```ts Actor (server) +import { actor, setup } from "rivetkit"; +import { SandboxAgent, type SessionPersistDriver, type SessionRecord, type SessionEvent, type ListPageRequest, type ListPage, type ListEventsRequest } from "sandbox-agent"; + +interface RivetPersistData { sessions: Record; events: Record; } +type RivetPersistState = { _sandboxAgentPersist: RivetPersistData }; + +class RivetSessionPersistDriver implements SessionPersistDriver { + private readonly stateKey: string; + private readonly ctx: { state: Record }; + constructor(ctx: { state: Record }, options: { stateKey?: string } = {}) { + this.ctx = ctx; + this.stateKey = options.stateKey ?? "_sandboxAgentPersist"; + if (!this.ctx.state[this.stateKey]) { + this.ctx.state[this.stateKey] = { sessions: {}, events: {} }; + } + } + private get data(): RivetPersistData { return this.ctx.state[this.stateKey] as RivetPersistData; } + async getSession(id: string) { const s = this.data.sessions[id]; return s ? { ...s } : undefined; } + async listSessions(request: ListPageRequest = {}): Promise> { + const sorted = Object.values(this.data.sessions).sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id)); + const offset = Number(request.cursor ?? 0); + const limit = request.limit ?? 100; + const slice = sorted.slice(offset, offset + limit); + return { items: slice, nextCursor: offset + slice.length < sorted.length ? String(offset + slice.length) : undefined }; + } + async updateSession(session: SessionRecord) { this.data.sessions[session.id] = { ...session }; if (!this.data.events[session.id]) this.data.events[session.id] = []; } + async listEvents(request: ListEventsRequest): Promise> { + const all = [...(this.data.events[request.sessionId] ?? [])].sort((a, b) => a.eventIndex - b.eventIndex || a.id.localeCompare(b.id)); + const offset = Number(request.cursor ?? 0); + const limit = request.limit ?? 100; + const slice = all.slice(offset, offset + limit); + return { items: slice, nextCursor: offset + slice.length < all.length ? String(offset + slice.length) : undefined }; + } + async insertEvent(sessionId: string, event: SessionEvent) { const events = this.data.events[sessionId] ?? []; events.push({ ...event, payload: JSON.parse(JSON.stringify(event.payload)) }); this.data.events[sessionId] = events; } +} + +type WorkspaceState = RivetPersistState & { + sandboxId: string; + baseUrl: string; +}; + +export const workspace = actor({ + createState: async () => { + return { + sandboxId: "sbx_123", + baseUrl: "http://127.0.0.1:2468", + } satisfies Partial; + }, + + createVars: async (c) => { + const persist = new RivetSessionPersistDriver(c); + const sdk = await SandboxAgent.connect({ + baseUrl: c.state.baseUrl, + persist, + }); + + const session = await sdk.resumeOrCreateSession({ id: "default", agent: "codex" }); + + const unsubscribe = session.onEvent((event) => { + c.broadcast("session.event", event); + }); + + return { sdk, session, unsubscribe }; + }, + + actions: { + getSessionInfo: (c) => ({ + workspaceId: c.key[0], + sandboxId: c.state.sandboxId, + }), + + prompt: async (c, input: { userId: string; text: string }) => { + c.broadcast("chat.user", { + userId: input.userId, + text: input.text, + createdAt: Date.now(), + }); + + await c.vars.session.prompt([{ type: "text", text: input.text }]); + }, + }, + + onSleep: async (c) => { + c.vars.unsubscribe?.(); + await c.vars.sdk.dispose(); + }, +}); + +export const registry = setup({ + use: { workspace }, +}); +``` + +```ts Client (browser) +import { createClient } from "rivetkit/client"; +import type { registry } from "./actors"; + +const client = createClient({ + endpoint: process.env.NEXT_PUBLIC_RIVET_ENDPOINT!, +}); + +const workspaceId = "workspace-42"; +const room = client.workspace.getOrCreate([workspaceId]); +const conn = room.connect(); + +conn.on("chat.user", (event) => { + console.log("user message", event); +}); + +conn.on("session.event", (event) => { + console.log("sandbox event", event); +}); + +await conn.prompt({ + userId: "user-123", + text: "Propose a refactor plan for auth middleware.", +}); +``` + +## Notes + +- Keep sandbox calls actor-only. Browser clients should not call Sandbox Agent directly. +- Copy the Rivet persist driver from the example above into your project so session history persists in actor state. +- For client connection patterns, see [Rivet JavaScript client](https://rivet.dev/docs/clients/javascript). diff --git a/.agents/skills/sandbox-agent/references/observability.md b/.agents/skills/sandbox-agent/references/observability.md new file mode 100644 index 0000000..bc5852f --- /dev/null +++ b/.agents/skills/sandbox-agent/references/observability.md @@ -0,0 +1,65 @@ +# Observability + +> Source: `docs/observability.mdx` +> Canonical URL: https://sandboxagent.dev/docs/observability +> Description: Track session activity with OpenTelemetry. + +--- +Use OpenTelemetry to instrument session traffic, then ship telemetry to your collector/backend. + +## Common collectors and backends + +- [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) +- [Jaeger](https://www.jaegertracing.io/) +- [Grafana Tempo](https://grafana.com/oss/tempo/) +- [Honeycomb](https://www.honeycomb.io/) +- [Datadog APM](https://docs.datadoghq.com/tracing/) + +## Example: trace a prompt round-trip + +Wrap `session.prompt()` in a span to measure the full round-trip, then log individual events as span events. + +Assumes your OTEL provider/exporter is already configured. + +```ts +import { trace } from "@opentelemetry/api"; +import { SandboxAgent } from "sandbox-agent"; + +const tracer = trace.getTracer("my-app/sandbox-agent"); + +const sdk = await SandboxAgent.connect({ + baseUrl: process.env.SANDBOX_URL!, +}); + +const session = await sdk.createSession({ agent: "mock" }); + +// Log each event as an OTEL span event on the active span +const unsubscribe = session.onEvent((event) => { + const activeSpan = trace.getActiveSpan(); + if (!activeSpan) return; + + activeSpan.addEvent("session.event", { + "sandbox.sender": event.sender, + "sandbox.event_index": event.eventIndex, + }); +}); + +// The span covers the full prompt round-trip +await tracer.startActiveSpan("sandbox_agent.prompt", async (span) => { + span.setAttribute("sandbox.session_id", session.id); + + try { + const result = await session.prompt([ + { type: "text", text: "Summarize this repository." }, + ]); + span.setAttribute("sandbox.stop_reason", result.stopReason); + } catch (error) { + span.recordException(error as Error); + throw error; + } finally { + span.end(); + } +}); + +unsubscribe(); +``` diff --git a/.agents/skills/sandbox-agent/references/opencode-compatibility.md b/.agents/skills/sandbox-agent/references/opencode-compatibility.md new file mode 100644 index 0000000..568b1b3 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/opencode-compatibility.md @@ -0,0 +1,123 @@ +# OpenCode Compatibility + +> Source: `docs/opencode-compatibility.mdx` +> Canonical URL: https://sandboxagent.dev/docs/opencode-compatibility +> Description: Connect OpenCode clients, SDKs, and web UI to Sandbox Agent. + +--- +**Experimental**: OpenCode SDK/UI compatibility may change. + +Sandbox Agent exposes an OpenCode-compatible API at `/opencode`. + +## Why use OpenCode clients with Sandbox Agent? + +- OpenCode CLI (`opencode attach`) +- OpenCode web UI +- OpenCode TypeScript SDK (`@opencode-ai/sdk`) + +## Quick start + +### OpenCode CLI / TUI + +```bash +sandbox-agent opencode --port 2468 --no-token +``` + +Or start server + attach manually: + +```bash +sandbox-agent server --no-token --host 127.0.0.1 --port 2468 +opencode attach http://localhost:2468/opencode +``` + +With authentication enabled: + +```bash +sandbox-agent server --token "$SANDBOX_TOKEN" --host 127.0.0.1 --port 2468 +opencode attach http://localhost:2468/opencode --password "$SANDBOX_TOKEN" +``` + +### OpenCode web UI + +### Start Sandbox Agent with CORS + +```bash +sandbox-agent server --no-token --host 127.0.0.1 --port 2468 --cors-allow-origin http://127.0.0.1:5173 +``` + +### Run OpenCode web app + +```bash +git clone https://github.com/anomalyco/opencode +cd opencode/packages/app +export VITE_OPENCODE_SERVER_HOST=127.0.0.1 +export VITE_OPENCODE_SERVER_PORT=2468 +bun install +bun run dev -- --host 127.0.0.1 --port 5173 +``` + +### Open UI + +Visit `http://127.0.0.1:5173/`. + +### OpenCode SDK + +```typescript +import { createOpencodeClient } from "@opencode-ai/sdk"; + +const client = createOpencodeClient({ + baseUrl: "http://localhost:2468/opencode", +}); + +const session = await client.session.create(); + +await client.session.promptAsync({ + path: { id: session.data.id }, + body: { + parts: [{ type: "text", text: "Hello, write a hello world script" }], + }, +}); + +const events = await client.event.subscribe({}); +for await (const event of events.stream) { + console.log(event); +} +``` + +## Notes + +- API base path: `/opencode` +- If server auth is enabled, pass bearer auth (or `--password` in OpenCode CLI) +- For browser UIs, configure CORS with `--cors-allow-origin` +- Provider selector currently exposes compatible providers (`mock`, `amp`, `claude`, `codex`) +- Provider/model metadata for compatibility endpoints is normalized and may differ from native OpenCode grouping +- Optional proxy: set `OPENCODE_COMPAT_PROXY_URL` to forward selected endpoints to native OpenCode + +## Endpoint coverage + +#### Endpoint Status Table + +| Endpoint | Status | Notes | +|---|---|---| +| `GET /event` | ✓ | Session/message updates (SSE) | +| `GET /global/event` | ✓ | GlobalEvent-wrapped stream | +| `GET /session` | ✓ | Session list | +| `POST /session` | ✓ | Create session | +| `GET /session/{id}` | ✓ | Session details | +| `POST /session/{id}/message` | ✓ | Send message | +| `GET /session/{id}/message` | ✓ | Session messages | +| `GET /permission` | ✓ | Pending permissions | +| `POST /permission/{id}/reply` | ✓ | Permission reply | +| `GET /question` | ✓ | Pending questions | +| `POST /question/{id}/reply` | ✓ | Question reply | +| `GET /provider` | ✓ | Provider metadata | +| `GET /command` | ↔ | Proxied when `OPENCODE_COMPAT_PROXY_URL` is set; otherwise stub | +| `GET /config` | ↔ | Proxied when set; otherwise stub | +| `PATCH /config` | ↔ | Proxied when set; otherwise local compatibility behavior | +| `GET /global/config` | ↔ | Proxied when set; otherwise stub | +| `PATCH /global/config` | ↔ | Proxied when set; otherwise local compatibility behavior | +| `/tui/*` | ↔ | Proxied when set; otherwise local compatibility behavior | +| `GET /agent` | − | Agent list | +| *other endpoints* | − | Empty/stub responses | + +✓ Functional ↔ Proxied optional − Stubbed diff --git a/.agents/skills/sandbox-agent/references/orchestration-architecture.md b/.agents/skills/sandbox-agent/references/orchestration-architecture.md new file mode 100644 index 0000000..2c58005 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/orchestration-architecture.md @@ -0,0 +1,44 @@ +# Orchestration Architecture + +> Source: `docs/orchestration-architecture.mdx` +> Canonical URL: https://sandboxagent.dev/docs/orchestration-architecture +> Description: Production topology, backend requirements, and session persistence. + +--- +This page covers production topology and backend requirements. Read [Architecture](/architecture) first for an overview of how the server, SDK, and agent processes fit together. + +## Suggested Topology + +Run the SDK on your backend, then call it from your frontend. + +This extra hop is recommended because it keeps auth/token logic on the backend and makes persistence simpler. + +```mermaid placement="top-right" +flowchart LR + BROWSER["Browser"] + subgraph BACKEND["Your backend"] + direction TB + SDK["Sandbox Agent SDK"] + end + subgraph SANDBOX_SIMPLE["Sandbox"] + SERVER_SIMPLE["Sandbox Agent server"] + end + + BROWSER --> BACKEND + BACKEND --> SDK --> SERVER_SIMPLE +``` + +### Backend requirements + +Your backend layer needs to handle: + +- **Long-running connections**: prompts can take minutes. +- **Session affinity**: follow-up messages must reach the same session. +- **State between requests**: session metadata and event history must persist across requests. +- **Graceful recovery**: sessions should resume after backend restarts. + +We recommend [Rivet](https://rivet.dev) over serverless because actors natively support the long-lived connections, session routing, and state persistence that agent workloads require. + +## Session persistence + +For storage driver options and replay behavior, see [Persisting Sessions](/session-persistence). diff --git a/.agents/skills/sandbox-agent/references/processes.md b/.agents/skills/sandbox-agent/references/processes.md new file mode 100644 index 0000000..2ba78a2 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/processes.md @@ -0,0 +1,242 @@ +# Processes + +> Source: `docs/processes.mdx` +> Canonical URL: https://sandboxagent.dev/docs/processes +> Description: Run commands and manage long-lived processes inside the sandbox. + +--- +The process API supports: + +- **One-shot execution** — run a command to completion and capture stdout, stderr, and exit code +- **Managed processes** — spawn, list, stop, kill, and delete long-lived processes +- **Log streaming** — fetch buffered logs or follow live output +- **Terminals** — full PTY support with bidirectional WebSocket I/O +- **Configurable limits** — control concurrency, timeouts, and buffer sizes per runtime + +## Run a command + +Execute a command to completion and get its output. + +```ts TypeScript +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", +}); + +const result = await sdk.runProcess({ + command: "ls", + args: ["-la", "/workspace"], +}); + +console.log(result.exitCode); // 0 +console.log(result.stdout); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"ls","args":["-la","/workspace"]}' +``` + +You can set a timeout and cap output size: + +```ts TypeScript +const result = await sdk.runProcess({ + command: "make", + args: ["build"], + timeoutMs: 60000, + maxOutputBytes: 1048576, +}); + +if (result.timedOut) { + console.log("Build timed out"); +} +if (result.stdoutTruncated) { + console.log("Output was truncated"); +} +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/run" \ + -H "Content-Type: application/json" \ + -d '{"command":"make","args":["build"],"timeoutMs":60000,"maxOutputBytes":1048576}' +``` + +## Managed processes + +Create a long-lived process that you can interact with, monitor, and stop later. + +### Create + +```ts TypeScript +const proc = await sdk.createProcess({ + command: "node", + args: ["server.js"], + cwd: "/workspace", +}); + +console.log(proc.id, proc.pid); // proc_1, 12345 +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes" \ + -H "Content-Type: application/json" \ + -d '{"command":"node","args":["server.js"],"cwd":"/workspace"}' +``` + +### List and get + +```ts TypeScript +const { processes } = await sdk.listProcesses(); + +for (const p of processes) { + console.log(p.id, p.command, p.status); +} + +const proc = await sdk.getProcess("proc_1"); +``` + +```bash cURL +curl "http://127.0.0.1:2468/v1/processes" + +curl "http://127.0.0.1:2468/v1/processes/proc_1" +``` + +### Stop, kill, and delete + +```ts TypeScript +// SIGTERM with optional wait +await sdk.stopProcess("proc_1", { waitMs: 5000 }); + +// SIGKILL +await sdk.killProcess("proc_1", { waitMs: 1000 }); + +// Remove exited process record +await sdk.deleteProcess("proc_1"); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/proc_1/stop?waitMs=5000" + +curl -X POST "http://127.0.0.1:2468/v1/processes/proc_1/kill?waitMs=1000" + +curl -X DELETE "http://127.0.0.1:2468/v1/processes/proc_1" +``` + +## Logs + +### Fetch buffered logs + +```ts TypeScript +const logs = await sdk.getProcessLogs("proc_1", { + tail: 50, + stream: "combined", +}); + +for (const entry of logs.entries) { + console.log(entry.stream, atob(entry.data)); +} +``` + +```bash cURL +curl "http://127.0.0.1:2468/v1/processes/proc_1/logs?tail=50&stream=combined" +``` + +### Follow logs + +Stream log entries in real time. The subscription replays buffered entries first, then streams new output as it arrives. + +```ts TypeScript +const sub = await sdk.followProcessLogs("proc_1", (entry) => { + console.log(entry.stream, atob(entry.data)); +}); + +// Later, stop following +sub.close(); +await sub.closed; +``` + +## Terminals + +Create a process with `tty: true` to allocate a pseudo-terminal, then connect via WebSocket for full bidirectional I/O. + +```ts TypeScript +const proc = await sdk.createProcess({ + command: "bash", + tty: true, +}); +``` + +### Write input + +```ts TypeScript +await sdk.sendProcessInput("proc_1", { + data: "echo hello\n", + encoding: "utf8", +}); +``` + +```bash cURL +curl -X POST "http://127.0.0.1:2468/v1/processes/proc_1/input" \ + -H "Content-Type: application/json" \ + -d '{"data":"echo hello\n","encoding":"utf8"}' +``` + +### Connect to a terminal + +Use `ProcessTerminalSession` unless you need direct frame access. + +```ts TypeScript +const terminal = sdk.connectProcessTerminal("proc_1"); + +terminal.onReady(() => { + terminal.resize({ cols: 120, rows: 40 }); + terminal.sendInput("ls\n"); +}); + +terminal.onData((bytes) => { + process.stdout.write(new TextDecoder().decode(bytes)); +}); + +terminal.onExit((status) => { + console.log("exit:", status.exitCode); +}); + +terminal.onError((error) => { + console.error(error instanceof Error ? error.message : error.message); +}); + +terminal.onClose(() => { + console.log("terminal closed"); +}); +``` + +Since the browser WebSocket API cannot send custom headers, the endpoint accepts an `access_token` query parameter for authentication. The SDK handles this automatically. + +### Browser terminal emulators + +The terminal session works with any browser terminal emulator like ghostty-web or xterm.js. For a drop-in React terminal, see [React Components](/react-components). + +## Configuration + +Adjust runtime limits like max concurrent processes, timeouts, and buffer sizes. + +```ts TypeScript +const config = await sdk.getProcessConfig(); +console.log(config); + +await sdk.setProcessConfig({ + ...config, + maxConcurrentProcesses: 32, + defaultRunTimeoutMs: 60000, +}); +``` + +```bash cURL +curl "http://127.0.0.1:2468/v1/processes/config" + +curl -X POST "http://127.0.0.1:2468/v1/processes/config" \ + -H "Content-Type: application/json" \ + -d '{"maxConcurrentProcesses":32,"defaultRunTimeoutMs":60000,"maxRunTimeoutMs":300000,"maxOutputBytes":1048576,"maxLogBytesPerProcess":10485760,"maxInputBytesPerRequest":65536}' +``` diff --git a/.agents/skills/sandbox-agent/references/quickstart.md b/.agents/skills/sandbox-agent/references/quickstart.md new file mode 100644 index 0000000..5d9fdc3 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/quickstart.md @@ -0,0 +1,289 @@ +# Quickstart + +> Source: `docs/quickstart.mdx` +> Canonical URL: https://sandboxagent.dev/docs/quickstart +> Description: Start the server and send your first message. + +--- +### Install skill (optional) + +#### npx + +```bash +npx skills add rivet-dev/skills -s sandbox-agent +``` + +#### bunx + +```bash +bunx skills add rivet-dev/skills -s sandbox-agent +``` + +### Set environment variables + +Each coding agent requires API keys to connect to their respective LLM providers. + +#### Local shell + +```bash +export ANTHROPIC_API_KEY="sk-ant-..." +export OPENAI_API_KEY="sk-..." +``` + +#### E2B + +```typescript +import { Sandbox } from "@e2b/code-interpreter"; + +const envs: Record = {}; +if (process.env.ANTHROPIC_API_KEY) envs.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; +if (process.env.OPENAI_API_KEY) envs.OPENAI_API_KEY = process.env.OPENAI_API_KEY; + +const sandbox = await Sandbox.create({ envs }); +``` + +#### Daytona + +```typescript +import { Daytona } from "@daytonaio/sdk"; + +const envVars: Record = {}; +if (process.env.ANTHROPIC_API_KEY) envVars.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; +if (process.env.OPENAI_API_KEY) envVars.OPENAI_API_KEY = process.env.OPENAI_API_KEY; + +const daytona = new Daytona(); +const sandbox = await daytona.create({ + snapshot: "sandbox-agent-ready", + envVars, +}); +``` + +#### Docker + +```bash +docker run -p 2468:2468 \ + -e ANTHROPIC_API_KEY="sk-ant-..." \ + -e OPENAI_API_KEY="sk-..." \ + rivetdev/sandbox-agent:0.4.2-full \ + server --no-token --host 0.0.0.0 --port 2468 +``` + +#### Extracting API keys from current machine + +Use `sandbox-agent credentials extract-env --export` to extract your existing API keys (Anthropic, OpenAI, etc.) from local Claude Code or Codex config files. + +#### Testing without API keys + +Use the `mock` agent for SDK and integration testing without provider credentials. + +#### Multi-tenant and per-user billing + +For per-tenant token tracking, budget enforcement, or usage-based billing, see [LLM Credentials](/llm-credentials) for gateway options like OpenRouter, LiteLLM, and Portkey. + +### Run the server + +#### curl + +Install and run the binary directly. + +```bash +curl -fsSL https://releases.rivet.dev/sandbox-agent/0.4.x/install.sh | sh +sandbox-agent server --no-token --host 0.0.0.0 --port 2468 +``` + +#### npx + +Run without installing globally. + +```bash +npx @sandbox-agent/cli@0.4.x server --no-token --host 0.0.0.0 --port 2468 +``` + +#### bunx + +Run without installing globally. + +```bash +bunx @sandbox-agent/cli@0.4.x server --no-token --host 0.0.0.0 --port 2468 +``` + +#### npm i -g + +Install globally, then run. + +```bash +npm install -g @sandbox-agent/cli@0.4.x +sandbox-agent server --no-token --host 0.0.0.0 --port 2468 +``` + +#### bun add -g + +Install globally, then run. + +```bash +bun add -g @sandbox-agent/cli@0.4.x +# Allow Bun to run postinstall scripts for native binaries (required for SandboxAgent.start()). +bun pm -g trust @sandbox-agent/cli-linux-x64 @sandbox-agent/cli-linux-arm64 @sandbox-agent/cli-darwin-arm64 @sandbox-agent/cli-darwin-x64 @sandbox-agent/cli-win32-x64 +sandbox-agent server --no-token --host 0.0.0.0 --port 2468 +``` + +#### Node.js (local) + +For local development, use `SandboxAgent.start()` to spawn and manage the server as a subprocess. + +```bash +npm install sandbox-agent@0.4.x +``` + +```typescript +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.start(); +``` + +#### Bun (local) + +For local development, use `SandboxAgent.start()` to spawn and manage the server as a subprocess. + +```bash +bun add sandbox-agent@0.4.x +# Allow Bun to run postinstall scripts for native binaries (required for SandboxAgent.start()). +bun pm trust @sandbox-agent/cli-linux-x64 @sandbox-agent/cli-linux-arm64 @sandbox-agent/cli-darwin-arm64 @sandbox-agent/cli-darwin-x64 @sandbox-agent/cli-win32-x64 +``` + +```typescript +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.start(); +``` + +#### Build from source + +If you're running from source instead of the installed CLI. + +```bash +cargo run -p sandbox-agent -- server --no-token --host 0.0.0.0 --port 2468 +``` + +Binding to `0.0.0.0` allows the server to accept connections from any network interface, which is required when running inside a sandbox where clients connect remotely. + +#### Configuring token + +Tokens are usually not required. Most sandbox providers (E2B, Daytona, etc.) already secure networking at the infrastructure layer. + +If you expose the server publicly, use `--token "$SANDBOX_TOKEN"` to require authentication: + +```bash +sandbox-agent server --token "$SANDBOX_TOKEN" --host 0.0.0.0 --port 2468 +``` + +Then pass the token when connecting: + +#### TypeScript + +```typescript +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://your-server:2468", + token: process.env.SANDBOX_TOKEN, +}); +``` + +#### curl + +```bash +curl "http://your-server:2468/v1/health" \ + -H "Authorization: Bearer $SANDBOX_TOKEN" +``` + +#### CLI + +```bash +sandbox-agent --token "$SANDBOX_TOKEN" api agents list \ + --endpoint http://your-server:2468 +``` + +#### CORS + +If you're calling the server from a browser, see the [CORS configuration guide](/cors). + +### Install agents (optional) + +To preinstall agents: + +```bash +sandbox-agent install-agent --all +``` + +If agents are not installed up front, they are lazily installed when creating a session. + +### Install desktop dependencies (optional, Linux only) + +If you want to use `/v1/desktop/*`, install the desktop runtime packages first: + +```bash +sandbox-agent install desktop --yes +``` + +Then use `GET /v1/desktop/status` or `sdk.getDesktopStatus()` to verify the runtime is ready before calling desktop screenshot or input APIs. + +### Create a session + +```typescript +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", +}); + +const session = await sdk.createSession({ + agent: "claude", + sessionInit: { + cwd: "/", + mcpServers: [], + }, +}); + +console.log(session.id); +``` + +### Send a message + +```typescript +const result = await session.prompt([ + { type: "text", text: "Summarize the repository and suggest next steps." }, +]); + +console.log(result.stopReason); +``` + +### Read events + +```typescript +const off = session.onEvent((event) => { + console.log(event.sender, event.payload); +}); + +const page = await sdk.getEvents({ + sessionId: session.id, + limit: 50, +}); + +console.log(page.items.length); +off(); +``` + +### Test with Inspector + +Open the Inspector UI at `/ui/` on your server (for example, `http://localhost:2468/ui/`) to inspect sessions and events in a GUI. + +![Sandbox Agent Inspector](https://sandboxagent.dev/docs/images/inspector.png) + +## Next steps + +- [Session Persistence](/session-persistence) — Configure in-memory, Rivet Actor state, IndexedDB, SQLite, and Postgres persistence. + +- [Deploy to a Sandbox](/deploy/local) — Deploy your agent to E2B, Daytona, Docker, Vercel, or Cloudflare. + +- [SDK Overview](/sdk-overview) — Use the latest TypeScript SDK API. diff --git a/.agents/skills/sandbox-agent/references/react-components.md b/.agents/skills/sandbox-agent/references/react-components.md new file mode 100644 index 0000000..d2d5b9c --- /dev/null +++ b/.agents/skills/sandbox-agent/references/react-components.md @@ -0,0 +1,246 @@ +# React Components + +> Source: `docs/react-components.mdx` +> Canonical URL: https://sandboxagent.dev/docs/react-components +> Description: Drop-in React components for Sandbox Agent frontends. + +--- +`@sandbox-agent/react` exposes small React components built on top of the `sandbox-agent` SDK. + +Current exports: + +- `AgentConversation` for a combined transcript + composer surface +- `ProcessTerminal` for attaching to a running tty process +- `AgentTranscript` for rendering session/message timelines without bundling any styles +- `ChatComposer` for a reusable prompt input/send surface +- `useTranscriptVirtualizer` for wiring large transcript lists to a scroll container + +## Install + +```bash +npm install @sandbox-agent/react@0.4.x +``` + +## Full example + +This example connects to a running Sandbox Agent server, starts a tty shell, renders `ProcessTerminal`, and cleans up the process when the component unmounts. + +```tsx TerminalPane.tsx expandable highlight={5,32-36,71} +"use client"; + +import { useEffect, useState } from "react"; +import { SandboxAgent } from "sandbox-agent"; +import { ProcessTerminal } from "@sandbox-agent/react"; + +export default function TerminalPane() { + const [client, setClient] = useState(null); + const [processId, setProcessId] = useState(null); + const [error, setError] = useState(null); + + useEffect(() => { + let cancelled = false; + let sdk: SandboxAgent | null = null; + let createdProcessId: string | null = null; + + const cleanup = async () => { + if (!sdk || !createdProcessId) { + return; + } + + await sdk.killProcess(createdProcessId, { waitMs: 1_000 }).catch(() => {}); + await sdk.deleteProcess(createdProcessId).catch(() => {}); + }; + + const start = async () => { + try { + sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", + }); + + const process = await sdk.createProcess({ + command: "sh", + interactive: true, + tty: true, + }); + + if (cancelled) { + createdProcessId = process.id; + await cleanup(); + await sdk.dispose(); + return; + } + + createdProcessId = process.id; + setClient(sdk); + setProcessId(process.id); + } catch (err) { + const message = err instanceof Error ? err.message : "Failed to start terminal."; + setError(message); + } + }; + + void start(); + + return () => { + cancelled = true; + void cleanup(); + void sdk?.dispose(); + }; + }, []); + + if (error) { + return
{error}
; + } + + if (!client || !processId) { + return
Starting terminal...
; + } + + return ; +} +``` + +## Component + +`ProcessTerminal` attaches to a running tty process. + +- `client`: a `SandboxAgent` client +- `processId`: the process to attach to +- `height`, `style`, `terminalStyle`: optional layout overrides +- `onExit`, `onError`: optional lifecycle callbacks + +See [Processes](/processes) for the lower-level terminal APIs. + +## Headless transcript + +`AgentTranscript` is intentionally unstyled. It follows the common headless React pattern used by libraries like Radix, Headless UI, and React Aria: behavior lives in the component, while styling stays in your app through `className`, slot-level `classNames`, and `data-*` state attributes on the rendered DOM. + +```tsx TranscriptPane.tsx +import { + AgentTranscript, + type AgentTranscriptClassNames, + type TranscriptEntry, +} from "@sandbox-agent/react"; + +const transcriptClasses: Partial = { + root: "transcript", + message: "transcript-message", + messageContent: "transcript-message-content", + toolGroupContainer: "transcript-tools", + toolGroupHeader: "transcript-tools-header", + toolItem: "transcript-tool-item", + toolItemHeader: "transcript-tool-item-header", + toolItemBody: "transcript-tool-item-body", + divider: "transcript-divider", + dividerText: "transcript-divider-text", + error: "transcript-error", +}; + +export function TranscriptPane({ entries }: { entries: TranscriptEntry[] }) { + return ( +
{entry.text}
} + renderInlinePendingIndicator={() => ...} + renderToolGroupIcon={() => Events} + renderChevron={(expanded) => {expanded ? "Hide" : "Show"}} + /> + ); +} +``` + +```css +.transcript { + display: grid; + gap: 12px; +} + +.transcript [data-slot="message"][data-variant="user"] .transcript-message-content { + background: #161616; + color: white; +} + +.transcript [data-slot="message"][data-variant="assistant"] .transcript-message-content { + background: #f4f4f0; + color: #161616; +} + +.transcript [data-slot="tool-item"][data-failed="true"] { + border-color: #d33; +} + +.transcript [data-slot="tool-item-header"][data-expanded="true"] { + background: rgba(0, 0, 0, 0.06); +} +``` + +`AgentTranscript` accepts `TranscriptEntry[]`, which matches the Inspector timeline shape: + +- `message` entries render user/assistant text +- `tool` entries render expandable tool input/output sections +- `reasoning` entries render expandable reasoning blocks +- `meta` entries render status rows or expandable metadata details + +Useful props: + +- `className`: root class hook +- `classNames`: slot-level class hooks for styling from outside the package +- `scrollRef` + `virtualize`: opt into TanStack Virtual against an external scroll container +- `renderMessageText`: custom text or markdown renderer +- `renderToolItemIcon`, `renderToolGroupIcon`, `renderChevron`, `renderEventLinkContent`: presentation overrides +- `renderInlinePendingIndicator`, `renderThinkingState`: loading/thinking UI overrides +- `isDividerEntry`, `canOpenEvent`, `getToolGroupSummary`: behavior overrides for grouping and labels + +## Transcript virtualization hook + +`useTranscriptVirtualizer` exposes the same TanStack Virtual behavior used by `AgentTranscript` when `virtualize` is enabled. + +- Pass the grouped transcript rows you want to virtualize +- Pass a `scrollRef` that points at the actual scrollable element +- Use it when you need transcript-aware virtualization outside the stock `AgentTranscript` renderer + +## Composer and conversation + +`ChatComposer` is the headless message input. `AgentConversation` composes `AgentTranscript` and `ChatComposer` so apps can reuse the transcript/composer pairing without pulling in Inspector session chrome. + +```tsx ConversationPane.tsx +import { AgentConversation, type TranscriptEntry } from "@sandbox-agent/react"; + +export function ConversationPane({ + entries, + message, + onMessageChange, + onSubmit, +}: { + entries: TranscriptEntry[]; + message: string; + onMessageChange: (value: string) => void; + onSubmit: () => void; +}) { + return ( + Start the conversation.} + transcriptProps={{ + renderMessageText: (entry) =>
{entry.text}
, + }} + composerProps={{ + message, + onMessageChange, + onSubmit, + placeholder: "Send a message...", + }} + /> + ); +} +``` + +Useful `ChatComposer` props: + +- `className` and `classNames` for external styling +- `inputRef` to manage focus or autoresize from the consumer +- `textareaProps` for lower-level textarea behavior +- `allowEmptySubmit` when the submit action is valid without draft text, such as a stop button + +Use `transcriptProps` and `composerProps` when you want the shared composition but still need custom rendering or behavior. Use `transcriptClassNames` and `composerClassNames` when you want styling hooks for each subcomponent. diff --git a/.agents/skills/sandbox-agent/references/sdk-overview.md b/.agents/skills/sandbox-agent/references/sdk-overview.md new file mode 100644 index 0000000..2ba8370 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/sdk-overview.md @@ -0,0 +1,279 @@ +# SDK Overview + +> Source: `docs/sdk-overview.mdx` +> Canonical URL: https://sandboxagent.dev/docs/sdk-overview +> Description: Use the TypeScript SDK to manage Sandbox Agent sessions and APIs. + +--- +The TypeScript SDK is centered on `sandbox-agent` and its `SandboxAgent` class. + +## Install + +#### npm + +```bash +npm install sandbox-agent@0.4.x +``` + +#### bun + +```bash +bun add sandbox-agent@0.4.x +# Allow Bun to run postinstall scripts for native binaries (required for SandboxAgent.start()). +bun pm trust @sandbox-agent/cli-linux-x64 @sandbox-agent/cli-linux-arm64 @sandbox-agent/cli-darwin-arm64 @sandbox-agent/cli-darwin-x64 @sandbox-agent/cli-win32-x64 +``` + +## Optional React components + +```bash +npm install @sandbox-agent/react@0.4.x +``` + +## Create a client + +```ts +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", +}); +``` + +`SandboxAgent.connect(...)` now waits for `/v1/health` by default before other SDK requests proceed. To disable that gate, pass `waitForHealth: false`. To keep the default gate but fail after a bounded wait, pass `waitForHealth: { timeoutMs: 120_000 }`. To cancel the startup wait early, pass `signal: abortController.signal`. + +With a custom fetch handler (for example, proxying requests inside Workers): + +```ts +const sdk = await SandboxAgent.connect({ + fetch: (input, init) => customFetch(input, init), +}); +``` + +With an abort signal for the startup health gate: + +```ts +const controller = new AbortController(); + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", + signal: controller.signal, +}); + +controller.abort(); +``` + +With persistence (see [Persisting Sessions](/session-persistence) for driver options): + +```ts +import { SandboxAgent, InMemorySessionPersistDriver } from "sandbox-agent"; + +const persist = new InMemorySessionPersistDriver(); + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", + persist, +}); +``` + +Local spawn with a sandbox provider: + +```ts +import { SandboxAgent } from "sandbox-agent"; +import { local } from "sandbox-agent/local"; + +const sdk = await SandboxAgent.start({ + sandbox: local(), +}); + +// sdk.sandboxId — prefixed provider ID (e.g. "local/127.0.0.1:2468") + +await sdk.destroySandbox(); // provider-defined cleanup + disposes client +``` + +`SandboxAgent.start(...)` requires a `sandbox` provider. Built-in providers: + +| Import | Provider | +|--------|----------| +| `sandbox-agent/local` | Local subprocess | +| `sandbox-agent/docker` | Docker container | +| `sandbox-agent/e2b` | E2B sandbox | +| `sandbox-agent/daytona` | Daytona workspace | +| `sandbox-agent/agentcomputer` | Agent Computer managed worker | +| `sandbox-agent/vercel` | Vercel Sandbox | +| `sandbox-agent/cloudflare` | Cloudflare Sandbox | + +Use `sdk.dispose()` to disconnect without changing sandbox state, `sdk.pauseSandbox()` for graceful suspension when supported, or `sdk.killSandbox()` for permanent deletion. + +## Session flow + +```ts +const session = await sdk.createSession({ + agent: "mock", + cwd: "/", +}); + +const prompt = await session.prompt([ + { type: "text", text: "Summarize this repository." }, +]); + +console.log(prompt.stopReason); +``` + +Load and destroy: + +```ts +const restored = await sdk.resumeSession(session.id); +await restored.prompt([{ type: "text", text: "Continue from previous context." }]); + +await sdk.destroySession(restored.id); +``` + +## Session configuration + +Set model, mode, or thought level at creation or on an existing session: + +```ts +const session = await sdk.createSession({ + agent: "codex", + model: "gpt-5.3-codex", +}); + +await session.setModel("gpt-5.2-codex"); +await session.setMode("auto"); + +const options = await session.getConfigOptions(); +const modes = await session.getModes(); +``` + +Handle permission requests from agents that ask before executing tools: + +```ts +const claude = await sdk.createSession({ + agent: "claude", + mode: "default", +}); + +claude.onPermissionRequest((request) => { + void claude.respondPermission(request.id, "once"); +}); +``` + +See [Agent Sessions](/agent-sessions) for full details on config options and error handling. + +## Events + +Subscribe to live events: + +```ts +const unsubscribe = session.onEvent((event) => { + console.log(event.eventIndex, event.sender, event.payload); +}); + +await session.prompt([{ type: "text", text: "Give me a short summary." }]); +unsubscribe(); +``` + +Fetch persisted events: + +```ts +const page = await sdk.getEvents({ + sessionId: session.id, + limit: 100, +}); + +console.log(page.items.length); +``` + +## Control-plane and HTTP helpers + +```ts +const health = await sdk.getHealth(); +const agents = await sdk.listAgents(); +await sdk.installAgent("codex", { reinstall: true }); + +const entries = await sdk.listFsEntries({ path: "." }); +const writeResult = await sdk.writeFsFile({ path: "./hello.txt" }, "hello"); + +console.log(health.status, agents.agents.length, entries.length, writeResult.path); +``` + +## Desktop API + +The SDK also wraps the desktop host/runtime HTTP API. + +Install desktop dependencies first on Linux hosts: + +```bash +sandbox-agent install desktop --yes +``` + +Then query status, surface remediation if needed, and start the runtime: + +```ts +const status = await sdk.getDesktopStatus(); + +if (status.state === "install_required") { + console.log(status.installCommand); +} + +const started = await sdk.startDesktop({ + width: 1440, + height: 900, + dpi: 96, +}); + +const screenshot = await sdk.takeDesktopScreenshot(); +const displayInfo = await sdk.getDesktopDisplayInfo(); + +await sdk.moveDesktopMouse({ x: 400, y: 300 }); +await sdk.clickDesktop({ x: 400, y: 300, button: "left", clickCount: 1 }); +await sdk.typeDesktopText({ text: "hello world", delayMs: 10 }); +await sdk.pressDesktopKey({ key: "ctrl+l" }); + +await sdk.stopDesktop(); +``` + +Screenshot helpers return `Uint8Array` PNG bytes. The SDK does not attempt to install OS packages remotely; callers should surface `missingDependencies` and `installCommand` from `getDesktopStatus()`. + +## Error handling + +```ts +import { SandboxAgentError } from "sandbox-agent"; + +try { + await sdk.listAgents(); +} catch (error) { + if (error instanceof SandboxAgentError) { + console.error(error.status, error.problem); + } +} +``` + +## Inspector URL + +When you call `SandboxAgent.start(...)`, prefer `sdk.inspectorUrl`. Some hosted providers return a browser-ready Inspector URL there. + +```ts +import { buildInspectorUrl } from "sandbox-agent"; + +const url = buildInspectorUrl({ + baseUrl: "https://your-sandbox-agent.example.com", + headers: { "X-Custom-Header": "value" }, +}); + +console.log(url); +``` + +Parameters: + +- `baseUrl` (required unless `fetch` is provided): Sandbox Agent server URL +- `token` (optional): Bearer token for authenticated servers +- `headers` (optional): Additional request headers +- `fetch` (optional): Custom fetch implementation used by SDK HTTP and session calls +- `skipHealthCheck` (optional): set `true` to skip the startup `/v1/health` wait +- `waitForHealth` (optional, defaults to enabled): waits for `/v1/health` before HTTP helpers and session setup proceed; pass `false` to disable or `{ timeoutMs }` to bound the wait +- `signal` (optional): aborts the startup `/v1/health` wait used by `connect()` + +## LLM credentials + +Sandbox Agent supports personal API keys, shared organization keys, and per-tenant gateway keys with budget enforcement. See [LLM Credentials](/llm-credentials) for setup details. diff --git a/.agents/skills/sandbox-agent/references/security.md b/.agents/skills/sandbox-agent/references/security.md new file mode 100644 index 0000000..ac619a3 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/security.md @@ -0,0 +1,187 @@ +# Security + +> Source: `docs/security.mdx` +> Canonical URL: https://sandboxagent.dev/docs/security +> Description: Backend-first auth and access control patterns. + +--- +As covered in [Orchestration Architecture](/orchestration-architecture), run the Sandbox Agent client on your backend, not in the browser. + +This keeps sandbox credentials private and gives you one place for authz, rate limiting, and audit logging. + +## Auth model + +Implement auth however it fits your stack (sessions, JWT, API keys, etc.), but enforce it before any sandbox-bound request. + +Minimum checks: + +- Authenticate the caller. +- Authorize access to the target workspace/sandbox/session. +- Apply request rate limits and request logging. + +## Examples + +### Rivet + +```ts Actor (server) +import { UserError, actor } from "rivetkit"; +import { SandboxAgent } from "sandbox-agent"; + +type ConnParams = { + accessToken: string; +}; + +type WorkspaceClaims = { + sub: string; + workspaceId: string; + role: "owner" | "member" | "viewer"; +}; + +async function verifyWorkspaceToken( + token: string, + workspaceId: string, +): Promise { + // Validate JWT/session token here, then enforce workspace scope. + // Return null when invalid/expired/not a member. + if (!token) return null; + return { sub: "user_123", workspaceId, role: "member" }; +} + +export const workspace = actor({ + state: { + events: [] as Array<{ userId: string; prompt: string; createdAt: number }>, + }, + + onBeforeConnect: async (c, params: ConnParams) => { + const claims = await verifyWorkspaceToken(params.accessToken, c.key[0]); + if (!claims) { + throw new UserError("Forbidden", { code: "forbidden" }); + } + }, + + createConnState: async (c, params: ConnParams) => { + const claims = await verifyWorkspaceToken(params.accessToken, c.key[0]); + if (!claims) { + throw new UserError("Forbidden", { code: "forbidden" }); + } + + return { + userId: claims.sub, + role: claims.role, + workspaceId: claims.workspaceId, + }; + }, + + actions: { + submitPrompt: async (c, prompt: string) => { + if (!c.conn) { + throw new UserError("Connection required", { code: "connection_required" }); + } + + if (c.conn.state.role === "viewer") { + throw new UserError("Insufficient permissions", { code: "forbidden" }); + } + + // Connect to Sandbox Agent from the actor (server-side only). + // Sandbox credentials never reach the client. + const sdk = await SandboxAgent.connect({ + baseUrl: process.env.SANDBOX_URL!, + token: process.env.SANDBOX_TOKEN, + }); + + const session = await sdk.createSession({ + agent: "claude", + cwd: "/workspace", + }); + + session.onEvent((event) => { + c.broadcast("session.event", { + userId: c.conn!.state.userId, + eventIndex: event.eventIndex, + sender: event.sender, + payload: event.payload, + }); + }); + + const result = await session.prompt([ + { type: "text", text: prompt }, + ]); + + c.state.events.push({ + userId: c.conn.state.userId, + prompt, + createdAt: Date.now(), + }); + + return { stopReason: result.stopReason }; + }, + }, +}); +``` + +```ts Client (browser) +import { createClient } from "rivetkit/client"; +import type { registry } from "./actors"; + +const client = createClient({ + endpoint: process.env.NEXT_PUBLIC_RIVET_ENDPOINT!, +}); + +const handle = client.workspace.getOrCreate(["ws_123"], { + params: { accessToken: userJwt }, +}); + +const conn = handle.connect(); + +conn.on("session.event", (event) => { + console.log(event.sender, event.payload); +}); + +const result = await conn.submitPrompt("Plan a refactor for auth middleware."); +console.log(result.stopReason); +``` + +Use [onBeforeConnect](https://rivet.dev/docs/actors/authentication), [connection params](https://rivet.dev/docs/actors/connections), and [actor keys](https://rivet.dev/docs/actors/keys) together so each actor enforces auth per workspace. + +### Hono + +```ts +import { Hono } from "hono"; +import { bearerAuth } from "hono/bearer-auth"; + +const app = new Hono(); + +app.use("/sandbox/*", bearerAuth({ token: process.env.APP_API_TOKEN! })); + +app.all("/sandbox/*", async (c) => { + const incoming = new URL(c.req.url); + const upstreamUrl = new URL(process.env.SANDBOX_URL!); + upstreamUrl.pathname = incoming.pathname.replace(/^\/sandbox/, "/v1"); + upstreamUrl.search = incoming.search; + + const headers = new Headers(); + headers.set("authorization", `Bearer ${process.env.SANDBOX_TOKEN ?? ""}`); + + const accept = c.req.header("accept"); + if (accept) headers.set("accept", accept); + + const contentType = c.req.header("content-type"); + if (contentType) headers.set("content-type", contentType); + + const body = + c.req.method === "POST" || c.req.method === "PUT" || c.req.method === "PATCH" + ? await c.req.text() + : undefined; + + const upstream = await fetch(upstreamUrl, { + method: c.req.method, + headers, + body, + }); + + return new Response(upstream.body, { + status: upstream.status, + headers: upstream.headers, + }); +}); +``` diff --git a/.agents/skills/sandbox-agent/references/session-persistence.md b/.agents/skills/sandbox-agent/references/session-persistence.md new file mode 100644 index 0000000..c8f1bc5 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/session-persistence.md @@ -0,0 +1,122 @@ +# Persisting Sessions + +> Source: `docs/session-persistence.mdx` +> Canonical URL: https://sandboxagent.dev/docs/session-persistence +> Description: Choose and configure session persistence for the TypeScript SDK. + +--- +The TypeScript SDK uses a `SessionPersistDriver` to store session records and event history. +If you do not provide one, the SDK uses in-memory storage. +With persistence enabled, sessions can be restored after runtime/session loss. See [Session Restoration](/session-restoration). + +Each driver stores: + +- `SessionRecord` (`id`, `agent`, `agentSessionId`, `lastConnectionId`, `createdAt`, optional `destroyedAt`, optional `sandboxId`, optional `sessionInit`, optional `configOptions`, optional `modes`) +- `SessionEvent` (`id`, `eventIndex`, `sessionId`, `connectionId`, `sender`, `payload`, `createdAt`) + +## Persistence drivers + +### Rivet + +Recommended for sandbox orchestration with actor state. See [Multiplayer](/multiplayer) for a full Rivet actor example with persistence in actor state. + +### IndexedDB (browser) + +Best for browser apps that should survive reloads. See the [Inspector source](https://github.com/rivet-dev/sandbox-agent/tree/main/frontend/packages/inspector/src/persist-indexeddb.ts) for a complete IndexedDB driver you can copy into your project. + +### In-memory (built-in) + +Best for local dev and ephemeral workloads. No extra dependencies required. + +```ts +import { InMemorySessionPersistDriver, SandboxAgent } from "sandbox-agent"; + +const persist = new InMemorySessionPersistDriver({ + maxSessions: 1024, + maxEventsPerSession: 500, +}); + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", + persist, +}); +``` + +### SQLite + +Best for local/server Node apps that need durable storage without a DB server. + +```bash +npm install better-sqlite3 +``` + +```ts +import { SandboxAgent } from "sandbox-agent"; +import { SQLiteSessionPersistDriver } from "./persist.ts"; + +const persist = new SQLiteSessionPersistDriver({ + filename: "./sandbox-agent.db", +}); + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", + persist, +}); +``` + +See the [full SQLite example](https://github.com/rivet-dev/sandbox-agent/tree/main/examples/persist-sqlite) for the complete driver implementation you can copy into your project. + +### Postgres + +Use when you already run Postgres and want shared relational storage. + +```bash +npm install pg +``` + +```ts +import { SandboxAgent } from "sandbox-agent"; +import { PostgresSessionPersistDriver } from "./persist.ts"; + +const persist = new PostgresSessionPersistDriver({ + connectionString: process.env.DATABASE_URL, + schema: "public", +}); + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", + persist, +}); +``` + +See the [full Postgres example](https://github.com/rivet-dev/sandbox-agent/tree/main/examples/persist-postgres) for the complete driver implementation you can copy into your project. + +### Custom driver + +Implement `SessionPersistDriver` for custom backends. + +```ts +import type { SessionPersistDriver } from "sandbox-agent"; + +class MyDriver implements SessionPersistDriver { + async getSession(id) { return undefined; } + async listSessions(request) { return { items: [] }; } + async updateSession(session) {} + async listEvents(request) { return { items: [] }; } + async insertEvent(sessionId, event) {} +} +``` + +## Replay controls + +`SandboxAgent.connect(...)` supports: + +- `replayMaxEvents` (default `50`) +- `replayMaxChars` (default `12000`) + +These cap replay size when restoring sessions. + +## Related docs + +- [SDK Overview](/sdk-overview) +- [Session Restoration](/session-restoration) diff --git a/.agents/skills/sandbox-agent/references/session-restoration.md b/.agents/skills/sandbox-agent/references/session-restoration.md new file mode 100644 index 0000000..c97d505 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/session-restoration.md @@ -0,0 +1,35 @@ +# Session Restoration + +> Source: `docs/session-restoration.mdx` +> Canonical URL: https://sandboxagent.dev/docs/session-restoration +> Description: How the TypeScript SDK restores sessions after connection/runtime loss. + +--- +Sandbox Agent automatically restores stale sessions when live session state is no longer available. + +This is driven by the configured `SessionPersistDriver` (`inMemory`, IndexedDB, SQLite, Postgres, or custom). + +## How Auto-Restore Works + +When you call `session.prompt(...)` (or `resumeSession(...)`) and the saved session points to a stale connection, the SDK: + +1. Recreates a fresh session for the same local session id. +2. Rebinds the local session to the new runtime session id. +3. Replays recent persisted events into the next prompt as context. + +This happens automatically; you do not need to manually rebuild the session. + +## Replay Limits + +Replay payload size is capped by: + +- `replayMaxEvents` (default `50`) +- `replayMaxChars` (default `12000`) + +These controls limit prompt growth during restore while preserving recent context. + +## Related Docs + +- [SDK Overview](/sdk-overview) +- [Persisting Sessions](/session-persistence) +- [Agent Sessions](/agent-sessions) diff --git a/.agents/skills/sandbox-agent/references/skills-config.md b/.agents/skills/sandbox-agent/references/skills-config.md new file mode 100644 index 0000000..47bea16 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/skills-config.md @@ -0,0 +1,79 @@ +# Skills + +> Source: `docs/skills-config.mdx` +> Canonical URL: https://sandboxagent.dev/docs/skills-config +> Description: Configure skill sources for agent sessions. + +--- +Skills are local instruction bundles stored in `SKILL.md` files. + +## Configuring skills + +Use `setSkillsConfig` / `getSkillsConfig` / `deleteSkillsConfig` to manage skill source config by directory + skill name. + +```ts +import { SandboxAgent } from "sandbox-agent"; + +const sdk = await SandboxAgent.connect({ + baseUrl: "http://127.0.0.1:2468", +}); + +// Add a skill +await sdk.setSkillsConfig( + { + directory: "/workspace", + skillName: "default", + }, + { + sources: [ + { type: "github", source: "rivet-dev/skills", skills: ["sandbox-agent"] }, + { type: "local", source: "/workspace/my-custom-skill" }, + ], + }, +); + +// Create a session using the configured skills +const session = await sdk.createSession({ + agent: "claude", + cwd: "/workspace", +}); + +await session.prompt([ + { type: "text", text: "Use available skills to help with this task." }, +]); + +// List skills +const config = await sdk.getSkillsConfig({ + directory: "/workspace", + skillName: "default", +}); + +console.log(config.sources.length); + +// Delete skill +await sdk.deleteSkillsConfig({ + directory: "/workspace", + skillName: "default", +}); + +``` + +## Skill sources + +Each `skills.sources` entry describes where to find skills. + +| Type | `source` value | Example | +|------|---------------|---------| +| `github` | `owner/repo` | `"rivet-dev/skills"` | +| `local` | filesystem path | `"/workspace/my-skill"` | +| `git` | git clone URL | `"https://git.example.com/skills.git"` | + +Optional fields: + +- `skills`: subset of skill directory names to include +- `ref`: branch/tag/commit (for `github` and `git`) +- `subpath`: subdirectory within repo to scan + +## Custom skills + +To write, upload, and configure your own skills inside the sandbox, see [Custom Tools](/custom-tools). diff --git a/.agents/skills/sandbox-agent/references/telemetry.md b/.agents/skills/sandbox-agent/references/telemetry.md new file mode 100644 index 0000000..2885b49 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/telemetry.md @@ -0,0 +1,27 @@ +# Telemetry + +> Source: `docs/telemetry.mdx` +> Canonical URL: https://sandboxagent.dev/docs/telemetry +> Description: Anonymous telemetry collected by sandbox-agent. + +--- +sandbox-agent sends a small, anonymous telemetry payload on startup and then every 5 minutes to help us understand usage and improve reliability. + +## What gets sent + +- Sandbox Agent version. +- OS name, architecture, and OS family. +- Detected sandbox provider (for example: Docker, E2B, Vercel Sandboxes). + +Each sandbox gets a random anonymous ID stored on disk so usage can be counted without identifying users. +The last successful send time is also stored on disk, and heartbeats are rate-limited to at most one every 5 minutes. + +## Opting out + +Telemetry is enabled by default in release builds. + +Disable it with: + +```bash +sandbox-agent server --no-telemetry +``` diff --git a/.agents/skills/sandbox-agent/references/troubleshooting.md b/.agents/skills/sandbox-agent/references/troubleshooting.md new file mode 100644 index 0000000..424fb13 --- /dev/null +++ b/.agents/skills/sandbox-agent/references/troubleshooting.md @@ -0,0 +1,58 @@ +# Troubleshooting + +> Source: `docs/troubleshooting.mdx` +> Canonical URL: https://sandboxagent.dev/docs/troubleshooting +> Description: Common issues and solutions when running sandbox-agent + +--- +## "Agent Process Exited" immediately after sending a message + +This typically means the agent (Claude, Codex) crashed on startup. Common causes: + +### 1. Network restrictions + +The sandbox cannot reach the AI provider's API (`api.anthropic.com` or `api.openai.com`). Test connectivity with: + +```bash +curl -s -o /dev/null -w '%{http_code}' --connect-timeout 5 https://api.anthropic.com/v1/messages +``` + +A `000` or timeout means the network is blocked. See [Daytona Network Restrictions](#daytona-network-restrictions) below. + +### 2. Missing API key + +Ensure `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` is set in the sandbox environment, not just locally. + +### 3. Agent binary not found + +Verify the agent is installed: + +```bash +ls -la ~/.local/share/sandbox-agent/bin/ +``` + +## Daytona Network Restrictions + +Daytona sandboxes have tier-based network access: + +| Tier | Network Access | +|------|----------------| +| Tier 1 & 2 | Restricted. **Cannot be overridden.** AI provider APIs blocked by default. | +| Tier 3 & 4 | Full internet access. Custom allowlists supported. | + +If you're on Tier 1/2 and agents fail immediately, you have two options: + +1. **Upgrade to Tier 3+** for full network access +2. **Contact Daytona support** to whitelist `api.anthropic.com` and `api.openai.com` for your organization + +The `networkAllowList` parameter only works on Tier 3+: + +```typescript +await daytona.create({ + snapshot: "my-snapshot", + envVars: { ANTHROPIC_API_KEY: "..." }, + networkAllowList: "api.anthropic.com,api.openai.com", // Tier 3+ only +}); +``` + +See [Daytona Network Limits documentation](https://www.daytona.io/docs/en/network-limits/) for details. diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..ede5f1f --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,13 @@ +{ + "typescript.preferences.autoImportFileExcludePatterns": ["repos/**"], + "javascript.preferences.autoImportFileExcludePatterns": ["repos/**"], + "files.exclude": { + "repos/**": true + }, + "files.watcherExclude": { + "repos/**": true + }, + "search.exclude": { + "repos/**": true + } +} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..c409605 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,174 @@ +# Repository Guidelines + +## Project Overview + +This is a Bun/TypeScript monorepo for operating coding agents across web, native, desktop, terminal, and remote daemon surfaces. Convex is the backend control plane; the compiled Bun daemon subscribes to Convex commands and dispatches them to AgentOS/RivetKit actors that manage isolated agent VMs. + +## Architecture & Data Flow + +- `apps/web`, `apps/native`, `apps/desktop`, and `apps/tui` are user interfaces. Shared UI lives in `packages/ui`; runtime-specific environment validation lives in `packages/env`. +- `packages/backend/convex` owns persistence, Better Auth, daemon registration/presence, the leased command queue, and append-only command events. +- `apps/daemon` is an Effect v4 application. It connects to Convex, subscribes to available commands, atomically claims a lease, invokes an AgentOS actor action, then reports success or failure. +- `packages/primitives` provides shared Effect v4 services, currently the `AgentOs` service and layer over `@rivet-dev/agentos`. +- `packages/agents` contains separate Flue agent definitions; do not conflate these with the AgentOS daemon runtime. + +Primary daemon flow: + +```text +UI mutation -> Convex daemonCommands.enqueue + -> daemon onUpdate subscription + -> claim -> start -> AgentOS action + -> succeed/fail + daemonCommandEvents +``` + +The command queue is lease-based. Preserve ownership checks through `claimedBySessionId`, expiry through `leaseExpiresAt`, terminal statuses, and bounded query results. Keep stable daemon configuration separate from high-churn presence/heartbeat state. + +## Key Directories + +- `apps/web/`: React Router 8 web client; desktop consumes its static build. +- `apps/native/`: Expo/React Native client. +- `apps/desktop/`: Electrobun shell around `apps/web/build/client`. +- `apps/tui/`: OpenTUI/React terminal client. +- `apps/daemon/`: compiled Bun daemon; Effect runtime, Convex adapter, AgentOS adapter. +- `packages/backend/convex/`: schema, queries, mutations, HTTP/auth integration, generated Convex bindings. +- `packages/primitives/`: reusable Effect v4 primitives. +- `packages/ui/`: shared shadcn/Tailwind UI package. +- `packages/env/`: `./web`, `./native`, and `./server` environment schemas. +- `packages/config/`: shared strict TypeScript configuration. +- `repos/`: committed, read-only upstream references; exclude from normal project tooling. + +## Development Commands + +Run commands from the repository root unless noted. + +```sh +bun install # install workspace dependencies +bun run dev:setup # configure/start the Convex development deployment +bun run dev # run workspace dev scripts +bun run build # build all targets; desktop is built separately last +bun run check-types # recursive workspace type checks +bun run check # Ultracite checks +bun run lint # Oxlint through Vite+ +bun run format # Oxfmt through Vite+ +bun run fix # apply Ultracite fixes +``` + +Targeted commands: + +```sh +bun run dev:web +bun run dev:native +bun run dev:desktop +bun run dev:tui +bun run dev:server # Convex dev server +bun run dev:daemon +bun run build:daemon # apps/daemon/dist/code-daemon +bun run build:desktop +``` + +Repository maintenance: + +```sh +bun run docs:update [commit-or-range] --dry-run # preview a documentation-agent prompt +bun run docs:update [commit-or-range] # update first-party docs with codex/opencode/claude +bun run subtree list # list configured vendored subtrees +bun run subtree status [name] # inspect local subtree metadata +bun run subtree preview # show incoming upstream commits +bun run subtree update --yes # pull a configured subtree using --squash +``` + +`docs:update` defaults to `HEAD`, accepts Git ranges such as `main..HEAD`, excludes vendored/generated content, and detects the agent in `codex`, `opencode`, `claude` order. Override it with `--agent` or `DOCS_AGENT`. Subtree configuration is stored in `scripts/subtrees.json`; pinned historical entries require `--force-pinned --yes`. + +Add shared shadcn components with `npx shadcn@latest add -c packages/ui` and import them from `@code/ui/components/`. + +## Code Conventions & Common Patterns + +- Use ESM, TypeScript 6, double quotes, semicolons, and sorted `package.json` fields. Formatting/lint configuration is in `vite.config.ts`, `oxfmt.config.ts`, and `oxlint.config.ts`. +- Use `import type` for type-only imports. Do not use `any`; validate or narrow `unknown` at trust boundaries. +- Reuse workspace packages through `@code/` and their declared subpath exports instead of reaching into unrelated package internals. +- Environment access belongs in `packages/env`; validate new variables with Zod and expose them through the correct runtime entry point. +- Generated files are not hand-edited: notably `packages/backend/convex/_generated/**`, `apps/web/src/routeTree.gen.ts`, and framework build/type directories. +- Convex modules map directly to `api..`. Every function requires argument validators. Prefer indexed, bounded reads and preserve mutation atomicity for claims/state transitions. +- Before changing `packages/backend/convex`, read `packages/backend/AGENTS.md` and `packages/backend/convex/_generated/ai/guidelines.md`; those instructions override remembered Convex APIs. + +Effect v4 patterns used by daemon/primitives: + +- Define dependencies with `Context.Service` and provide them through `Layer`. +- Use `Schema.TaggedErrorClass` for typed failures and `Effect.try`/`Effect.tryPromise` at external boundaries. +- Name effectful functions with `Effect.fn("Module.operation")`. +- Manage resources with scopes, `Effect.acquireRelease`, and finalizers; use structured concurrency (`FiberSet`, scoped fibers) rather than detached promises. +- Bridge callback APIs through Effect streams/queues. Keep promise and callback errors in the typed error channel. +- Run Bun applications through `BunRuntime.runMain`. + +## Important Files + +- `package.json`: workspace catalog and authoritative scripts; package manager is `bun@1.3.14`. +- `vite.config.ts`: Vite+ task, lint, format, staged-file, and generated-file exclusions. +- `packages/config/tsconfig.base.json`: shared strict compiler settings. +- `packages/backend/convex/schema.ts`: daemon and command data model. +- `packages/backend/convex/daemonCommands.ts`: lease-based command state machine. +- `packages/backend/convex/daemonRuntime.ts`: connection, heartbeat, disconnect, and event reporting. +- `apps/daemon/src/index.ts`: Bun/Effect entry point. +- `apps/daemon/src/runtime.ts`: command subscription and execution loop. +- `apps/daemon/src/convex.ts`: `ConvexControlPlane` Effect service. +- `apps/daemon/src/agent-os.ts`: RivetKit registry and AgentOS action dispatch. +- `packages/primitives/src/agent-os.ts`: reusable AgentOS Effect service/layer. +- `packages/env/src/{web,native,server}.ts`: runtime environment contracts. + +## Runtime/Tooling Preferences + +- Use Bun, not npm/pnpm/yarn, for root installation and scripts. The daemon intentionally compiles with `bun build --compile`. +- Vite+ (`vp`) is the workspace task runner; there is no Turbo or Nx workflow. +- Linting is not type-aware. Always run `bun run check-types` for TypeScript verification. +- Effect and `@effect/platform-bun` are pinned to `4.0.0-beta.99`. AgentOS uses `@rivet-dev/agentos`; RivetKit is currently pinned to a feature build. Verify APIs against installed declarations/source before upgrading or generalizing. +- `.env` and `.env*.local` may contain deployment values and are generally ignored. Use `apps/daemon/.env.example` as the daemon template. Placeholder Convex hosts are deliberately rejected by the environment schemas. + +## Testing & QA + +There are currently no first-party automated tests, test scripts, coverage thresholds, or CI workflows. Do not claim a test suite passed. The current baseline verification is: + +```sh +bun run check-types +bun run check +``` + +Also run the changed application path: compile and start the daemon for daemon work, exercise the affected page for UI work, and use a development Convex deployment for backend state transitions. + +When adding tests: + +- Use the Vite+ test configuration rather than adding a standalone Vitest config. +- Convex tests belong under `packages/backend/convex/` and should follow the generated guidance (`convex-test`, Vitest, edge runtime). +- RivetKit actor tests should use its `setupTest` helper. +- Tests must defend observable behavior such as lease ownership, state transitions, cleanup, retries, authentication, or rendered interactions. + +## Vendored Repositories + +External repositories under `repos/` are read-only reference material. + +- Prefer their patterns, examples, tests, and API usage over guesses or web snippets. +- Do not edit files under `repos/` unless explicitly asked. +- Do not import application code from `repos/`; use normal package dependencies. +- Exclude `repos/` from project-wide formatting, linting, typechecking, and tests unless explicitly validating a vendored repository. + +### Effect v4 and Effect Smol + +Effect v4 moved from the archived `effect-smol` repository into canonical `Effect-TS/effect` in July 2026. When writing or reviewing Effect v4 code: + +1. Read `repos/effect/LLMS.md` before making changes. +2. Use `repos/effect/` as the current source of truth. Its `main` branch contains Effect v4 beta; Effect v3 is on upstream `v3`. +3. Use `repos/effect/packages/effect/src/`, `repos/effect/packages/effect/test/`, and `repos/effect/ai-docs/` for current APIs and idioms. +4. Treat `repos/effect-smol/` as historical only; read its `README.md` before consulting it. +5. Verify API names and signatures against `repos/effect/`; do not rely on Effect v3 knowledge or prefer older Smol APIs. +6. Import only from the installed `effect` package in application code. + +Refresh the current reference only from a clean worktree: + +```sh +git subtree pull --prefix=repos/effect https://github.com/Effect-TS/effect.git main --squash +``` + +The archived Smol subtree should normally stay pinned. If historical synchronization is explicitly required: + +```sh +git subtree pull --prefix=repos/effect-smol https://github.com/Effect-TS/effect-smol.git main --squash +``` diff --git a/README.md b/README.md index 7bd7338..1ab071f 100644 --- a/README.md +++ b/README.md @@ -42,9 +42,7 @@ Then, run the development server: bun run dev ``` -Open [http://localhost:5173](http://localhost:5173) in your browser to see the web application. -Use the Expo Go app to run the mobile application. -Your app will connect to the Convex cloud backend automatically. +Open [http://localhost:5173](http://localhost:5173) in your browser to see the web application. Use the Expo Go app to run the mobile application. Your app will connect to the Convex cloud backend automatically. ## UI Customization @@ -106,3 +104,8 @@ code/ - `bun run dev:desktop`: Start the Electrobun desktop app with HMR - `bun run build:desktop`: Build the stable Electrobun desktop app - `bun run build:desktop:canary`: Build the canary Electrobun desktop app +- `bun run docs:update [commit-or-range]`: Ask a detected coding-agent CLI to update first-party documentation for a commit or revision range; use `--dry-run` to inspect the prompt +- `bun run subtree list`: List configured vendored Git subtrees +- `bun run subtree status [name]`: Inspect subtree metadata and local dirtiness +- `bun run subtree preview `: Fetch and display upstream commits not yet represented by the subtree +- `bun run subtree update --yes`: Safely pull a configured subtree with squash semantics diff --git a/apps/daemon/.env.example b/apps/daemon/.env.example new file mode 100644 index 0000000..6d7a156 --- /dev/null +++ b/apps/daemon/.env.example @@ -0,0 +1,7 @@ +CONVEX_URL=https://example.convex.cloud +DAEMON_ID=local-macbook +DAEMON_NAME=Local MacBook +DAEMON_VERSION=0.0.0 +DAEMON_HEARTBEAT_MS=15000 +DAEMON_COMMAND_LEASE_MS=60000 +# RIVET_ENDPOINT=http://localhost:6420 diff --git a/apps/daemon/package.json b/apps/daemon/package.json new file mode 100644 index 0000000..d1cdd56 --- /dev/null +++ b/apps/daemon/package.json @@ -0,0 +1,29 @@ +{ + "name": "daemon", + "version": "0.0.0", + "private": true, + "type": "module", + "module": "src/index.ts", + "scripts": { + "dev": "bun run --watch src/index.ts", + "build": "bun build src/index.ts --compile --outfile dist/code-daemon", + "start": "./dist/code-daemon", + "check-types": "tsc --noEmit" + }, + "dependencies": { + "@code/backend": "workspace:*", + "@code/env": "workspace:*", + "@code/primitives": "workspace:*", + "@effect/platform-bun": "4.0.0-beta.99", + "@rivet-dev/agentos": "^0.2.7", + "convex": "catalog:", + "effect": "4.0.0-beta.99", + "rivetkit": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0" + }, + "devDependencies": { + "@code/config": "workspace:*", + "@types/bun": "latest", + "@types/node": "^22.13.14", + "typescript": "^6" + } +} diff --git a/apps/daemon/src/agent-os.ts b/apps/daemon/src/agent-os.ts new file mode 100644 index 0000000..1e1dcfb --- /dev/null +++ b/apps/daemon/src/agent-os.ts @@ -0,0 +1,74 @@ +import type { Id } from "@code/backend/convex/_generated/dataModel"; +import { env } from "@code/env/server"; +import { AgentOs, createAgentOsActorEffect } from "@code/primitives/agent-os"; +import { Effect, Schema } from "effect"; +import { setup } from "rivetkit"; +import { createClient } from "rivetkit/client"; + +import type { DaemonCommand } from "./convex"; +import { ConvexControlPlane } from "./convex"; + +export class AgentOsCommandError extends Schema.TaggedErrorClass()( + "AgentOsCommandError", + { + method: Schema.String, + cause: Schema.Defect(), + } +) {} + +const asArgs = (value: unknown): unknown[] => { + if (!Array.isArray(value)) { + throw new TypeError("agentOS command args must be an array"); + } + return value; +}; + +export const makeAgentOsRuntime = Effect.gen(function* () { + const actor = yield* createAgentOsActorEffect(); + const registry = setup({ use: { agentOs: actor } }); + registry.start(); + const client = createClient(env.RIVET_ENDPOINT); + + const execute = Effect.fn("AgentOsRuntime.execute")(function* ( + command: DaemonCommand + ) { + const controlPlane = yield* ConvexControlPlane; + const handle = client.agentOs.getOrCreate([...command.actorKey]); + return yield* Effect.tryPromise({ + try: () => + handle.action({ + name: command.method, + args: asArgs(command.args), + }), + catch: (cause) => + new AgentOsCommandError({ method: command.method, cause }), + }).pipe( + Effect.tap((result) => + controlPlane.recordEvent({ + commandId: command._id, + kind: "agentos.action.succeeded", + data: { method: command.method, result }, + }) + ), + Effect.tapError((error) => + controlPlane.recordEvent({ + commandId: command._id, + kind: "agentos.action.failed", + data: { method: command.method, error: String(error.cause) }, + }) + ) + ); + }); + + const recordLifecycleEvent = ( + commandId: Id<"daemonCommands"> | undefined, + kind: string, + data: unknown + ) => + Effect.gen(function* () { + const controlPlane = yield* ConvexControlPlane; + yield* controlPlane.recordEvent({ commandId, kind, data }); + }); + + return { execute, recordLifecycleEvent } as const; +}).pipe(Effect.provide(AgentOs.layer)); diff --git a/apps/daemon/src/convex.ts b/apps/daemon/src/convex.ts new file mode 100644 index 0000000..2fce473 --- /dev/null +++ b/apps/daemon/src/convex.ts @@ -0,0 +1,174 @@ +import { api } from "@code/backend/convex/_generated/api"; +import type { Id } from "@code/backend/convex/_generated/dataModel"; +import { env } from "@code/env/server"; +import { ConvexClient } from "convex/browser"; +import { Cause, Context, Effect, Layer, Queue, Schema, Stream } from "effect"; + +export class ConvexControlPlaneError extends Schema.TaggedErrorClass()( + "ConvexControlPlaneError", + { + operation: Schema.String, + cause: Schema.Defect(), + } +) {} + +export interface DaemonCommand { + readonly _id: Id<"daemonCommands">; + readonly daemonId: string; + readonly actorKey: readonly string[]; + readonly method: string; + readonly args: unknown; +} + +const tryPromise = (operation: string, evaluate: () => Promise) => + Effect.tryPromise({ + try: evaluate, + catch: (cause) => new ConvexControlPlaneError({ operation, cause }), + }); + +export class ConvexControlPlane extends Context.Service< + ConvexControlPlane, + { + readonly commands: Stream.Stream< + readonly DaemonCommand[], + ConvexControlPlaneError + >; + readonly connect: (input: { + readonly sessionId: string; + readonly hostname: string; + readonly platform: string; + readonly architecture: string; + }) => Effect.Effect; + readonly heartbeat: ( + sessionId: string + ) => Effect.Effect; + readonly disconnect: ( + sessionId: string + ) => Effect.Effect; + readonly claim: ( + commandId: Id<"daemonCommands">, + sessionId: string + ) => Effect.Effect; + readonly start: ( + commandId: Id<"daemonCommands">, + sessionId: string + ) => Effect.Effect; + readonly succeed: ( + commandId: Id<"daemonCommands">, + sessionId: string, + result: unknown + ) => Effect.Effect; + readonly fail: ( + commandId: Id<"daemonCommands">, + sessionId: string, + error: string + ) => Effect.Effect; + readonly recordEvent: (input: { + readonly commandId?: Id<"daemonCommands">; + readonly kind: string; + readonly data: unknown; + }) => Effect.Effect; + readonly close: Effect.Effect; + } +>()("@code/daemon/ConvexControlPlane") { + static readonly layer = Layer.effect( + ConvexControlPlane, + Effect.gen(function* () { + const client = yield* Effect.acquireRelease( + Effect.sync(() => new ConvexClient(env.CONVEX_URL)), + (client) => Effect.promise(() => client.close()) + ); + const commands = Stream.callback< + readonly DaemonCommand[], + ConvexControlPlaneError + >((queue) => + Effect.acquireRelease( + Effect.sync(() => + client.onUpdate( + api.daemonCommands.available, + { daemonId: env.DAEMON_ID }, + (items) => { + Queue.offerUnsafe(queue, items); + }, + (cause) => { + Queue.failCauseUnsafe( + queue, + Cause.fail( + new ConvexControlPlaneError({ + operation: "subscribe commands", + cause, + }) + ) + ); + } + ) + ), + (unsubscribe) => Effect.sync(unsubscribe) + ) + ); + + return ConvexControlPlane.of({ + commands, + connect: (input) => + tryPromise("connect daemon", async () => { + await client.mutation(api.daemonRuntime.connect, { + daemonId: env.DAEMON_ID, + version: env.DAEMON_VERSION, + ...input, + }); + }), + heartbeat: (sessionId) => + tryPromise("heartbeat daemon", async () => { + await client.mutation(api.daemonRuntime.heartbeat, { + daemonId: env.DAEMON_ID, + sessionId, + }); + }), + disconnect: (sessionId) => + tryPromise("disconnect daemon", async () => { + await client.mutation(api.daemonRuntime.disconnect, { + daemonId: env.DAEMON_ID, + sessionId, + }); + }), + claim: (commandId, sessionId) => + tryPromise("claim command", () => + client.mutation(api.daemonCommands.claim, { + commandId, + daemonId: env.DAEMON_ID, + sessionId, + leaseDurationMs: env.DAEMON_COMMAND_LEASE_MS, + }) + ), + start: (commandId, sessionId) => + tryPromise("start command", () => + client.mutation(api.daemonCommands.start, { commandId, sessionId }) + ), + succeed: (commandId, sessionId, result) => + tryPromise("complete command", () => + client.mutation(api.daemonCommands.succeed, { + commandId, + sessionId, + result, + }) + ), + fail: (commandId, sessionId, error) => + tryPromise("fail command", () => + client.mutation(api.daemonCommands.fail, { + commandId, + sessionId, + error, + }) + ), + recordEvent: (input) => + tryPromise("record daemon event", async () => { + await client.mutation(api.daemonRuntime.recordEvent, { + daemonId: env.DAEMON_ID, + ...input, + }); + }), + close: tryPromise("close Convex client", () => client.close()), + }); + }) + ); +} diff --git a/apps/daemon/src/index.ts b/apps/daemon/src/index.ts new file mode 100644 index 0000000..325d03c --- /dev/null +++ b/apps/daemon/src/index.ts @@ -0,0 +1,7 @@ +import { BunRuntime } from "@effect/platform-bun"; +import { Effect } from "effect"; + +import { ConvexControlPlane } from "./convex"; +import { runDaemon } from "./runtime"; + +BunRuntime.runMain(runDaemon.pipe(Effect.provide(ConvexControlPlane.layer))); diff --git a/apps/daemon/src/runtime.ts b/apps/daemon/src/runtime.ts new file mode 100644 index 0000000..8128e64 --- /dev/null +++ b/apps/daemon/src/runtime.ts @@ -0,0 +1,83 @@ +import { env } from "@code/env/server"; +import { Console, Effect, FiberSet, Result, Stream } from "effect"; + +import { makeAgentOsRuntime } from "./agent-os"; +import { ConvexControlPlane, type DaemonCommand } from "./convex"; + +const errorMessage = (cause: unknown) => + cause instanceof Error ? cause.message : String(cause); + +export const runDaemon = Effect.scoped( + Effect.gen(function* () { + const controlPlane = yield* ConvexControlPlane; + const agentOs = yield* makeAgentOsRuntime; + const sessionId = crypto.randomUUID(); + const hostname = yield* Effect.promise(() => import("node:os")).pipe( + Effect.map((os) => os.hostname()) + ); + const fibers = yield* FiberSet.make(); + + yield* controlPlane.connect({ + sessionId, + hostname, + platform: process.platform, + architecture: process.arch, + }); + yield* Console.log(`daemon ${env.DAEMON_ID} connected as ${sessionId}`); + + yield* Effect.addFinalizer(() => + controlPlane + .disconnect(sessionId) + .pipe( + Effect.catchCause((cause) => + Console.error("failed to mark daemon offline", cause) + ) + ) + ); + + yield* Stream.tick(env.DAEMON_HEARTBEAT_MS).pipe( + Stream.runForEach(() => controlPlane.heartbeat(sessionId)), + Effect.forkScoped + ); + + const processCommand = Effect.fn("Daemon.processCommand")(function* ( + candidate: DaemonCommand + ) { + const command = yield* controlPlane.claim(candidate._id, sessionId); + if (!command) { + return; + } + const started = yield* controlPlane.start(command._id, sessionId); + if (!started) { + return; + } + yield* controlPlane.recordEvent({ + commandId: command._id, + kind: "command.started", + data: { method: command.method, actorKey: command.actorKey }, + }); + const result = yield* agentOs.execute(command).pipe(Effect.result); + if (Result.isSuccess(result)) { + yield* controlPlane.succeed(command._id, sessionId, result.success); + return; + } + yield* controlPlane.fail( + command._id, + sessionId, + errorMessage(result.failure) + ); + }); + + yield* controlPlane.commands.pipe( + Stream.runForEach((commands) => + Effect.forEach( + commands, + (command) => FiberSet.run(fibers, processCommand(command)), + { + discard: true, + } + ) + ) + ); + }) +); diff --git a/apps/daemon/tsconfig.json b/apps/daemon/tsconfig.json new file mode 100644 index 0000000..6055307 --- /dev/null +++ b/apps/daemon/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "@code/config/tsconfig.base.json", + "compilerOptions": { + "types": ["node", "bun"] + }, + "include": ["src/**/*.ts"], + "exclude": ["dist"] +} diff --git a/bun.lock b/bun.lock index cc4f2db..7e13a00 100644 --- a/bun.lock +++ b/bun.lock @@ -11,6 +11,7 @@ }, "devDependencies": { "@code/config": "workspace:*", + "@types/bun": "latest", "@types/node": "^22.13.14", "oxfmt": "latest", "oxlint": "latest", @@ -20,6 +21,26 @@ "vite-plus": "0.2.2", }, }, + "apps/daemon": { + "name": "daemon", + "version": "0.0.0", + "dependencies": { + "@code/backend": "workspace:*", + "@code/env": "workspace:*", + "@code/primitives": "workspace:*", + "@effect/platform-bun": "4.0.0-beta.99", + "@rivet-dev/agentos": "^0.2.7", + "convex": "catalog:", + "effect": "4.0.0-beta.99", + "rivetkit": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", + }, + "devDependencies": { + "@code/config": "workspace:*", + "@types/bun": "latest", + "@types/node": "^22.13.14", + "typescript": "^6", + }, + }, "apps/desktop": { "name": "desktop", "dependencies": { @@ -180,6 +201,19 @@ "typescript": "^6", }, }, + "packages/primitives": { + "name": "@code/primitives", + "version": "0.0.0", + "dependencies": { + "@rivet-dev/agentos": "^0.2.7", + "effect": "4.0.0-beta.99", + }, + "devDependencies": { + "@code/config": "workspace:*", + "@types/node": "^22.13.14", + "typescript": "^6", + }, + }, "packages/ui": { "name": "@code/ui", "version": "0.0.0", @@ -228,10 +262,46 @@ "packages": { "@adobe/css-tools": ["@adobe/css-tools@4.5.0", "", {}, "sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q=="], + "@agentclientprotocol/sdk": ["@agentclientprotocol/sdk@0.16.1", "", { "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" } }, "sha512-1ad+Sc/0sCtZGHthxxvgEUo5Wsbw16I+aF+YwdiLnPwkZG8KAGUEAPK6LM6Pf69lCyJPt1Aomk1d+8oE3C4ZEw=="], + + "@agentos-software/claude-code": ["@agentos-software/claude-code@0.2.7", "", { "dependencies": { "@agentclientprotocol/sdk": "^0.16.1", "@anthropic-ai/claude-agent-sdk": "0.2.87", "zod": "^4.1.11" }, "bin": { "claude": "dist/claude-cli.mjs", "claude-sdk-acp": "dist/adapter.js" } }, "sha512-gXmqqOUWT98QvLkQXHn1UU8OOvqMO8BRSj+0PT99mOL6XNpBlPW6L065FJ9dC4IwJC5xeGzB1XFevjOdP7LwQg=="], + + "@agentos-software/codex-cli": ["@agentos-software/codex-cli@0.3.3", "", {}, "sha512-63f4jymlxe4S003/4Fiu9Y/BAzT6ajHEDidfNqv39SkWNJWxT1ndY+j1/7XYT6NsGgg2ZSo+OGuexlkL8Jx1RA=="], + + "@agentos-software/common": ["@agentos-software/common@0.2.7", "", { "dependencies": { "@agentos-software/coreutils": "0.3.3", "@agentos-software/diffutils": "0.3.3", "@agentos-software/findutils": "0.3.3", "@agentos-software/gawk": "0.3.3", "@agentos-software/grep": "0.3.3", "@agentos-software/gzip": "0.3.3", "@agentos-software/sed": "0.3.3", "@agentos-software/tar": "0.3.3" } }, "sha512-eM5znR9qOaDIEsCBtzxzAfxgynq7ntNyk+lchHF7OUv7Cenbq4XGhCbA1T2dbl45G3/2Wz3+21QM0sv+797lvA=="], + + "@agentos-software/coreutils": ["@agentos-software/coreutils@0.3.3", "", {}, "sha512-uzBD6Q5z+ACn29CMNMSnA+nUzITbTosuOe6Hr/o5ylUpoxODbz6ziAwZ5Cr1XAgF//Qqz7HfQfnogf4zcb+Gvg=="], + + "@agentos-software/diffutils": ["@agentos-software/diffutils@0.3.3", "", {}, "sha512-aaTMx3jWrTn18OxLk0g4nb3MgkLHjXyqlz5BQ3YlRj7hNuRT+hOPnzcSf8zP+pXFR+SGf7a98M2kSNV/ucfyDw=="], + + "@agentos-software/findutils": ["@agentos-software/findutils@0.3.3", "", {}, "sha512-CrtFrmG2o+z0gaxtQBJw4wWGF7TxKq5ukxVFkf2/LxxsdZBc2F04MT6FNY3VMKf4Cq5kFvh7/ZRkMdg2yHAMvA=="], + + "@agentos-software/gawk": ["@agentos-software/gawk@0.3.3", "", {}, "sha512-iHDeJ6rsGxijBQMmqH1w6bQ2+sWrC1f9OqNvUItHOZk85KFmg9a3ueyy0krq9pZRuZe+fU5yEhuUg7ovNqZ9NQ=="], + + "@agentos-software/grep": ["@agentos-software/grep@0.3.3", "", {}, "sha512-jV49HWFJcEGjHBPk37EnisrdKwNfeZ+d+TA6LpAuDKRwFmj/2xc3rGVCTvKIxdZUKYuffu9NI9xgxJ0iKiUU2w=="], + + "@agentos-software/gzip": ["@agentos-software/gzip@0.3.3", "", {}, "sha512-Jbmsu7trAhnnWvT9qlry/hETa5EOlUwdcYHtsyV9W2OQvMc3tOeLy3zwF8nWNuZ3/g1veRenRkK1ZgkqsDZpiw=="], + + "@agentos-software/manifest": ["@agentos-software/manifest@0.2.7", "", {}, "sha512-1e4J8YRR8Ftj7ftKFdqAH2m5ksHz9v+XUGMzirDPGHwXaGzjham3SdWadpqHOE7q3GIWJdP4uWZeY22fquJNrg=="], + + "@agentos-software/opencode": ["@agentos-software/opencode@0.2.7", "", { "bin": { "agentos-opencode-acp": "dist/adapter.js" } }, "sha512-lZspCiMgM0+kPAA08CEvyNy8lfBx463wObKpAwbYyaVvc0KfGvbAPS6VmnuZQWmaBmJJuRMtSo14nmb8XCD16g=="], + + "@agentos-software/pi": ["@agentos-software/pi@0.2.7", "", { "dependencies": { "@agentclientprotocol/sdk": "^0.16.1", "@mariozechner/pi-ai": "0.60.0", "@mariozechner/pi-coding-agent": "0.60.0" }, "bin": { "pi": "node_modules/@mariozechner/pi-coding-agent/dist/cli.js", "pi-sdk-acp": "dist/adapter.js" } }, "sha512-nOdwksByJgTqt92Ya84CzTGxpVFwGI6gkGWaCD/mmvP11JRA++1nshNdbig2mtiaxT7VG3ovWJmK7ZLTTzkhPA=="], + + "@agentos-software/pi-cli": ["@agentos-software/pi-cli@0.2.7", "", { "dependencies": { "@mariozechner/pi-coding-agent": "^0.60.0", "pi-acp": "^0.0.23" }, "bin": { "pi": "node_modules/@mariozechner/pi-coding-agent/dist/cli.js", "pi-acp": "node_modules/pi-acp/dist/index.js" } }, "sha512-uddhoZ8o5zcGsma5s/+jzQg++SRKtZkpY6cSNru4O0t53LJ41t3+OFhC6j8WkQsIYU0ThAwH6LdKHHjWWKBa2g=="], + + "@agentos-software/sed": ["@agentos-software/sed@0.3.3", "", {}, "sha512-cVNTD9VzodpJ+Kn/xqHo/AcUUkpPSuF9A/0jIqFkDNF24alwNG8ndVLwgFWMP+0mSo68HZumbjjnMQWE3NjRSw=="], + + "@agentos-software/tar": ["@agentos-software/tar@0.3.3", "", {}, "sha512-pmYVIn3XQEKVbfKhms7bEpsGR7YXqaLXtglIHmnhyUwLZhdyerrEkO+VgpC8zuWMeYfmTsstEgpEL1K66sgR2w=="], + "@alloc/quick-lru": ["@alloc/quick-lru@5.2.0", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="], + "@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.2.87", "", { "dependencies": { "@anthropic-ai/sdk": "^0.74.0", "@modelcontextprotocol/sdk": "^1.27.1" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "^0.34.2", "@img/sharp-darwin-x64": "^0.34.2", "@img/sharp-linux-arm": "^0.34.2", "@img/sharp-linux-arm64": "^0.34.2", "@img/sharp-linux-x64": "^0.34.2", "@img/sharp-linuxmusl-arm64": "^0.34.2", "@img/sharp-linuxmusl-x64": "^0.34.2", "@img/sharp-win32-arm64": "^0.34.2", "@img/sharp-win32-x64": "^0.34.2" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-WWmgBPxPhBOvNT0ujI8vPTI2lK+w5YEkEZ/y1mH0EDkK/0kBnxVJNhCtG5vnueiAViwLoUOFn66pbkDiivijdA=="], + "@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.91.1", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-LAmu761tSN9r66ixvmciswUj/ZC+1Q4iAfpedTfSVLeswRwnY3n2Nb6Tsk+cLPP28aLOPWeMgIuTuCcMC6W/iw=="], + "@asteasolutions/zod-to-openapi": ["@asteasolutions/zod-to-openapi@8.5.0", "", { "dependencies": { "openapi3-ts": "^4.1.2" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-SABbKiObg5dLRiTFnqiW1WWwGcg1BJfmHtT2asIBnBHg6Smy/Ms2KHc650+JI4Hw7lSkdiNebEGXpwoxfben8Q=="], + "@aws-crypto/sha256-browser": ["@aws-crypto/sha256-browser@5.2.0", "", { "dependencies": { "@aws-crypto/sha256-js": "^5.2.0", "@aws-crypto/supports-web-crypto": "^5.2.0", "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "@aws-sdk/util-locate-window": "^3.0.0", "@smithy/util-utf8": "^2.0.0", "tslib": "^2.6.2" } }, "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw=="], "@aws-crypto/sha256-js": ["@aws-crypto/sha256-js@5.2.0", "", { "dependencies": { "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "tslib": "^2.6.2" } }, "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA=="], @@ -240,8 +310,12 @@ "@aws-crypto/util": ["@aws-crypto/util@5.2.0", "", { "dependencies": { "@aws-sdk/types": "^3.222.0", "@smithy/util-utf8": "^2.0.0", "tslib": "^2.6.2" } }, "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ=="], + "@aws-sdk/checksums": ["@aws-sdk/checksums@3.1000.18", "", { "dependencies": { "@aws-sdk/core": "^3.975.3", "@aws-sdk/types": "^3.974.2", "@smithy/core": "^3.29.4", "@smithy/types": "^4.16.1", "tslib": "^2.6.2" } }, "sha512-IImkbEyXdV6/uaF5r6Wkk+8718mQw1ll83j0a4a30R3JM/rHVFdWAiT4jtJpFjJiIwM/oJ6SxIxr0z2TaQUGqw=="], + "@aws-sdk/client-bedrock-runtime": ["@aws-sdk/client-bedrock-runtime@3.1048.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.11", "@aws-sdk/credential-provider-node": "^3.972.42", "@aws-sdk/eventstream-handler-node": "^3.972.16", "@aws-sdk/middleware-eventstream": "^3.972.12", "@aws-sdk/middleware-websocket": "^3.972.19", "@aws-sdk/token-providers": "3.1048.0", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/fetch-http-handler": "^5.4.2", "@smithy/node-http-handler": "^4.7.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-u+NT61JZEkRFtpL0CAw1N1dwxnaLgwVXQl/zjJxTGgLyS/jTIdg2SdoEoCTHxgDyCnqa1HEi9QOoE9/pYRNpOQ=="], + "@aws-sdk/client-s3": ["@aws-sdk/client-s3@3.1090.0", "", { "dependencies": { "@aws-sdk/checksums": "^3.1000.18", "@aws-sdk/core": "^3.975.3", "@aws-sdk/credential-provider-node": "^3.972.70", "@aws-sdk/middleware-sdk-s3": "^3.972.64", "@aws-sdk/signature-v4-multi-region": "^3.996.41", "@aws-sdk/types": "^3.974.2", "@smithy/core": "^3.29.4", "@smithy/fetch-http-handler": "^5.6.6", "@smithy/node-http-handler": "^4.9.6", "@smithy/types": "^4.16.1", "tslib": "^2.6.2" } }, "sha512-R6GX9cd1jljwzZ8xFmgAI/hHCuX1MobIKBdsymv7WL9SENvO9Vgz9KOR6avTnu0Ao+w1LmxnTe+jqmZXEn7Q/Q=="], + "@aws-sdk/core": ["@aws-sdk/core@3.975.3", "", { "dependencies": { "@aws-sdk/types": "^3.974.2", "@aws-sdk/xml-builder": "^3.972.36", "@aws/lambda-invoke-store": "^0.3.0", "@smithy/core": "^3.29.4", "@smithy/signature-v4": "^5.6.5", "@smithy/types": "^4.16.1", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-7ur3kCKuvPLqlsZ2XlvnNBVQ7KkpSu6Y6dOTwSPHLrFpTEfZM8isLBJc4cgv96WB7GifeVM436mpycwxBd2vEA=="], "@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.59", "", { "dependencies": { "@aws-sdk/core": "^3.975.3", "@aws-sdk/types": "^3.974.2", "@smithy/core": "^3.29.4", "@smithy/types": "^4.16.1", "tslib": "^2.6.2" } }, "sha512-Ny5e4Mfh3QPmiAc0AiUe+cbTXDlxkU3Rc+EpWOfyWeWEy6yp7Fa1KmfNeCc+1a8by9zQ9gtohmiQUkMPScF3ng=="], @@ -264,6 +338,8 @@ "@aws-sdk/middleware-eventstream": ["@aws-sdk/middleware-eventstream@3.972.24", "", { "dependencies": { "@aws-sdk/types": "^3.974.2", "@smithy/core": "^3.29.4", "@smithy/types": "^4.16.1", "tslib": "^2.6.2" } }, "sha512-oykin4mDWxNOuYQ7SF1cHzgYeuFEkF4cdRwgvjFFbIklkx09qIFBiOgsORafG9sXZFO3TayMmQuAQYgADXhI8w=="], + "@aws-sdk/middleware-sdk-s3": ["@aws-sdk/middleware-sdk-s3@3.972.64", "", { "dependencies": { "@aws-sdk/core": "^3.975.3", "@aws-sdk/signature-v4-multi-region": "^3.996.41", "@aws-sdk/types": "^3.974.2", "@smithy/core": "^3.29.4", "@smithy/types": "^4.16.1", "tslib": "^2.6.2" } }, "sha512-RBi43anhDBUv+HCfxCOXwGOE7GmT4n7ChV04Mwr22RhXTNcamW/iWnJlOotDPCZSrJ4dEvhZSiWWQMwLX+ZhFA=="], + "@aws-sdk/middleware-websocket": ["@aws-sdk/middleware-websocket@3.972.41", "", { "dependencies": { "@aws-sdk/core": "^3.975.3", "@aws-sdk/types": "^3.974.2", "@smithy/core": "^3.29.4", "@smithy/fetch-http-handler": "^5.6.6", "@smithy/signature-v4": "^5.6.5", "@smithy/types": "^4.16.1", "tslib": "^2.6.2" } }, "sha512-LSbGvvYmjc4Br9BPYI2dTLnIclmrSiQbahkP4D6nRGVEv4qsCZ8csVuKBPVEEFCVD+EEngGh8ROls6XpumtwMg=="], "@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.33", "", { "dependencies": { "@aws-sdk/core": "^3.975.3", "@aws-sdk/signature-v4-multi-region": "^3.996.41", "@aws-sdk/types": "^3.974.2", "@smithy/core": "^3.29.4", "@smithy/fetch-http-handler": "^5.6.6", "@smithy/node-http-handler": "^4.9.6", "@smithy/types": "^4.16.1", "tslib": "^2.6.2" } }, "sha512-dVZOroI/r3/ENvqNGgjMPul+jjlz9GddfVusgTXlVjfZj5isibOxecLkGQbRPp8XOuX+RAfjXLFgPkD1JS5xrw=="], @@ -458,6 +534,18 @@ "@borewit/text-codec": ["@borewit/text-codec@0.2.2", "", {}, "sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ=="], + "@cbor-extract/cbor-extract-darwin-arm64": ["@cbor-extract/cbor-extract-darwin-arm64@2.2.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-ZKZ/F8US7JR92J4DMct6cLW/Y66o2K576+zjlEN/MevH70bFIsB10wkZEQPLzl2oNh2SMGy55xpJ9JoBRl5DOA=="], + + "@cbor-extract/cbor-extract-darwin-x64": ["@cbor-extract/cbor-extract-darwin-x64@2.2.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-32b1mgc+P61Js+KW9VZv/c+xRw5EfmOcPx990JbCBSkYJFY0l25VinvyyWfl+3KjibQmAcYwmyzKF9J4DyKP/Q=="], + + "@cbor-extract/cbor-extract-linux-arm": ["@cbor-extract/cbor-extract-linux-arm@2.2.2", "", { "os": "linux", "cpu": "arm" }, "sha512-tNg0za41TpQfkhWjptD+0gSD2fggMiDCSacuIeELyb2xZhr7PrhPe5h66Jc67B/5dmpIhI2QOUtv4SBsricyYQ=="], + + "@cbor-extract/cbor-extract-linux-arm64": ["@cbor-extract/cbor-extract-linux-arm64@2.2.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-wfqgzqCAy/Vn8i6WVIh7qZd0DdBFaWBjPdB6ma+Wihcjv0gHqD/mw3ouVv7kbbUNrab6dKEx/w3xQZEdeXIlzg=="], + + "@cbor-extract/cbor-extract-linux-x64": ["@cbor-extract/cbor-extract-linux-x64@2.2.2", "", { "os": "linux", "cpu": "x64" }, "sha512-rpiLnVEsqtPJ+mXTdx1rfz4RtUGYIUg2rUAZgd1KjiC1SehYUSkJN7Yh+aVfSjvCGtVP0/bfkQkXpPXKbmSUaA=="], + + "@cbor-extract/cbor-extract-win32-x64": ["@cbor-extract/cbor-extract-win32-x64@2.2.2", "", { "os": "win32", "cpu": "x64" }, "sha512-dI+9P7cfWxkTQ+oE+7Aa6onEn92PHgfWXZivjNheCRmTBDBf2fx6RyTi0cmgpYLnD1KLZK9ZYrMxaPZ4oiXhGA=="], + "@clack/core": ["@clack/core@1.4.3", "", { "dependencies": { "fast-wrap-ansi": "^0.2.0", "sisteransi": "^1.0.5" } }, "sha512-/kr3UWNtdJfxZtPgDqUOmG2pvwlmcLGheex5yiZKdwbzZJxhV+HMNR9QNmyY5cGwTNV6LrR7Jtp+KjhUAP1qBQ=="], "@clack/prompts": ["@clack/prompts@1.7.0", "", { "dependencies": { "@clack/core": "1.4.3", "fast-string-width": "^3.0.2", "fast-wrap-ansi": "^0.2.0", "sisteransi": "^1.0.5" } }, "sha512-y7/yvZ2TPAnR9+jnc00klvNNLkJiXFFrQA/hlLCcxA9a2A4zQIOimyFQ9XfwYKiGD1fb5GY8vbKIIgO8d5Tb2A=="], @@ -486,6 +574,8 @@ "@code/env": ["@code/env@workspace:packages/env"], + "@code/primitives": ["@code/primitives@workspace:packages/primitives"], + "@code/ui": ["@code/ui@workspace:packages/ui"], "@convex-dev/better-auth": ["@convex-dev/better-auth@0.12.5", "", { "dependencies": { "@better-fetch/fetch": "^1.1.18", "common-tags": "^1.8.2", "convex-helpers": "^0.1.95", "jose": "^6.1.0", "remeda": "^2.32.0", "semver": "^7.7.3", "type-fest": "^5.0.0", "zod": "^4.0.0" }, "peerDependencies": { "better-auth": ">=1.6.11 <1.7.0", "convex": "^1.25.0", "react": "^18.3.1 || ^19.0.0" } }, "sha512-YFUbGk04OlINno9FpOTNZN67AP+kSQsblfep5zs1f/WTgMWjD5FymU6rSSh3mu52gukmDNnBJTjC/lj4QRpjlQ=="], @@ -502,6 +592,10 @@ "@earendil-works/pi-ai": ["@earendil-works/pi-ai@0.80.10", "", { "dependencies": { "@anthropic-ai/sdk": "0.91.1", "@aws-sdk/client-bedrock-runtime": "3.1048.0", "@google/genai": "1.52.0", "@mistralai/mistralai": "2.2.6", "@opentelemetry/api": "1.9.0", "@smithy/node-http-handler": "4.7.3", "http-proxy-agent": "7.0.2", "https-proxy-agent": "7.0.6", "openai": "6.26.0", "partial-json": "0.1.7", "typebox": "1.1.38" }, "bin": { "pi-ai": "dist/cli.js" } }, "sha512-Moe/H8c87yacDGK9dPbWphZNjVsrb3nTrIHycOQJAkFEnY9PYxOOd74+ny44kATfPU9Dm7aTHefar3pZF+UKUA=="], + "@effect/platform-bun": ["@effect/platform-bun@4.0.0-beta.99", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.99" }, "peerDependencies": { "effect": "^4.0.0-beta.99" } }, "sha512-CCjzD7BY6wvG8tWEBvup2Ko4ME65RX2zZnt8sD+SLwrSEEGJhTliwmQyjyesm8WjAJpALv8NL9/Tv17ocxUPNg=="], + + "@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.0-beta.99", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.21.0" }, "peerDependencies": { "effect": "^4.0.0-beta.99" } }, "sha512-POBAowafsAAb3bH1x1rJlWnv32yMAazFgEuRW5LhkW/JJA5VGoEk9OnuoUkIH1OW6K/X6IrdNpqcO+5e9lPQJA=="], + "@egjs/hammerjs": ["@egjs/hammerjs@2.0.17", "", { "dependencies": { "@types/hammerjs": "^2.0.36" } }, "sha512-XQsZgjm2EcVUiZQf11UBJQfmZeEmOW8DpI1gsFeln6w0ae0ii4dMQEQ0kjl6DspdWX1aGY1/loyXnP0JS06e/A=="], "@emnapi/core": ["@emnapi/core@1.11.1", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ=="], @@ -670,6 +764,10 @@ "@hono/standard-validator": ["@hono/standard-validator@0.2.3", "", { "peerDependencies": { "@standard-schema/spec": "^1.0.0", "hono": ">=3.9.0" } }, "sha512-bp9vHu6Va6SfMHC3D4ZLBbT/woi+AZ9CRdTXQu3kLJuLh2W/Gb9UO4hijS+BQAGFXi4EGpXdetxpzwTAawSVeg=="], + "@hono/zod-openapi": ["@hono/zod-openapi@1.5.1", "", { "dependencies": { "@asteasolutions/zod-to-openapi": "^8.5.0", "@hono/zod-validator": "^0.9.0", "openapi3-ts": "^4.5.0" }, "peerDependencies": { "hono": ">=4.10.0", "zod": "^4.0.0" } }, "sha512-ZaDdEIkn6PEGjIYHXJeyByg6yhvLzI+UXn968pWtahpwcQ6HMjQYXI3zNffTl0Wl9QZ79nUnGqiN1erEIu23fA=="], + + "@hono/zod-validator": ["@hono/zod-validator@0.9.0", "", { "peerDependencies": { "hono": ">=4.11.2", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-n0ZSXmCiHVIp4Y5wlOOyZCeTd/rsawA/qW1cipB8QOYKZ9N8Tk0nZUZCXho9cu374AN4JpDNKioNKBJ/W+LBug=="], + "@humanfs/core": ["@humanfs/core@0.19.2", "", { "dependencies": { "@humanfs/types": "^0.15.0" } }, "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA=="], "@humanfs/node": ["@humanfs/node@0.16.8", "", { "dependencies": { "@humanfs/core": "^0.19.2", "@humanfs/types": "^0.15.0", "@humanwhocodes/retry": "^0.4.0" } }, "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ=="], @@ -760,6 +858,38 @@ "@malept/cross-spawn-promise": ["@malept/cross-spawn-promise@1.1.1", "", { "dependencies": { "cross-spawn": "^7.0.1" } }, "sha512-RTBGWL5FWQcg9orDOCcp4LvItNzUPcyEU9bwaeJX0rJ1IQxzucC48Y0/sQLp/g6t99IQgAlGIaesJS+gTn7tVQ=="], + "@mariozechner/clipboard": ["@mariozechner/clipboard@0.3.9", "", { "optionalDependencies": { "@mariozechner/clipboard-darwin-arm64": "0.3.9", "@mariozechner/clipboard-darwin-universal": "0.3.9", "@mariozechner/clipboard-darwin-x64": "0.3.9", "@mariozechner/clipboard-linux-arm64-gnu": "0.3.9", "@mariozechner/clipboard-linux-arm64-musl": "0.3.9", "@mariozechner/clipboard-linux-riscv64-gnu": "0.3.9", "@mariozechner/clipboard-linux-x64-gnu": "0.3.9", "@mariozechner/clipboard-linux-x64-musl": "0.3.9", "@mariozechner/clipboard-win32-arm64-msvc": "0.3.9", "@mariozechner/clipboard-win32-x64-msvc": "0.3.9" } }, "sha512-ABnA53mdfkGZwOFUdZNv2S0CWGO/EIuPj8Vv9xmBFmSYg/qFc7ihO6q5FcQjvoE67kZpWkEc4AhD6B/os04yuA=="], + + "@mariozechner/clipboard-darwin-arm64": ["@mariozechner/clipboard-darwin-arm64@0.3.9", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BfgV7vCEWZwJwZJw03r6bP5+tf0iI/ANuQYCxi9RNn7FrWB3yzGuMKCrNLRl6V761vXRdL8+OqZ0wd4TqlsNOQ=="], + + "@mariozechner/clipboard-darwin-universal": ["@mariozechner/clipboard-darwin-universal@0.3.9", "", { "os": "darwin" }, "sha512-BGGR4iA9Z2shAjI65eI5xtyb3LYNlDW9X3gxKxDbqtbnREohsrqznov6zpKoIrsRWpzlYVEdKphS7ksJ0/ndSQ=="], + + "@mariozechner/clipboard-darwin-x64": ["@mariozechner/clipboard-darwin-x64@0.3.9", "", { "os": "darwin", "cpu": "x64" }, "sha512-4kURmCbS6nt8uYhtmWpUcJWyPHfmAr5dTpXD1nO3pIfa+TSQ9DbrGOYCKH+aEFW47XhQ4Vp8ZTszie+wfFvDKg=="], + + "@mariozechner/clipboard-linux-arm64-gnu": ["@mariozechner/clipboard-linux-arm64-gnu@0.3.9", "", { "os": "linux", "cpu": "arm64" }, "sha512-g59OkUGP2DDfCOIKypHeYgv2M55u/cKvXa5dSxFbEJ34XvIQMdcVmpKCkGUro3ZgefXiGVdwguvTMQGpHWzIXw=="], + + "@mariozechner/clipboard-linux-arm64-musl": ["@mariozechner/clipboard-linux-arm64-musl@0.3.9", "", { "os": "linux", "cpu": "arm64" }, "sha512-AGuJdgKsmJdm4Pych7kv3sqe591ERRaAHW3xjLooiFzn8J+PxUyof++7YZrB5Y5tpnTO+K18Og3taj2NpluCRQ=="], + + "@mariozechner/clipboard-linux-riscv64-gnu": ["@mariozechner/clipboard-linux-riscv64-gnu@0.3.9", "", { "os": "linux", "cpu": "none" }, "sha512-DXBEAiuMpk7dhS1a9NzNxVAFi1vaKoPu7rQNgY8LIDLGrK3lnIp3nT10DUum+PKVJoJppIP+NAA8IZe4DMNDPw=="], + + "@mariozechner/clipboard-linux-x64-gnu": ["@mariozechner/clipboard-linux-x64-gnu@0.3.9", "", { "os": "linux", "cpu": "x64" }, "sha512-WORrMLd6EpElEME7JRKfSaY34nW1P5LbdgK5YNCS1ncG2LqmITsSMEJ8nh2mpvxb3TxqbOOKgY7k9eMJYlW9Mw=="], + + "@mariozechner/clipboard-linux-x64-musl": ["@mariozechner/clipboard-linux-x64-musl@0.3.9", "", { "os": "linux", "cpu": "x64" }, "sha512-/DHn+1DrfL6oRaPPWXaOKvonFFrni666fxd+zFqiQEfvBH0tsHVWjq9iqBk0oDp0qaPA72lIMy5BptxISBEhZQ=="], + + "@mariozechner/clipboard-win32-arm64-msvc": ["@mariozechner/clipboard-win32-arm64-msvc@0.3.9", "", { "os": "win32", "cpu": "arm64" }, "sha512-O5FHD3ErkMwMhNzAfu3ggy0ug4z7btZuoQgwwxlzPrwV2bxlD6WDpqBY4NCgICAgZdDKdp+loUEKVAVt8aYnhQ=="], + + "@mariozechner/clipboard-win32-x64-msvc": ["@mariozechner/clipboard-win32-x64-msvc@0.3.9", "", { "os": "win32", "cpu": "x64" }, "sha512-ihQC3EufqEY81vhXBgVBtK4prL+wc62zJsSvxrgz7K1hsdt6OObz6v9p3Rn1OG3GJksTTKMJF0u/guMISHPhSA=="], + + "@mariozechner/jiti": ["@mariozechner/jiti@2.6.5", "", { "dependencies": { "std-env": "^3.10.0", "yoctocolors": "^2.1.2" }, "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-faGUlTcXka5l7rv0lP3K3vGW/ejRuOS24RR2aSFWREUQqzjgdsuWNo/IiPqL3kWRGt6Ahl2+qcDAwtdeWeuGUw=="], + + "@mariozechner/pi-agent-core": ["@mariozechner/pi-agent-core@0.60.0", "", { "dependencies": { "@mariozechner/pi-ai": "^0.60.0" } }, "sha512-1zQcfFp8r0iwZCxCBQ9/ccFJoagns68cndLPTJJXl1ZqkYirzSld1zBOPxLAgeAKWIz3OX8dB2WQwTJFhmEojQ=="], + + "@mariozechner/pi-ai": ["@mariozechner/pi-ai@0.60.0", "", { "dependencies": { "@anthropic-ai/sdk": "^0.73.0", "@aws-sdk/client-bedrock-runtime": "^3.983.0", "@google/genai": "^1.40.0", "@mistralai/mistralai": "1.14.1", "@sinclair/typebox": "^0.34.41", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "chalk": "^5.6.2", "openai": "6.26.0", "partial-json": "^0.1.7", "proxy-agent": "^6.5.0", "undici": "^7.19.1", "zod-to-json-schema": "^3.24.6" }, "bin": { "pi-ai": "dist/cli.js" } }, "sha512-OiMuXQturnEDPmA+ho7eLe4G8plO2z21yjNMs9niQREauoblWOz7Glv58I66KPzczLED4aZTlQLTRdU6t1rz8A=="], + + "@mariozechner/pi-coding-agent": ["@mariozechner/pi-coding-agent@0.60.0", "", { "dependencies": { "@mariozechner/jiti": "^2.6.2", "@mariozechner/pi-agent-core": "^0.60.0", "@mariozechner/pi-ai": "^0.60.0", "@mariozechner/pi-tui": "^0.60.0", "@silvia-odwyer/photon-node": "^0.3.4", "chalk": "^5.5.0", "cli-highlight": "^2.1.11", "diff": "^8.0.2", "extract-zip": "^2.0.1", "file-type": "^21.1.1", "glob": "^13.0.1", "hosted-git-info": "^9.0.2", "ignore": "^7.0.5", "marked": "^15.0.12", "minimatch": "^10.2.3", "proper-lockfile": "^4.1.2", "strip-ansi": "^7.1.0", "undici": "^7.19.1", "yaml": "^2.8.2" }, "optionalDependencies": { "@mariozechner/clipboard": "^0.3.2" }, "bin": { "pi": "dist/cli.js" } }, "sha512-IOv7cTU4nbznFNUE5ofi13k2dmSG39coBoGWIBQTVw3iVyl0HxuHbg0NiTx3ktrPIDNtkii+y7tWXzWqwoo4lw=="], + + "@mariozechner/pi-tui": ["@mariozechner/pi-tui@0.60.0", "", { "dependencies": { "@types/mime-types": "^2.1.4", "chalk": "^5.5.0", "get-east-asian-width": "^1.3.0", "marked": "^15.0.12", "mime-types": "^3.0.1" }, "optionalDependencies": { "koffi": "^2.9.0" } }, "sha512-ZAK5gxYhGmfJqMjfWcRBjB8glITltDbTrYJXvcDtfengbKTZN0p39p5uO5pvUB8/PiAWKTRS06yaNMhf/LG26g=="], + "@microsoft/fetch-event-source": ["@microsoft/fetch-event-source@2.0.1", "", {}, "sha512-W6CLUJ2eBMw3Rec70qrsEW0jOm/3twwJv21mrmj2yORiaVmVYGS4sSS5yUwvQc1ZlDLYGPnClVWmUUMagKNsfA=="], "@mistralai/mistralai": ["@mistralai/mistralai@2.2.6", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.40.0", "ws": "^8.18.0", "zod": "^3.25.0 || ^4.0.0", "zod-to-json-schema": "^3.25.0" }, "peerDependencies": { "@opentelemetry/api": "^1.9.0" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-W8pX7zHxjJvMIpw8JMxeJEleapXX0Q9NPszdNzqkM3MIEoIGPObdodujj+WHteXEvGfaP/AMwlNyRfEzSY6dQQ=="], @@ -770,6 +900,20 @@ "@mongodb-js/zstd": ["@mongodb-js/zstd@7.0.0", "", { "dependencies": { "node-addon-api": "^8.5.0", "prebuild-install": "^7.1.3" } }, "sha512-mQ2s0pYYiav+tzCDR05Zptem8Ey2v8s11lri5RKGhTtL4COVCvVCk5vtyRYNT+9L8qSfyOqqefF9UtnW8mC5jA=="], + "@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ=="], + + "@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w=="], + + "@msgpackr-extract/msgpackr-extract-linux-arm": ["@msgpackr-extract/msgpackr-extract-linux-arm@3.0.4", "", { "os": "linux", "cpu": "arm" }, "sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw=="], + + "@msgpackr-extract/msgpackr-extract-linux-arm64": ["@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw=="], + + "@msgpackr-extract/msgpackr-extract-linux-x64": ["@msgpackr-extract/msgpackr-extract-linux-x64@3.0.4", "", { "os": "linux", "cpu": "x64" }, "sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ=="], + + "@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/msgpackr-extract-win32-x64@3.0.4", "", { "os": "win32", "cpu": "x64" }, "sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ=="], + + "@napi-rs/cli": ["@napi-rs/cli@2.18.4", "", { "bin": { "napi": "scripts/index.js" } }, "sha512-SgJeA4df9DE2iAEpr3M2H0OKl/yjtg1BnRI5/JyowS71tUWhrfSu2LT0V3vlHET+g1hBVlrO60PmEXwUEKp8Mg=="], + "@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.6", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" } }, "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg=="], "@noble/ciphers": ["@noble/ciphers@2.2.0", "", {}, "sha512-Z6pjIZ/8IJcCGzb2S/0Px5J81yij85xASuk1teLNeg75bfT07MV3a/O2Mtn1I2se43k3lkVEcFaR10N4cgQcZA=="], @@ -902,6 +1046,8 @@ "@oxlint/plugins": ["@oxlint/plugins@1.68.0", "", {}, "sha512-titLmukUt/h8ho7Svlf0xSBjoy2ccZKrXjpXpZCj+v6V4CJccC2KyP45BLSCMx8YIpifMyiDyUptM4+5sruKbQ=="], + "@pinojs/redact": ["@pinojs/redact@0.4.0", "", {}, "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg=="], + "@polka/url": ["@polka/url@1.0.0-next.29", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="], "@poppinss/colors": ["@poppinss/colors@4.1.6", "", { "dependencies": { "kleur": "^4.1.5" } }, "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg=="], @@ -1016,6 +1162,82 @@ "@remix-run/node-fetch-server": ["@remix-run/node-fetch-server@0.13.3", "", {}, "sha512-UfjOXed/DQteaM5VyTfqTeGpHwyL2J5aoRGY6cydip4tt1ehNNeSwuXCC7AEGE0RWBs/7bgKxYkL/B/+UDe4AA=="], + "@rivet-dev/agentos": ["@rivet-dev/agentos@0.2.7", "", { "dependencies": { "@agentos-software/common": "0.2.7", "@rivet-dev/agentos-core": "0.2.7", "@rivet-dev/agentos-sidecar": "0.2.7", "@rivetkit/react": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "rivetkit": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "zod": "^4.1.11" }, "optionalDependencies": { "@rivet-dev/agentos-plugin-darwin-arm64": "0.2.7", "@rivet-dev/agentos-plugin-darwin-x64": "0.2.7", "@rivet-dev/agentos-plugin-linux-arm64-gnu": "0.2.7", "@rivet-dev/agentos-plugin-linux-x64-gnu": "0.2.7" }, "peerDependencies": { "react": "^18 || ^19", "react-dom": "^18 || ^19" }, "optionalPeers": ["react", "react-dom"] }, "sha512-qJmkqu6NGZ4tbq9Vi3SsOqwTbY4Akm6G+inO6wfDJ8cCJH5LxDoip0ghATi0QM74pHWctOGZS8F+ZEuLE5ONvQ=="], + + "@rivet-dev/agentos-core": ["@rivet-dev/agentos-core@0.2.7", "", { "dependencies": { "@agentos-software/claude-code": "0.2.7", "@agentos-software/codex-cli": "0.3.3", "@agentos-software/common": "0.2.7", "@agentos-software/manifest": "0.2.7", "@agentos-software/opencode": "0.2.7", "@agentos-software/pi": "0.2.7", "@agentos-software/pi-cli": "0.2.7", "@aws-sdk/client-s3": "^3.1019.0", "@rivet-dev/agentos-runtime-core": "0.2.7", "@rivet-dev/agentos-sidecar": "0.2.7", "@rivetkit/bare-ts": "^0.6.2", "@xterm/headless": "^6.0.0", "better-sqlite3": "^12.8.0", "croner": "^10.0.1", "googleapis": "^144.0.0", "isolated-vm": "^6.0.0", "long-timeout": "^0.1.1", "minimatch": "^10.2.4", "zod": "^4.1.11", "zod-to-json-schema": "^3.25.2" } }, "sha512-7KC+eCo23lwaCYi+PoD8VxSg+BT46GesWFsAJBgTksKgOX2XOvDh3QKGKhNUU8ywwwtG4z3QpuRXe9kauXi6Zg=="], + + "@rivet-dev/agentos-plugin-darwin-arm64": ["@rivet-dev/agentos-plugin-darwin-arm64@0.2.7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-bYnR25T1zuC4V8GonnYNSrSEE3LADz17lSRzSP509bC2JTQL7L6Ztq+AY1Hs/iTJ+mK6j2PEdrj7bIG0SOTHDA=="], + + "@rivet-dev/agentos-plugin-darwin-x64": ["@rivet-dev/agentos-plugin-darwin-x64@0.2.7", "", { "os": "darwin", "cpu": "x64" }, "sha512-Rc4xoWb46VZfsAZMBLdmNX0aRQZs34sPGWH+AfM2WADvvZGbL1MSYEbRvdaC7wMjVrXiFJ9QpYDBBnD2L/x10Q=="], + + "@rivet-dev/agentos-plugin-linux-arm64-gnu": ["@rivet-dev/agentos-plugin-linux-arm64-gnu@0.2.7", "", { "os": "linux", "cpu": "arm64" }, "sha512-XWicGBQVOTCXL1CakZzqGRZ0U2oOVSOu4+R5j1wQBcv4IZWXJV5qHAVz44AW4YJmUsiG/MU3aK3UDOL/o+IzJQ=="], + + "@rivet-dev/agentos-plugin-linux-x64-gnu": ["@rivet-dev/agentos-plugin-linux-x64-gnu@0.2.7", "", { "os": "linux", "cpu": "x64" }, "sha512-7xxCD6M5ak/L8SuXPXR1xdRO0STf1gIHCSiFPBSPkQ0bAfLdOcV/LMJwolzMJqUWRRL68+MT4luQgysnKPeoiQ=="], + + "@rivet-dev/agentos-runtime-core": ["@rivet-dev/agentos-runtime-core@0.2.7", "", { "dependencies": { "@rivet-dev/agentos-runtime-sidecar": "0.2.7", "@rivetkit/bare-ts": "^0.6.2", "zod": "^4.1.11" } }, "sha512-Dih3ex/FIr69VhReUIAapBBNrghkA26IMlPs9fiWkrj0QEjdDTCMvfBkhseQelUdzmL6hCLnIrru2cQ29KwxCQ=="], + + "@rivet-dev/agentos-runtime-sidecar": ["@rivet-dev/agentos-runtime-sidecar@0.2.7", "", { "optionalDependencies": { "@rivet-dev/agentos-runtime-sidecar-darwin-arm64": "0.2.7", "@rivet-dev/agentos-runtime-sidecar-darwin-x64": "0.2.7", "@rivet-dev/agentos-runtime-sidecar-linux-arm64-gnu": "0.2.7", "@rivet-dev/agentos-runtime-sidecar-linux-x64-gnu": "0.2.7" } }, "sha512-QuAEG3/IKiBDlUbVYBNKc4h0TcT6DDYKlz58lwniv/L0v4qpJBwKLYikdSyNjp1H8eVZXFr7UsaaqFmuvCSsug=="], + + "@rivet-dev/agentos-runtime-sidecar-darwin-arm64": ["@rivet-dev/agentos-runtime-sidecar-darwin-arm64@0.2.7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-u14Mr7wp4h7IF8mc7jXREBh1xPOoLCzwMVUH/zpa/Y7eiGb6LE7RPW2n+nC0VpciiLf/7gYejU6QboJnhiq1uw=="], + + "@rivet-dev/agentos-runtime-sidecar-darwin-x64": ["@rivet-dev/agentos-runtime-sidecar-darwin-x64@0.2.7", "", { "os": "darwin", "cpu": "x64" }, "sha512-4IABmx8Pi7f76J8aMypln5dZs0qsWVXXW31oA7v4I3e11EGvCmsubjCEO+9YLvEuk6La3JcSO+685bs45twIvA=="], + + "@rivet-dev/agentos-runtime-sidecar-linux-arm64-gnu": ["@rivet-dev/agentos-runtime-sidecar-linux-arm64-gnu@0.2.7", "", { "os": "linux", "cpu": "arm64" }, "sha512-YHZFlGAljRMjceUsVU7e1GjTeM4QNj6/OjGcpprciyKosRNny8aoVsA4gJbe0dCNEbwVmO6peczFVAt5k54VEw=="], + + "@rivet-dev/agentos-runtime-sidecar-linux-x64-gnu": ["@rivet-dev/agentos-runtime-sidecar-linux-x64-gnu@0.2.7", "", { "os": "linux", "cpu": "x64" }, "sha512-wcHg/ifVWKqFosNN7YLNsP/SrZxZccd2UP2EPQHnIcRyMg+w14LpgdDcIsPWO/HvS7+78OwRsCck5IIOeonIUw=="], + + "@rivet-dev/agentos-sidecar": ["@rivet-dev/agentos-sidecar@0.2.7", "", { "optionalDependencies": { "@rivet-dev/agentos-sidecar-darwin-arm64": "0.2.7", "@rivet-dev/agentos-sidecar-darwin-x64": "0.2.7", "@rivet-dev/agentos-sidecar-linux-arm64-gnu": "0.2.7", "@rivet-dev/agentos-sidecar-linux-x64-gnu": "0.2.7" } }, "sha512-mui+hg8uWF3mjubp6YfpTW21TAqB+ZpA/VTSsKjngEw774oBkuvpY+eycxRbsxZIM4RMzl0EdHgCt8fFTGNxOQ=="], + + "@rivet-dev/agentos-sidecar-darwin-arm64": ["@rivet-dev/agentos-sidecar-darwin-arm64@0.2.7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-/FgUVxg27IQQ0swBXVBg8s3spaFk8tA+icQVa0KYC7eOZF+2fhNXcjuQrkCB9yoNHd2YMNrWp4PB/mQ16yg3Ag=="], + + "@rivet-dev/agentos-sidecar-darwin-x64": ["@rivet-dev/agentos-sidecar-darwin-x64@0.2.7", "", { "os": "darwin", "cpu": "x64" }, "sha512-akj3VqdmcPHPzBDwBYpScjeudjpEsTBJAL5iGnPUEoLA3hLJrBdoXovbR9xMQgixontPDYu4rvttiTQUt0doug=="], + + "@rivet-dev/agentos-sidecar-linux-arm64-gnu": ["@rivet-dev/agentos-sidecar-linux-arm64-gnu@0.2.7", "", { "os": "linux", "cpu": "arm64" }, "sha512-Hyrxo6Bh5aF6iqt076xN8VggxfCMN9qGkMb/BBH+LgtQQX2Pq76wJRZCltm8g5TOCxlczob8E5HqMdpCkw0Z9w=="], + + "@rivet-dev/agentos-sidecar-linux-x64-gnu": ["@rivet-dev/agentos-sidecar-linux-x64-gnu@0.2.7", "", { "os": "linux", "cpu": "x64" }, "sha512-blcgYjNG1zE3bI6SFOfhTHe8NrSm3QGannfNR6RQCoalif9Hf7bpxR/ha3uMKH+0fmlmuuc8LUi/O2N/uoiB9Q=="], + + "@rivetkit/bare-ts": ["@rivetkit/bare-ts@0.6.2", "", {}, "sha512-3qndQUQXLdwafMEqfhz24hUtDPcsf1Bu3q52Kb8MqeH8JUh3h6R4HYW3ZJXiQsLcyYyFM68PuIwlLRlg1xDEpg=="], + + "@rivetkit/engine-cli": ["@rivetkit/engine-cli@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "optionalDependencies": { "@rivetkit/engine-cli-darwin-arm64": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "@rivetkit/engine-cli-darwin-x64": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "@rivetkit/engine-cli-linux-arm64-musl": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "@rivetkit/engine-cli-linux-x64-musl": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0" } }, "sha512-7fq+rJt5+bujGV+Q0esDY3OJrzRUhEpYd2EV0oVUI+pcIRyYJMx2y7KrMUucqTFOr77O/NDlmSGTfD4cStRfrg=="], + + "@rivetkit/engine-cli-darwin-arm64": ["@rivetkit/engine-cli-darwin-arm64@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-kPzGTfdIIR5qAZpZDDRXC3OtGd8Jh/dZb/Pbmd03k/2DT12ILUHmI2DZg829icylExSSmhfRVjUSYsjRw8rmug=="], + + "@rivetkit/engine-cli-darwin-x64": ["@rivetkit/engine-cli-darwin-x64@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "os": "darwin", "cpu": "x64" }, "sha512-0rJcsIttFzycpR4J/ciECjPk+KzlVFeJwTPobhG9anWHycq8GpCuQx9ipgBA++01tZYo/x7kEfSU+dNdrxqsEA=="], + + "@rivetkit/engine-cli-linux-arm64-musl": ["@rivetkit/engine-cli-linux-arm64-musl@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "os": "linux", "cpu": "arm64" }, "sha512-jXh2SgMHm/JPwVGOlFSO1NGMy7/2t4lNwU/iSwX4CN1px9Nrr4Ud8n0FY58VHcU4Ppv1tWAdWEWsOlF5EZlr8Q=="], + + "@rivetkit/engine-cli-linux-x64-musl": ["@rivetkit/engine-cli-linux-x64-musl@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "os": "linux", "cpu": "x64" }, "sha512-pDBkdi5la//sp7Uq1KXDR4eXbwO0l/HmQCnosbgWHWz8OBL62RcueeYWQt181Gl7VIsINm1QB7mihUcbcECVxw=="], + + "@rivetkit/engine-envoy-protocol": ["@rivetkit/engine-envoy-protocol@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "dependencies": { "@rivetkit/bare-ts": "^0.6.2" } }, "sha512-2u0MPsYLMSuwaX0amz52kZX4wsh3PmbczjPb4AoSk1hCbycf1IN3Vkj3RR87ZwMTlLYKkcpgq8fHPlxoPSkftQ=="], + + "@rivetkit/framework-base": ["@rivetkit/framework-base@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "dependencies": { "@tanstack/store": "^0.7.1", "fast-deep-equal": "^3.1.3", "rivetkit": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0" } }, "sha512-513zdVQgSYQeQ3nXu5RTjVxvwhpAcfn6bKXpcb9XLFli+wux07oTcszo6HCsqfeChEO19LAXWysWbEDMzwYU3g=="], + + "@rivetkit/on-change": ["@rivetkit/on-change@6.0.1", "", {}, "sha512-QBN/KRBXLJdCgN4gBTL3XAc/zKm58atSnieXWMOyFSPmo6F1/yIVV/LTRdvAktfCttrGx7W6c32i/lwqCHWnsQ=="], + + "@rivetkit/react": ["@rivetkit/react@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "dependencies": { "@rivetkit/framework-base": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "@tanstack/react-store": "^0.7.1", "rivetkit": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0" }, "peerDependencies": { "react": "^18 || ^19", "react-dom": "^18 || ^19" } }, "sha512-7iHF3wGl4y2S+v700QgXEqBOjtJr/5AZ20qfD5rwE3dtBY8H5Smw4FllJTxBuUrdzHjZ2L7C8LyGALWi/5e1NQ=="], + + "@rivetkit/rivetkit-napi": ["@rivetkit/rivetkit-napi@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "dependencies": { "@napi-rs/cli": "^2.18.4", "@rivetkit/engine-envoy-protocol": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0" }, "optionalDependencies": { "@rivetkit/rivetkit-napi-darwin-arm64": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "@rivetkit/rivetkit-napi-darwin-x64": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "@rivetkit/rivetkit-napi-linux-arm64-gnu": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "@rivetkit/rivetkit-napi-linux-arm64-musl": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "@rivetkit/rivetkit-napi-linux-x64-gnu": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "@rivetkit/rivetkit-napi-linux-x64-musl": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0" } }, "sha512-uSBQFnTSuh+YMjdRR34KAS7QJQpkVXNleNdzLoCic1XdRyIh13KvuX3+JR3bbk3S32euM7ZeScy3kve8c3nuyA=="], + + "@rivetkit/rivetkit-napi-darwin-arm64": ["@rivetkit/rivetkit-napi-darwin-arm64@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-TQPCk1U2Z7otH9ehV7NEEksRT/hzEsLyMaA7ZpkMKxOr8bBNWkES7U+YY5fc7mLFdWR/N15iN7SU0koxJE7PjA=="], + + "@rivetkit/rivetkit-napi-darwin-x64": ["@rivetkit/rivetkit-napi-darwin-x64@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "os": "darwin", "cpu": "x64" }, "sha512-wAuJIR0efIcpaQQvWgniZ0qOy6x5+/V+/agACJhQVSjj7P29kY0piEBKLKDtP0M4gTd6GGzBAe5oNY0t785/0w=="], + + "@rivetkit/rivetkit-napi-linux-arm64-gnu": ["@rivetkit/rivetkit-napi-linux-arm64-gnu@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "os": "linux", "cpu": "arm64" }, "sha512-A+kuGvc9RJjUflPVHbHPkQSH4xyjasbVMNRfq2ISdaJ/CnNcmrexJ4F+5Mm2VPz61gxNjkSoyk8tPupz07CZnw=="], + + "@rivetkit/rivetkit-napi-linux-arm64-musl": ["@rivetkit/rivetkit-napi-linux-arm64-musl@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "os": "linux", "cpu": "arm64" }, "sha512-jo7WcmJ7hjWpi/8DUlWu1x2JtHfEAiY21QdNy5VZ23Dtg/pzKzDAn4m6myPB/s8MS+nAOiJcruWTH16qMHAeWw=="], + + "@rivetkit/rivetkit-napi-linux-x64-gnu": ["@rivetkit/rivetkit-napi-linux-x64-gnu@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "os": "linux", "cpu": "x64" }, "sha512-hcHO0FkMQITQ3taSJ0084DVDRysOep3eBzv8cwgA0qJhIzzd5EF+4qo4QO4woEdnDYCGMBJZLByYyEPFY3WSOQ=="], + + "@rivetkit/rivetkit-napi-linux-x64-musl": ["@rivetkit/rivetkit-napi-linux-x64-musl@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "os": "linux", "cpu": "x64" }, "sha512-Xx8DWZwdWBZdkqSbR7UdPR1nrZH53tK4r0kSM9Y670GGwgBHg3mesaYshPs/B0XzEFVybF5vS/0ToIi97T/LIw=="], + + "@rivetkit/rivetkit-wasm": ["@rivetkit/rivetkit-wasm@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", {}, "sha512-8bTqxP4WihKbKifZHZT1umnINvlv1NU+GfciQ+pciiIxnaPVT7dX++IczTB2g3njEibYL44wrEzicNNXNsf6lg=="], + + "@rivetkit/traces": ["@rivetkit/traces@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "dependencies": { "@rivetkit/bare-ts": "^0.6.2", "cbor-x": "^1.6.0", "fdb-tuple": "^1.0.0", "vbare": "^0.0.4" } }, "sha512-4yXOCC2rPncF/aNBhW4KU6CF56Bo9Sslidj311eY0iGqCxRBpQhI57Y5eX8Ho5DNXmVTobjP6USxeWp6Oymmvg=="], + + "@rivetkit/virtual-websocket": ["@rivetkit/virtual-websocket@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", {}, "sha512-Rd3MdziVAS4Ut/dqcLfN9pMCRLOSqK7n/AunWtI6Xr72y+0jh7gwFVYmZRJGyGamnfJFTKTQnbnhg+KGkyu+wg=="], + + "@rivetkit/workflow-engine": ["@rivetkit/workflow-engine@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "dependencies": { "@rivetkit/bare-ts": "^0.6.2", "cbor-x": "^1.6.0", "fdb-tuple": "^1.0.0", "pino": "^9.6.0", "vbare": "^0.0.4" } }, "sha512-Nh+tlQT9FoBsznHfRujeT/hlgj/4k4d3M7+0ogZpCmPhuwim0cjiog6fL18bfehr7BPobvSH0SInqLvF3kPPWA=="], + "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.1.4", "", { "os": "android", "cpu": "arm64" }, "sha512-EZLpf/8y7GXkkra90ML47kzik/GMP3EMcE9bPyHmRfxLC6z9+aW5A8poCsoxjrT5GfEcNAAvWwUHjvP1pUQkfw=="], "@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.1.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-aUi+HBvmYb7j8krl1+qJgkG8C17fO79gk3c+jPw4S8glRFc1DTija9S3EyaTSQUm5GJXYKDAsugBEhFHH2vYiQ=="], @@ -1056,6 +1278,8 @@ "@shadcn/react": ["@shadcn/react@0.2.1", "", { "peerDependencies": { "@types/react": ">=19", "react": ">=19" }, "optionalPeers": ["@types/react", "react"] }, "sha512-5krgi3dRMKb5jH6a+qPzVJUy/54s0kKE4Rw4LjDfLqOdVQTWKUgxWf1kW8r912I0jX/Lzxqc+pgjkjWxUIK5BQ=="], + "@silvia-odwyer/photon-node": ["@silvia-odwyer/photon-node@0.3.4", "", {}, "sha512-bnly4BKB3KDTFxrUIcgCLbaeVVS8lrAkri1pEzskpmxu9MdfGQTy8b8EgcD83ywD3RPMsIulY8xJH5Awa+t9fA=="], + "@sinclair/typebox": ["@sinclair/typebox@0.27.12", "", {}, "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g=="], "@sindresorhus/is": ["@sindresorhus/is@7.2.0", "", {}, "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw=="], @@ -1200,6 +1424,8 @@ "@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="], + "@types/mime-types": ["@types/mime-types@2.1.4", "", {}, "sha512-lfU4b34HOri+kAY5UheuFMWPDOI+OPceBSHZKp69gEyTL/mmJ4cnU6Y/rlme3UL3GyOn6Y42hyIEw0/q8sWx5w=="], + "@types/node": ["@types/node@22.20.1", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q=="], "@types/react": ["@types/react@19.2.17", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw=="], @@ -1208,7 +1434,7 @@ "@types/react-test-renderer": ["@types/react-test-renderer@19.1.0", "", { "dependencies": { "@types/react": "*" } }, "sha512-XD0WZrHqjNrxA/MaR9O22w/RNidWR9YZmBdRGI7wcnWGrv/3dA8wKCJ8m63Sn+tLJhcjmuhOi629N66W6kgWzQ=="], - "@types/retry": ["@types/retry@0.12.0", "", {}, "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA=="], + "@types/retry": ["@types/retry@0.12.2", "", {}, "sha512-XISRgDJ2Tc5q4TRqvgJtzsRkFYNJzZrhTdtMoGVBttwzzQJkPnS3WWTFc7kuDRoPtPakl+T+OfdEUjYJj7Jbow=="], "@types/stats.js": ["@types/stats.js@0.17.4", "", {}, "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA=="], @@ -1218,10 +1444,14 @@ "@types/webxr": ["@types/webxr@0.5.24", "", {}, "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg=="], + "@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="], + "@types/yargs": ["@types/yargs@17.0.35", "", { "dependencies": { "@types/yargs-parser": "*" } }, "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg=="], "@types/yargs-parser": ["@types/yargs-parser@21.0.3", "", {}, "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ=="], + "@types/yauzl": ["@types/yauzl@2.10.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="], + "@typescript-eslint/project-service": ["@typescript-eslint/project-service@8.64.0", "", { "dependencies": { "@typescript-eslint/tsconfig-utils": "^8.64.0", "@typescript-eslint/types": "^8.64.0", "debug": "^4.4.3" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-tk4WpOJ6IEbGrVHaNmM0YRrwAD3exZlIK3iadQNAxh4YKk6jvUQ4ecq18n+v7+meh+cJ3j+D8nbk8sRKhlwLQg=="], "@typescript-eslint/scope-manager": ["@typescript-eslint/scope-manager@8.64.0", "", { "dependencies": { "@typescript-eslint/types": "8.64.0", "@typescript-eslint/visitor-keys": "8.64.0" } }, "sha512-CXEaFdYXjSTgKhisNkwCcJwTP8Pl+fmRrEQrri4nm3vU743bALrxzLmq7fHG/7e6a5xO0lDYeURpZmBuhHk54w=="], @@ -1280,6 +1510,8 @@ "@xmldom/xmldom": ["@xmldom/xmldom@0.8.13", "", {}, "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw=="], + "@xterm/headless": ["@xterm/headless@6.0.0", "", {}, "sha512-5Yj1QINYCyzrZtf8OFIHi47iQtI+0qYFPHmouEfG8dHNxbZ9Tb9YGSuLcsEwj9Z+OL75GJqPyJbyoFer80a2Hw=="], + "abort-controller": ["abort-controller@3.0.0", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="], "accepts": ["accepts@1.3.8", "", { "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" } }, "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw=="], @@ -1306,6 +1538,8 @@ "ansi-styles": ["ansi-styles@5.2.0", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="], + "any-promise": ["any-promise@1.3.0", "", {}, "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A=="], + "anynum": ["anynum@1.0.1", "", {}, "sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A=="], "arg": ["arg@5.0.2", "", {}, "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg=="], @@ -1322,6 +1556,8 @@ "ast-types": ["ast-types@0.16.1", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg=="], + "atomic-sleep": ["atomic-sleep@1.0.0", "", {}, "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ=="], + "atomically": ["atomically@1.7.0", "", {}, "sha512-Xcz9l0z7y9yQ9rdDaxlmaI4uJHf/T8g9hOEzJcsEqX2SjCj4J20uK7+ldkDHMbpJDK76wF7xEIgxc/vSlsfw5w=="], "babel-dead-code-elimination": ["babel-dead-code-elimination@1.0.12", "", { "dependencies": { "@babel/core": "^7.23.7", "@babel/parser": "^7.23.6", "@babel/traverse": "^7.23.7", "@babel/types": "^7.23.6" } }, "sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig=="], @@ -1356,10 +1592,14 @@ "better-call": ["better-call@1.3.5", "", { "dependencies": { "@better-auth/utils": "^0.4.0", "@better-fetch/fetch": "^1.1.21", "rou3": "^0.7.12", "set-cookie-parser": "^3.0.1" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-kOFJkBP7utAQLEYrobZm3vkTH8mXq5GNgvjc5/XEST1ilVHaxXUXfeDeFlqoETMtyqS4+3/h4ONX2i++ebZrvA=="], + "better-sqlite3": ["better-sqlite3@12.11.1", "", { "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" } }, "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA=="], + "big-integer": ["big-integer@1.6.52", "", {}, "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg=="], "bignumber.js": ["bignumber.js@9.3.1", "", {}, "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ=="], + "bindings": ["bindings@1.5.0", "", { "dependencies": { "file-uri-to-path": "1.0.0" } }, "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ=="], + "bl": ["bl@4.1.0", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="], "blake3-wasm": ["blake3-wasm@2.1.5", "", {}, "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g=="], @@ -1384,6 +1624,8 @@ "buffer": ["buffer@5.7.1", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="], + "buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="], + "buffer-equal-constant-time": ["buffer-equal-constant-time@1.0.1", "", {}, "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="], "buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="], @@ -1406,6 +1648,10 @@ "caniuse-lite": ["caniuse-lite@1.0.30001806", "", {}, "sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw=="], + "cbor-extract": ["cbor-extract@2.2.2", "", { "dependencies": { "node-gyp-build-optional-packages": "5.1.1" }, "optionalDependencies": { "@cbor-extract/cbor-extract-darwin-arm64": "2.2.2", "@cbor-extract/cbor-extract-darwin-x64": "2.2.2", "@cbor-extract/cbor-extract-linux-arm": "2.2.2", "@cbor-extract/cbor-extract-linux-arm64": "2.2.2", "@cbor-extract/cbor-extract-linux-x64": "2.2.2", "@cbor-extract/cbor-extract-win32-x64": "2.2.2" }, "bin": { "download-cbor-prebuilds": "bin/download-prebuilds.js" } }, "sha512-hlSxxI9XO2yQfe9g6msd3g4xCfDqK5T5P0fRMLuaLHhxn4ViPrm+a+MUfhrvH2W962RGxcBwEGzLQyjbDG1gng=="], + + "cbor-x": ["cbor-x@1.6.4", "", { "optionalDependencies": { "cbor-extract": "^2.2.2" } }, "sha512-UGKHjp6RHC6QuZ2yy5LCKm7MojM4716DwoSaqwQpaH4DvZvbBTGcoDNTiG9Y2lByXZYFEs9WRkS5tLl96IrF1Q=="], + "chai": ["chai@6.2.2", "", {}, "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg=="], "chain-function": ["chain-function@1.0.1", "", {}, "sha512-SxltgMwL9uCko5/ZCLiyG2B7R9fY4pDZUw7hJ4MhirdjBLosoDqkWABi3XMucddHdLiFJMb7PD2MZifZriuMTg=="], @@ -1430,6 +1676,8 @@ "cli-cursor": ["cli-cursor@5.0.0", "", { "dependencies": { "restore-cursor": "^5.0.0" } }, "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw=="], + "cli-highlight": ["cli-highlight@2.1.11", "", { "dependencies": { "chalk": "^4.0.0", "highlight.js": "^10.7.1", "mz": "^2.4.0", "parse5": "^5.1.1", "parse5-htmlparser2-tree-adapter": "^6.0.0", "yargs": "^16.0.0" }, "bin": { "highlight": "bin/highlight" } }, "sha512-9KDcoEVwyUXrjcJNvHD0NFc/hiwe/WPVYIleQh2O1N2Zro5gWJZ/K+3DGn8w8P/F6FxOgzyC5bxDyHIgCSPhGg=="], + "cli-spinners": ["cli-spinners@2.9.2", "", {}, "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg=="], "client-only": ["client-only@0.0.1", "", {}, "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA=="], @@ -1488,6 +1736,8 @@ "cosmiconfig": ["cosmiconfig@9.0.2", "", { "dependencies": { "env-paths": "^2.2.1", "import-fresh": "^3.3.0", "js-yaml": "^4.1.0", "parse-json": "^5.2.0" }, "peerDependencies": { "typescript": ">=4.9.5" }, "optionalPeers": ["typescript"] }, "sha512-gtTZxTDau1wL7Y7zifc2dd8jHSK/k6BTx/2Xp/BpdlAdnlYWFVt7qhJqgwi7637yRwRQ3qL4ZidbB4I8tA5VOg=="], + "croner": ["croner@10.0.1", "", {}, "sha512-ixNtAJndqh173VQ4KodSdJEI6nuioBWI0V1ITNKhZZsO0pEMoDxz539T4FTTbSZ/xIOSuDnzxLVRqBVSvPNE2g=="], + "cross-fetch": ["cross-fetch@3.2.0", "", { "dependencies": { "node-fetch": "^2.7.0" } }, "sha512-Q+xVJLoGOeIMXZmbUK4HYk+69cQH6LudR0Vu/pRm2YlU/hDV9CiS0gKUMaWY5f2NeUH9C1nV3bsTlCo0FsTV1Q=="], "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], @@ -1534,6 +1784,8 @@ "d3-zoom": ["d3-zoom@3.0.0", "", { "dependencies": { "d3-dispatch": "1 - 3", "d3-drag": "2 - 3", "d3-interpolate": "1 - 3", "d3-selection": "2 - 3", "d3-transition": "2 - 3" } }, "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw=="], + "daemon": ["daemon@workspace:apps/daemon"], + "data-uri-to-buffer": ["data-uri-to-buffer@6.0.2", "", {}, "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw=="], "dayjs": ["dayjs@1.11.21", "", {}, "sha512-98IT+HOahAisibz/yjKbzuOBwYcjJ7BCLPzARyHiyEBmRz4fatF+KPJszEHXsGYjUG234aH/cOjW1wwTbKUZlA=="], @@ -1598,12 +1850,16 @@ "dotenv": ["dotenv@17.4.2", "", {}, "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw=="], + "drizzle-orm": ["drizzle-orm@0.44.7", "", { "peerDependencies": { "@aws-sdk/client-rds-data": ">=3", "@cloudflare/workers-types": ">=4", "@electric-sql/pglite": ">=0.2.0", "@libsql/client": ">=0.10.0", "@libsql/client-wasm": ">=0.10.0", "@neondatabase/serverless": ">=0.10.0", "@op-engineering/op-sqlite": ">=2", "@opentelemetry/api": "^1.4.1", "@planetscale/database": ">=1.13", "@prisma/client": "*", "@tidbcloud/serverless": "*", "@types/better-sqlite3": "*", "@types/pg": "*", "@types/sql.js": "*", "@upstash/redis": ">=1.34.7", "@vercel/postgres": ">=0.8.0", "@xata.io/client": "*", "better-sqlite3": ">=7", "bun-types": "*", "expo-sqlite": ">=14.0.0", "gel": ">=2", "knex": "*", "kysely": "*", "mysql2": ">=2", "pg": ">=8", "postgres": ">=3", "prisma": "*", "sql.js": ">=1", "sqlite3": ">=5" }, "optionalPeers": ["@aws-sdk/client-rds-data", "@cloudflare/workers-types", "@electric-sql/pglite", "@libsql/client", "@libsql/client-wasm", "@neondatabase/serverless", "@op-engineering/op-sqlite", "@opentelemetry/api", "@planetscale/database", "@prisma/client", "@tidbcloud/serverless", "@types/better-sqlite3", "@types/pg", "@types/sql.js", "@upstash/redis", "@vercel/postgres", "@xata.io/client", "better-sqlite3", "bun-types", "expo-sqlite", "gel", "knex", "kysely", "mysql2", "pg", "postgres", "prisma", "sql.js", "sqlite3"] }, "sha512-quIpnYznjU9lHshEOAYLoZ9s3jweleHlZIAWR/jX9gAWNg/JhQ1wj0KGRf7/Zm+obRrYd9GjPVJg790QY9N5AQ=="], + "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], "ecdsa-sig-formatter": ["ecdsa-sig-formatter@1.0.11", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ=="], "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], + "effect": ["effect@4.0.0-beta.99", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.9.0", "find-my-way-ts": "^0.1.6", "ini": "^7.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^2.0.4", "multipasta": "^0.2.8", "toml": "^4.1.2", "uuid": "^14.0.1", "yaml": "^2.9.0" } }, "sha512-hP1C61uzINfLl/4kKMwcqksxd34s4sQ3VSjsWjhGrkx9CRlXaqnfOK9dpTEKynQ6rA7wU9rb3c+48eDYw7uzxA=="], + "electrobun": ["electrobun@1.18.1", "", { "dependencies": { "@babylonjs/core": "^7.45.0", "@types/bun": "^1.3.8", "png-to-ico": "^2.1.8", "proxy-agent": "^6.5.0", "rcedit": "^4.0.1", "three": "^0.165.0" }, "bin": { "electrobun": "bin/electrobun.cjs" } }, "sha512-tgZ+WKGskn/1/Y5i1mpVCCkgRa1O31Tz7MIArBTK44GfPzT43uOq9c/HvxdQGrLeZV8ZvjK1lQrwqSXCgh6tvA=="], "electron-to-chromium": ["electron-to-chromium@1.5.393", "", {}, "sha512-kiDJdIUawuEIcp9XoICKp1iTYDEbgguIPq526N1Q7jIQDeQ3CqoMx71025PI/7E48Ddtw2HuWsVjY7afEgNxmg=="], @@ -1730,6 +1986,10 @@ "extend": ["extend@3.0.2", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="], + "extract-zip": ["extract-zip@2.0.1", "", { "dependencies": { "debug": "^4.1.1", "get-stream": "^5.1.0", "yauzl": "^2.10.0" }, "optionalDependencies": { "@types/yauzl": "^2.9.1" }, "bin": { "extract-zip": "cli.js" } }, "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg=="], + + "fast-check": ["fast-check@4.9.0", "", { "dependencies": { "pure-rand": "^8.0.0" } }, "sha512-7ms6T7SybUev/PQITciI0yLM2pOSFy5zpG8Ty7tQofcVaQUvrMXp6CBwqF6fThLCLOrfBtuHAtwq6Yu4XPCllg=="], + "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], "fast-glob": ["fast-glob@3.3.3", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.8" } }, "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg=="], @@ -1760,6 +2020,10 @@ "fbjs-css-vars": ["fbjs-css-vars@1.0.2", "", {}, "sha512-b2XGFAFdWZWg0phtAWLHCk836A1Xann+I+Dgd3Gk64MHKZO44FfoD1KxyvbSh0qZsIoXQGGlVztIY+oitJPpRQ=="], + "fd-slicer": ["fd-slicer@1.1.0", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g=="], + + "fdb-tuple": ["fdb-tuple@1.0.0", "", {}, "sha512-8jSvKPCYCgTpi9Pt87qlfTk6griyMx4Gk3Xv31Dp72Qp8b6XgIyFsMm8KzPmFJ9iJ8K4pGvRxvOS8D0XGnrkjw=="], + "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], "fetch-blob": ["fetch-blob@3.2.0", "", { "dependencies": { "node-domexception": "^1.0.0", "web-streams-polyfill": "^3.0.3" } }, "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ=="], @@ -1774,12 +2038,16 @@ "file-type": ["file-type@21.3.4", "", { "dependencies": { "@tokenizer/inflate": "^0.4.1", "strtok3": "^10.3.4", "token-types": "^6.1.1", "uint8array-extras": "^1.4.0" } }, "sha512-Ievi/yy8DS3ygGvT47PjSfdFoX+2isQueoYP1cntFW1JLYAuS4GD7NUPGg4zv2iZfV52uDyk5w5Z0TdpRS6Q1g=="], + "file-uri-to-path": ["file-uri-to-path@1.0.0", "", {}, "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="], + "fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="], "filter-obj": ["filter-obj@1.1.0", "", {}, "sha512-8rXg1ZnX7xzy2NGDVkBVaAy+lSlPNwad13BtgSlLuxfIslyt5Vg64U7tFcCt4WS1R0hvtnQybT/IyCkGZ3DpXQ=="], "finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="], + "find-my-way-ts": ["find-my-way-ts@0.1.6", "", {}, "sha512-a85L9ZoXtNAey3Y6Z+eBWW658kO/MwR7zIafkIUPUMf3isZG0NCs2pjW2wtjxAKuJPxMAsHUIP4ZPGv0o5gyTA=="], + "find-up": ["find-up@5.0.0", "", { "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" } }, "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng=="], "find-up-simple": ["find-up-simple@1.0.1", "", {}, "sha512-afd4O7zpqHeRyg4PfDQsXmlDe2PfdHtJt6Akt8jOWaApLOZk5JXs6VMR29lz03pRe9mpykrRCYIYxaJYcfpncQ=="], @@ -1848,10 +2116,16 @@ "google-logging-utils": ["google-logging-utils@1.1.3", "", {}, "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA=="], + "googleapis": ["googleapis@144.0.0", "", { "dependencies": { "google-auth-library": "^9.0.0", "googleapis-common": "^7.0.0" } }, "sha512-ELcWOXtJxjPX4vsKMh+7V+jZvgPwYMlEhQFiu2sa9Qmt5veX8nwXPksOWGGN6Zk4xCiLygUyaz7xGtcMO+Onxw=="], + + "googleapis-common": ["googleapis-common@7.2.0", "", { "dependencies": { "extend": "^3.0.2", "gaxios": "^6.0.3", "google-auth-library": "^9.7.0", "qs": "^6.7.0", "url-template": "^2.0.8", "uuid": "^9.0.0" } }, "sha512-/fhDZEJZvOV3X5jmD+fKxMqma5q2Q9nZNSF3kn1F18tpxmA86BcTxAGBQdM0N89Z3bEaIs+HVznSmFJEAmMTjA=="], + "gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="], "graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="], + "gtoken": ["gtoken@7.1.0", "", { "dependencies": { "gaxios": "^6.0.0", "jws": "^4.0.0" } }, "sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw=="], + "has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="], "has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="], @@ -1866,6 +2140,8 @@ "heroui-native": ["heroui-native@1.0.5", "", { "peerDependencies": { "@gorhom/bottom-sheet": "^5.2.9", "react": ">=19.0.0", "react-native": ">=0.81.0", "react-native-gesture-handler": "^2.28.0", "react-native-reanimated": "^4.1.1", "react-native-safe-area-context": "^5.6.0", "react-native-screens": ">=4", "react-native-svg": "^15.12.1", "react-native-worklets": ">=0.5.1", "tailwind-merge": "^3.4.0", "tailwind-variants": "^3.2.2" }, "optionalPeers": ["@gorhom/bottom-sheet", "react-native-screens"] }, "sha512-8yE2N4aI9dhg0VYsLPxORgqOnThq1iBsTjZkqyKElkIWxsN8LxTp9shlrQR6bz1VasGn+xAilpzmKerUfPopAQ=="], + "highlight.js": ["highlight.js@10.7.3", "", {}, "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A=="], + "hoist-non-react-statics": ["hoist-non-react-statics@3.3.2", "", { "dependencies": { "react-is": "^16.7.0" } }, "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw=="], "hono": ["hono@4.12.30", "", {}, "sha512-emn+JoJjrN9YTpRDS5it/UI2SO9BAE37T6I3d963RxcZ81G9A4pr2SZTEiiaiKbzx+NKRg5BZ89fCL7gCJCUog=="], @@ -1900,7 +2176,7 @@ "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], - "ini": ["ini@6.0.0", "", {}, "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ=="], + "ini": ["ini@7.0.0", "", {}, "sha512-ifK0CgjALofS5bkrcTy4RaQ9Vx2Knf/eLeIO+NaswQEpH1UblrtTSCIvN71qQDMq0PeQ/SSPojvEJp9vvvfr+w=="], "inline-style-prefixer": ["inline-style-prefixer@7.0.1", "", { "dependencies": { "css-in-js-utils": "^3.1.0" } }, "sha512-lhYo5qNTQp3EvSSp3sRvXMbVQTLrvGV6DycRMJ5dm2BLMiJ30wpXKdDdgX+GmJZ5uQMucwRKHamXSst3Sj/Giw=="], @@ -1928,6 +2204,8 @@ "is-interactive": ["is-interactive@2.0.0", "", {}, "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ=="], + "is-network-error": ["is-network-error@1.3.2", "", {}, "sha512-PhBY86zaxNZUuWP6h13Vu5oFe0XY6/UlKzQnYFELzGVHygP3MxmvTfYSG7GN3aIab/iWudSMgjSnG9Dq+nHrgA=="], + "is-number": ["is-number@7.0.0", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="], "is-obj": ["is-obj@3.0.0", "", {}, "sha512-IlsXEHOjtKhpN8r/tRFj2nDyTmHvcfNeu/nrRIcXE17ROeatXchkojffa1SpdqW4cr/Fj6QkEf/Gn4zf6KKvEQ=="], @@ -1950,6 +2228,8 @@ "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], + "isolated-vm": ["isolated-vm@6.1.2", "", { "dependencies": { "node-gyp-build": "^4.8.4" } }, "sha512-GGfsHqtlZiiurZaxB/3kY7LLAXR3sgzDul0fom4cSyBjx6ZbjpTrFWiH3z/nUfLJGJ8PIq9LQmQFiAxu24+I7A=="], + "jest-get-type": ["jest-get-type@29.6.3", "", {}, "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw=="], "jest-util": ["jest-util@29.7.0", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "ci-info": "^3.2.0", "graceful-fs": "^4.2.9", "picomatch": "^2.2.3" } }, "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA=="], @@ -2002,6 +2282,10 @@ "kleur": ["kleur@4.1.5", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="], + "koffi": ["koffi@2.16.2", "", {}, "sha512-owU0MRwv6xkrVqCd+33uw6BaYppkTRXbO/rVdJNI2dvZG0gzyRhYwW25eWtc5pauwK8TGh3AbkFONSezdykfSA=="], + + "kubernetes-types": ["kubernetes-types@1.30.0", "", {}, "sha512-Dew1okvhM/SQcIa2rcgujNndZwU8VnSapDgdxlYoB84ZlpAD43U6KLAFqYo17ykSFGHNPrg0qry0bP+GJd9v7Q=="], + "kysely": ["kysely@0.29.4", "", {}, "sha512-y5mVgQNkMbs1eK9Xyc0pmNdabN2wHhRYY/5r4W5HrUT1rYCEPeVNSj1RUJeSDKT3U0p+mXCvLgkrFuIafYI6BA=="], "lan-network": ["lan-network@0.2.1", "", { "bin": { "lan-network": "dist/lan-network-cli.js" } }, "sha512-ONPnazC96VKDntab9j9JKwIWhZ4ZUceB4A9Epu4Ssg0hYFmtHZSeQ+n15nIwTFmcBUKtExOer8WTJ4GF9MO64A=="], @@ -2054,6 +2338,8 @@ "long": ["long@5.3.2", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="], + "long-timeout": ["long-timeout@0.1.1", "", {}, "sha512-BFRuQUqc7x2NWxfJBCyUrN8iYUYznzL9JROmRz1gZ6KlOIgmoD+njPVbb+VNn2nGMKggMsK79iUNErillsrx7w=="], + "loose-envify": ["loose-envify@1.4.0", "", { "dependencies": { "js-tokens": "^3.0.0 || ^4.0.0" }, "bin": { "loose-envify": "cli.js" } }, "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q=="], "lru-cache": ["lru-cache@7.18.3", "", {}, "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA=="], @@ -2156,8 +2442,16 @@ "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + "msgpackr": ["msgpackr@2.0.4", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.4" } }, "sha512-o1C5KRmuRt+apqMr1HuGSqWStZoRBUpEsCsl15uM9VdAF1qHLtvMOU2En747EnTyEl6c4pzPewRMFF31s1CNbA=="], + + "msgpackr-extract": ["msgpackr-extract@3.0.4", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.4", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.4", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.4" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw=="], + + "multipasta": ["multipasta@0.2.8", "", {}, "sha512-ZPWuMKyv0cSO29f7hozp+k6+crZbQijV8ipMvxNxRf2SwtYGTX1ZX89Kd20VV4H9Znonx+EQn+iy1wGQsJ+b+Q=="], + "multitars": ["multitars@1.0.0", "", {}, "sha512-H/J4fMLedtudftaYMOg7ajzLYgT3/rwbWVJbqr/iUgB8DQztn38ys5HOqI1CzSxx8QhXXwOOnnBvd4v3jG5+Mg=="], + "mz": ["mz@2.7.0", "", { "dependencies": { "any-promise": "^1.0.0", "object-assign": "^4.0.1", "thenify-all": "^1.0.0" } }, "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q=="], + "nanoid": ["nanoid@3.3.16", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q=="], "nanostores": ["nanostores@1.4.0", "", {}, "sha512-i0tloweeudshAEuddpDxcg9Ik6pkPfVsHIgKyf143JrgG7/MOh0+q7BypdLXZPoOP7fOYt1eTcwGkyiVmhJFkA=="], @@ -2186,6 +2480,8 @@ "node-gyp-build": ["node-gyp-build@4.8.4", "", { "bin": { "node-gyp-build": "bin.js", "node-gyp-build-optional": "optional.js", "node-gyp-build-test": "build-test.js" } }, "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ=="], + "node-gyp-build-optional-packages": ["node-gyp-build-optional-packages@5.2.2", "", { "dependencies": { "detect-libc": "^2.0.1" }, "bin": { "node-gyp-build-optional-packages": "bin.js", "node-gyp-build-optional-packages-optional": "optional.js", "node-gyp-build-optional-packages-test": "build-test.js" } }, "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw=="], + "node-int64": ["node-int64@0.4.0", "", {}, "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw=="], "node-liblzma": ["node-liblzma@2.2.0", "", { "dependencies": { "node-addon-api": "^8.5.0", "node-gyp-build": "^4.8.4" }, "bin": { "nxz": "lib/cli/nxz.js" } }, "sha512-s0KzNOWwOJJgPG6wxg6cKohnAl9Wk/oW1KrQaVzJBjQwVcUGPQCzpR46Ximygjqj/3KhOrtJXnYMp/xYAXp75g=="], @@ -2212,6 +2508,8 @@ "obug": ["obug@2.1.4", "", {}, "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA=="], + "on-exit-leak-free": ["on-exit-leak-free@2.1.2", "", {}, "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA=="], + "on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="], "on-headers": ["on-headers@1.1.0", "", {}, "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A=="], @@ -2226,6 +2524,8 @@ "openapi-types": ["openapi-types@12.1.3", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="], + "openapi3-ts": ["openapi3-ts@4.6.0", "", { "dependencies": { "yaml": "^2.9.0" } }, "sha512-a4sfn6L2sIShhtzJqmjGrARvxAW/3F2BJDdyRVvNF9VhAsZSh5hSyI3a9TNvmzBxXmq66nY5LNT5bQcBxYAZZg=="], + "optionator": ["optionator@0.9.4", "", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="], "ora": ["ora@8.2.0", "", { "dependencies": { "chalk": "^5.3.0", "cli-cursor": "^5.0.0", "cli-spinners": "^2.9.2", "is-interactive": "^2.0.0", "is-unicode-supported": "^2.0.0", "log-symbols": "^6.0.0", "stdin-discarder": "^0.2.2", "string-width": "^7.2.0", "strip-ansi": "^7.1.0" } }, "sha512-weP+BZ8MVNnlCm8c0Qdc1WSWq4Qn7I+9CJGm7Qali6g44e/PUzbjNqJX5NJ9ljlNMosfJvg1fKEGILklK9cwnw=="], @@ -2242,7 +2542,7 @@ "p-map": ["p-map@7.0.5", "", {}, "sha512-e8vJF4XdVkzqqSHguEMz41mQO1wKwxKm5ENrUJQUu9kLDCtn83cxbyHZcszr4QC5zEA7WffRRC4gsTecC7J9oA=="], - "p-retry": ["p-retry@4.6.2", "", { "dependencies": { "@types/retry": "0.12.0", "retry": "^0.13.1" } }, "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ=="], + "p-retry": ["p-retry@6.2.1", "", { "dependencies": { "@types/retry": "0.12.2", "is-network-error": "^1.0.0", "retry": "^0.13.1" } }, "sha512-hEt02O4hUct5wtwg4H4KcWgDdm+l1bOaEy/hWzd8xtXB9BqxTWBBhb+2ImAtH4Cv4rPjV76xN3Zumqk3k3AhhQ=="], "p-try": ["p-try@2.2.0", "", {}, "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ=="], @@ -2262,6 +2562,10 @@ "parse-png": ["parse-png@2.1.0", "", { "dependencies": { "pngjs": "^3.3.0" } }, "sha512-Nt/a5SfCLiTnQAjx3fHlqp8hRgTL3z7kTQZzvIMS9uCAepnCyjpdEc6M/sz69WqMBdaDBw9sF1F1UaHROYzGkQ=="], + "parse5": ["parse5@5.1.1", "", {}, "sha512-ugq4DFI0Ptb+WWjAdOK16+u/nHfiIrcE+sh8kZMaM0WllQKLI9rOUq6c2b7cwPkXdzfQESqvoqK6ug7U/Yyzug=="], + + "parse5-htmlparser2-tree-adapter": ["parse5-htmlparser2-tree-adapter@6.0.1", "", { "dependencies": { "parse5": "^6.0.1" } }, "sha512-qPuWvbLgvDGilKc5BoicRovlT4MtYT6JfJyBOMDsKoiT+GiuP5qyrPCnR9HcPECIJJmZh5jRndyNThnhhb/vlA=="], + "parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="], "partial-json": ["partial-json@0.1.7", "", {}, "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA=="], @@ -2282,10 +2586,20 @@ "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], + "pend": ["pend@1.2.0", "", {}, "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg=="], + + "pi-acp": ["pi-acp@0.0.23", "", { "dependencies": { "@agentclientprotocol/sdk": "^0.12.0", "zod": "^3.25.0" }, "bin": { "pi-acp": "dist/index.js" } }, "sha512-neOq/zgZoViyaDN/KsoAMJ1ToE63kqvzm5fdoQkDzQ2+UezO3vwdVY1WjyEfDHaLQiOKgQQjXVqFUZ9fn3LZvQ=="], + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], "picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], + "pino": ["pino@9.14.0", "", { "dependencies": { "@pinojs/redact": "^0.4.0", "atomic-sleep": "^1.0.0", "on-exit-leak-free": "^2.1.0", "pino-abstract-transport": "^2.0.0", "pino-std-serializers": "^7.0.0", "process-warning": "^5.0.0", "quick-format-unescaped": "^4.0.3", "real-require": "^0.2.0", "safe-stable-stringify": "^2.3.1", "sonic-boom": "^4.0.1", "thread-stream": "^3.0.0" }, "bin": { "pino": "bin.js" } }, "sha512-8OEwKp5juEvb/MjpIc4hjqfgCNysrS94RIOMXYvpYCdm/jglrKEiAYmiumbmGhCvs+IcInsphYDFwqrjr7398w=="], + + "pino-abstract-transport": ["pino-abstract-transport@2.0.0", "", { "dependencies": { "split2": "^4.0.0" } }, "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw=="], + + "pino-std-serializers": ["pino-std-serializers@7.1.0", "", {}, "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw=="], + "pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="], "pkg-types": ["pkg-types@2.3.1", "", { "dependencies": { "confbox": "^0.2.4", "exsolve": "^1.0.8", "pathe": "^2.0.3" } }, "sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg=="], @@ -2318,6 +2632,8 @@ "proc-log": ["proc-log@4.2.0", "", {}, "sha512-g8+OnU/L2v+wyiVK+D5fA34J7EH8jZ8DDlvwhRCMxmMj7UCBvxiO1mGeN+36JXIKF4zevU4kRBd8lVgG9vLelA=="], + "process-warning": ["process-warning@5.0.0", "", {}, "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA=="], + "progress": ["progress@2.0.3", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="], "promise": ["promise@8.3.0", "", { "dependencies": { "asap": "~2.0.6" } }, "sha512-rZPNPKTOYVNEEKFaq1HqTgOwZD+4/YHS5ukLzQCypkj+OkYx7iv0mA91lJlpPPZ8vMau3IIGj5Qlwrx+8iiSmg=="], @@ -2326,6 +2642,8 @@ "prop-types": ["prop-types@15.8.1", "", { "dependencies": { "loose-envify": "^1.4.0", "object-assign": "^4.1.1", "react-is": "^16.13.1" } }, "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg=="], + "proper-lockfile": ["proper-lockfile@4.1.2", "", { "dependencies": { "graceful-fs": "^4.2.4", "retry": "^0.12.0", "signal-exit": "^3.0.2" } }, "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA=="], + "protobufjs": ["protobufjs@7.6.5", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.5", "@protobufjs/eventemitter": "^1.1.1", "@protobufjs/fetch": "^1.1.1", "@protobufjs/float": "^1.0.2", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.1", "@types/node": ">=13.7.0", "long": "^5.3.2" } }, "sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw=="], "proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="], @@ -2338,6 +2656,8 @@ "punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="], + "pure-rand": ["pure-rand@8.4.2", "", {}, "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng=="], + "qs": ["qs@6.15.3", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A=="], "quansync": ["quansync@0.2.11", "", {}, "sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA=="], @@ -2348,6 +2668,8 @@ "queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="], + "quick-format-unescaped": ["quick-format-unescaped@4.0.4", "", {}, "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg=="], + "quickjs-emscripten": ["quickjs-emscripten@0.32.0", "", { "dependencies": { "@jitl/quickjs-wasmfile-debug-asyncify": "0.32.0", "@jitl/quickjs-wasmfile-debug-sync": "0.32.0", "@jitl/quickjs-wasmfile-release-asyncify": "0.32.0", "@jitl/quickjs-wasmfile-release-sync": "0.32.0", "quickjs-emscripten-core": "0.32.0" } }, "sha512-So0Sqw869y/S2oE3Nuc0uT3Dhqgvsj8FSrwBdsuTosVsG8ME5/OcudU1GxsrIFdFABgy17GHnTVO9TYV/bLQcA=="], "quickjs-emscripten-core": ["quickjs-emscripten-core@0.32.0", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-QFnPfjFey8EqknSrSxe1hZrf1/8z7/6s1QzGOmKo6++02r7QRRX7ZoyNaZh7JuVjWsVW87KnQrbZqnHkOAzUyg=="], @@ -2422,6 +2744,8 @@ "readdirp": ["readdirp@5.0.0", "", {}, "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ=="], + "real-require": ["real-require@0.2.0", "", {}, "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg=="], + "recast": ["recast@0.23.12", "", { "dependencies": { "ast-types": "^0.16.1", "esprima": "~4.0.0", "source-map": "~0.6.1", "tiny-invariant": "^1.3.3", "tslib": "^2.0.1" } }, "sha512-dEWRjcINDu/F4l2dYx57ugBtD7HV9KXESyxhzw/MqWLeglJrsjJKqACPyUPg+6AF8mIgm+Zi0dZ3ACoIg+QtpA=="], "redent": ["redent@3.0.0", "", { "dependencies": { "indent-string": "^4.0.0", "strip-indent": "^3.0.0" } }, "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg=="], @@ -2458,6 +2782,8 @@ "reusify": ["reusify@1.1.0", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="], + "rivetkit": ["rivetkit@0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "", { "dependencies": { "@hono/zod-openapi": "^1.1.5", "@rivetkit/bare-ts": "^0.6.2", "@rivetkit/engine-cli": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "@rivetkit/engine-envoy-protocol": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "@rivetkit/on-change": "6.0.1", "@rivetkit/rivetkit-napi": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "@rivetkit/rivetkit-wasm": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "@rivetkit/traces": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "@rivetkit/virtual-websocket": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "@rivetkit/workflow-engine": "0.0.0-stack-feat-rivetkit-forward-inspector-tabs-to-native-plugin-actors-qkwmksyy.d2859b0", "cbor-x": "^1.6.0", "drizzle-orm": "^0.44.2", "hono": "^4.7.0", "invariant": "^2.2.4", "p-retry": "^6.2.1", "pino": "^9.5.0", "uuid": "^12.0.0", "vbare": "^0.0.4", "zod": "^4.1.0" }, "peerDependencies": { "drizzle-kit": "^0.31.2", "eventsource": "^4.0.0", "ws": "^8.0.0" }, "optionalPeers": ["drizzle-kit", "eventsource", "ws"] }, "sha512-3kXHTXMv6u/P29xul+8YnqCmkhyj3TYJxl1f40yyjWqbrxhAPR7qoW+mDY3NTIMX6xpXuiqnR9gp9pSPiM4s0A=="], + "rolldown": ["rolldown@1.1.4", "", { "dependencies": { "@oxc-project/types": "=0.138.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.1.4", "@rolldown/binding-darwin-arm64": "1.1.4", "@rolldown/binding-darwin-x64": "1.1.4", "@rolldown/binding-freebsd-x64": "1.1.4", "@rolldown/binding-linux-arm-gnueabihf": "1.1.4", "@rolldown/binding-linux-arm64-gnu": "1.1.4", "@rolldown/binding-linux-arm64-musl": "1.1.4", "@rolldown/binding-linux-ppc64-gnu": "1.1.4", "@rolldown/binding-linux-s390x-gnu": "1.1.4", "@rolldown/binding-linux-x64-gnu": "1.1.4", "@rolldown/binding-linux-x64-musl": "1.1.4", "@rolldown/binding-openharmony-arm64": "1.1.4", "@rolldown/binding-wasm32-wasi": "1.1.4", "@rolldown/binding-win32-arm64-msvc": "1.1.4", "@rolldown/binding-win32-x64-msvc": "1.1.4" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-IjZYiLxZwpnhwhdBH2ugdTGVSdhCQUmLxLoqyjiL0JxYjyRst+5a0P3xfrTxJ5F638j4Mvvw5FAX5XE6eHpXbA=="], "rou3": ["rou3@0.7.12", "", {}, "sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg=="], @@ -2472,6 +2798,8 @@ "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], + "safe-stable-stringify": ["safe-stable-stringify@2.5.0", "", {}, "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA=="], + "safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="], "sax": ["sax@1.6.0", "", {}, "sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA=="], @@ -2550,6 +2878,8 @@ "solid-js": ["solid-js@1.9.14", "", { "dependencies": { "csstype": "^3.1.0", "seroval": "~1.5.4", "seroval-plugins": "~1.5.4" } }, "sha512-sAEXC0Kk0S1EDg+8ysEWJDbYhA3RRoEjwuySUGlKIemeo0I5YZfOyumNjNs9Sv3y2nmhD+0rW66ag2HsMuQiGQ=="], + "sonic-boom": ["sonic-boom@4.2.1", "", { "dependencies": { "atomic-sleep": "^1.0.0" } }, "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q=="], + "sonner": ["sonner@2.0.7", "", { "peerDependencies": { "react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc", "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc" } }, "sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w=="], "source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], @@ -2560,6 +2890,8 @@ "split-on-first": ["split-on-first@1.1.0", "", {}, "sha512-43ZssAJaMusuKWL8sKUBQXHWOpq8d6CfN/u1p4gUzfJkM05C8rxTmYrkIPTXapZpORA6LkkzcUulJ8FqA7Uudw=="], + "split2": ["split2@4.2.0", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="], + "sprintf-js": ["sprintf-js@1.1.3", "", {}, "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="], "sql.js": ["sql.js@1.14.1", "", {}, "sha512-gcj8zBWU5cFsi9WUP+4bFNXAyF1iRpA3LLyS/DP5xlrNzGmPIizUeBggKa8DbDwdqaKwUcTEnChtd2grWo/x/A=="], @@ -2632,6 +2964,12 @@ "terser": ["terser@5.49.0", "", { "dependencies": { "@jridgewell/source-map": "^0.3.3", "acorn": "^8.15.0", "commander": "^2.20.0", "source-map-support": "~0.5.20" }, "bin": { "terser": "bin/terser" } }, "sha512-SNiDnXyHSrxVcIOtVbULzcTmniUiwcV7Nwdyj1twVubeTmbjoa8p69KKDpfkdoOavuM4/GRm1+ykI8qqnavHoA=="], + "thenify": ["thenify@3.3.1", "", { "dependencies": { "any-promise": "^1.0.0" } }, "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw=="], + + "thenify-all": ["thenify-all@1.6.0", "", { "dependencies": { "thenify": ">= 3.1.0 < 4" } }, "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA=="], + + "thread-stream": ["thread-stream@3.2.0", "", { "dependencies": { "real-require": "^0.2.0" } }, "sha512-zLBvqpwr4Esa0kRjcrzGU6zL25lePWaCLMx0RQFrmteozIfeNdaMLpG5U7PeHzvlFkAWaRKA9/KVW4F60iB+qw=="], + "three": ["three@0.165.0", "", {}, "sha512-cc96IlVYGydeceu0e5xq70H8/yoVT/tXBxV/W8A/U6uOq7DXc4/s1Mkmnu6SqoYGhSRWWYFOhVwvq6V0VtbplA=="], "throat": ["throat@5.0.0", "", {}, "sha512-fcwX4mndzpLQKBS1DVYhGAcYaYt7vsHNIvQV+WXMvnow5cgjPphq5CaayLaGsjRdSCKZFNGt7/GYAuXaNOiYCA=="], @@ -2656,6 +2994,8 @@ "token-types": ["token-types@6.1.2", "", { "dependencies": { "@borewit/text-codec": "^0.2.1", "@tokenizer/token": "^0.3.0", "ieee754": "^1.2.1" } }, "sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww=="], + "toml": ["toml@4.3.0", "", {}, "sha512-lVb8X9BsPVuH0M4BKeS91tXAmJvCjQ5UIyAbQFaxkKGyUFK2RPkhwaFSQH8vbpl1d23eu/IBH+dwVMHWaq9A5A=="], + "toqr": ["toqr@0.1.1", "", {}, "sha512-FWAPzCIHZHnrE/5/w9MPk0kK25hSQSH2IKhYh9PyjS3SG/+IEMvlwIHbhz+oF7xl54I+ueZlVnMjyzdSwLmAwA=="], "totalist": ["totalist@3.0.1", "", {}, "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ=="], @@ -2728,6 +3068,8 @@ "uri-js": ["uri-js@4.4.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="], + "url-template": ["url-template@2.0.8", "", {}, "sha512-XdVKMF4SJ0nP/O7XIPB0JwAEuT9lDIYnNsK8yGVe43y0AWoKeJNdv3ZNWh7ksJ6KqQFjOO6ox/VEitLnaVNufw=="], + "use-callback-ref": ["use-callback-ref@1.3.3", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg=="], "use-latest-callback": ["use-latest-callback@0.2.6", "", { "peerDependencies": { "react": ">=16.8" } }, "sha512-FvRG9i1HSo0wagmX63Vrm8SnlUU3LMM3WyZkQ76RnslpBrX694AdG4A0zQBx2B3ZifFA0yv/BaEHGBnEax5rZg=="], @@ -2740,7 +3082,7 @@ "utils-merge": ["utils-merge@1.0.1", "", {}, "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA=="], - "uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="], + "uuid": ["uuid@14.0.1", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-6ZxzVpzDXDa3bJWaHilVayA+BH/1zmxCJoVgvmqJnid/gPoKHxUrS/aC/T6LGQtNHT+XHG9fXPJB4d+IrU30Ew=="], "valibot": ["valibot@1.4.2", "", { "peerDependencies": { "typescript": ">=5" }, "optionalPeers": ["typescript"] }, "sha512-gjdCvJ6d3RyHAneqxMYMW9QMCwYMb3jpOO0IyHZV1bnRHFBHrX3VkIILt5XYR0WhwHiH7Mty8ovuPZ/O3gamrg=="], @@ -2750,6 +3092,8 @@ "vaul": ["vaul@1.1.2", "", { "dependencies": { "@radix-ui/react-dialog": "^1.1.1" }, "peerDependencies": { "react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc" } }, "sha512-ZFkClGpWyI2WUQjdLJ/BaGuV6AVQiJ3uELGk3OYtP+B6yCO7Cmn9vPFXVJkRaGkOJu3m8bQMgtyzNHixULceQA=="], + "vbare": ["vbare@0.0.4", "", {}, "sha512-QsxSVw76NqYUWYPVcQmOnQPX8buIVjgn+yqldTHlWISulBTB9TJ9rnzZceDu+GZmycOtzsmuPbPN1YNxvK12fg=="], + "vite": ["@voidzero-dev/vite-plus-core@0.2.2", "", { "dependencies": { "@oxc-project/runtime": "=0.138.0", "@oxc-project/types": "=0.138.0", "lightningcss": "^1.32.0", "postcss": "^8.5.6" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@arethetypeswrong/core": "^0.18.1", "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.3.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "publint": "^0.3.8", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "typescript": "^5.0.0 || ^6.0.0", "unplugin-unused": "^0.5.0", "unrun": "*", "yaml": "^2.4.2" }, "optionalPeers": ["@arethetypeswrong/core", "@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "publint", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "typescript", "unplugin-unused", "unrun", "yaml"] }, "sha512-yAbKexF3npOGjg1N5EtXxun+7vdM/0x6QE5jucO/dv0LFhCAIzSN3UvLVCeamJt/Bz3jt7DLqQHEgXXrjy8drA=="], "vite-plus": ["vite-plus@0.2.2", "", { "dependencies": { "@oxc-project/types": "=0.138.0", "@oxlint/plugins": "=1.68.0", "@vitest/browser": "4.1.9", "@vitest/browser-preview": "4.1.9", "@vitest/expect": "4.1.9", "@vitest/mocker": "4.1.9", "@vitest/pretty-format": "4.1.9", "@vitest/runner": "4.1.9", "@vitest/snapshot": "4.1.9", "@vitest/spy": "4.1.9", "@vitest/utils": "4.1.9", "@voidzero-dev/vite-plus-core": "0.2.2", "oxfmt": "=0.57.0", "oxlint": "=1.72.0", "oxlint-tsgolint": "=0.24.0", "vitest": "4.1.9" }, "optionalDependencies": { "@voidzero-dev/vite-plus-darwin-arm64": "0.2.2", "@voidzero-dev/vite-plus-darwin-x64": "0.2.2", "@voidzero-dev/vite-plus-linux-arm64-gnu": "0.2.2", "@voidzero-dev/vite-plus-linux-arm64-musl": "0.2.2", "@voidzero-dev/vite-plus-linux-x64-gnu": "0.2.2", "@voidzero-dev/vite-plus-linux-x64-musl": "0.2.2", "@voidzero-dev/vite-plus-win32-arm64-msvc": "0.2.2", "@voidzero-dev/vite-plus-win32-x64-msvc": "0.2.2" }, "peerDependencies": { "@vitest/browser-playwright": "4.1.9", "@vitest/browser-webdriverio": "4.1.9" }, "optionalPeers": ["@vitest/browser-playwright", "@vitest/browser-webdriverio"], "bin": { "vp": "bin/vp", "vpr": "bin/vpr", "oxfmt": "bin/oxfmt", "oxlint": "bin/oxlint" } }, "sha512-bXO3O0F2/uxtvX9Ck0o67stTErH/Zh0GEcCMd9pAh22tTHABCNTDPrRMWVo733e7Ux3h0Y7HanJ7neOV/nid4g=="], @@ -2818,6 +3162,8 @@ "yargs-parser": ["yargs-parser@22.0.0", "", {}, "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw=="], + "yauzl": ["yauzl@2.10.0", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="], + "yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="], "yocto-spinner": ["yocto-spinner@1.2.2", "", { "dependencies": { "yoctocolors": "^2.1.1" } }, "sha512-DODGl1wJjA/s5pnJFKau9lIYHT81lnhob1i3e1TjxZRxEhWRKl74nTbWE6H5KlkViQQTo/Z29YFdxzTZAMY3ng=="], @@ -2832,6 +3178,10 @@ "zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="], + "@anthropic-ai/claude-agent-sdk/@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.74.0", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-srbJV7JKsc5cQ6eVuFzjZO7UR3xEPJqPamHFIe29bs38Ij2IripoAhC0S5NslNbaFUYqBKypmmpzMTpqfHEUDw=="], + + "@aws-sdk/client-s3/@smithy/node-http-handler": ["@smithy/node-http-handler@4.9.7", "", { "dependencies": { "@smithy/core": "^3.29.5", "@smithy/types": "^4.16.1", "tslib": "^2.6.2" } }, "sha512-wCU8HCLjAtAVqxxe0j2xff9LcEPw3yjBbg5IdQDIYFnxnPxbxcSLc7rgex7kqm9L/WYOnJEgaWQlfDkZleozMA=="], + "@aws-sdk/credential-provider-http/@smithy/node-http-handler": ["@smithy/node-http-handler@4.9.7", "", { "dependencies": { "@smithy/core": "^3.29.5", "@smithy/types": "^4.16.1", "tslib": "^2.6.2" } }, "sha512-wCU8HCLjAtAVqxxe0j2xff9LcEPw3yjBbg5IdQDIYFnxnPxbxcSLc7rgex7kqm9L/WYOnJEgaWQlfDkZleozMA=="], "@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1088.0", "", { "dependencies": { "@aws-sdk/core": "^3.975.3", "@aws-sdk/nested-clients": "^3.997.33", "@aws-sdk/types": "^3.974.2", "@smithy/core": "^3.29.4", "@smithy/types": "^4.16.1", "tslib": "^2.6.2" } }, "sha512-4ObatWt2qpJg5FBk4LOOKrTQYzaqeewAtdO3r9ZO8lH9YqLtpTzLyIdy0mJ+nVdfYOnqISkKNfmzP22bNDhwyw=="], @@ -2896,12 +3246,28 @@ "@expo/xcpretty/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], + "@google/genai/p-retry": ["p-retry@4.6.2", "", { "dependencies": { "@types/retry": "0.12.0", "retry": "^0.13.1" } }, "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ=="], + "@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA=="], "@jest/types/@types/node": ["@types/node@26.1.1", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="], "@jest/types/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], + "@mariozechner/jiti/std-env": ["std-env@3.10.0", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="], + + "@mariozechner/pi-ai/@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.73.0", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-URURVzhxXGJDGUGFunIOtBlSl7KWvZiAAKY/ttTkZAkXT9bTPqdk2eK0b8qqSxXpikh3QKPnPYpiyX98zf5ebw=="], + + "@mariozechner/pi-ai/@mistralai/mistralai": ["@mistralai/mistralai@1.14.1", "", { "dependencies": { "ws": "^8.18.0", "zod": "^3.25.0 || ^4.0.0", "zod-to-json-schema": "^3.24.1" } }, "sha512-IiLmmZFCCTReQgPAT33r7KQ1nYo5JPdvGkrkZqA8qQ2qB1GHgs5LoP5K2ICyrjnpw2n8oSxMM/VP+liiKcGNlQ=="], + + "@mariozechner/pi-ai/@sinclair/typebox": ["@sinclair/typebox@0.34.52", "", {}, "sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw=="], + + "@mariozechner/pi-coding-agent/hosted-git-info": ["hosted-git-info@9.0.3", "", { "dependencies": { "lru-cache": "^11.1.0" } }, "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg=="], + + "@mariozechner/pi-coding-agent/marked": ["marked@15.0.12", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA=="], + + "@mariozechner/pi-tui/marked": ["marked@15.0.12", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA=="], + "@modelcontextprotocol/sdk/@hono/node-server": ["@hono/node-server@1.19.14", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="], "@opentui/core/diff": ["diff@9.0.0", "", {}, "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw=="], @@ -2916,6 +3282,10 @@ "@react-router/dev/react-refresh": ["react-refresh@0.18.0", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="], + "@rivetkit/framework-base/@tanstack/store": ["@tanstack/store@0.7.7", "", {}, "sha512-xa6pTan1bcaqYDS9BDpSiS63qa6EoDkPN9RsRaxHuDdVDNntzq3xNwR5YKTU/V3SkSyC9T4YVOPh2zRQN0nhIQ=="], + + "@rivetkit/react/@tanstack/react-store": ["@tanstack/react-store@0.7.7", "", { "dependencies": { "@tanstack/store": "0.7.7", "use-sync-external-store": "^1.5.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-qqT0ufegFRDGSof9D/VqaZgjNgp4tRPHZIJq2+QIHkMUtHjaJ0lYrrXjeIUJvjnTbgPfSD1XgOMEt0lmANn6Zg=="], + "@tailwindcss/node/lightningcss": ["lightningcss@1.32.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="], "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.2", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" }, "bundled": true }, "sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA=="], @@ -2940,6 +3310,10 @@ "@testing-library/dom/pretty-format": ["pretty-format@27.5.1", "", { "dependencies": { "ansi-regex": "^5.0.1", "ansi-styles": "^5.0.0", "react-is": "^17.0.1" } }, "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ=="], + "@types/ws/@types/node": ["@types/node@26.1.1", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="], + + "@types/yauzl/@types/node": ["@types/node@26.1.1", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="], + "@typescript-eslint/visitor-keys/eslint-visitor-keys": ["eslint-visitor-keys@5.0.1", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="], "@voidzero-dev/vite-plus-core/lightningcss": ["lightningcss@1.32.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="], @@ -2958,10 +3332,16 @@ "bun-types/@types/node": ["@types/node@26.1.1", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="], + "cbor-extract/node-gyp-build-optional-packages": ["node-gyp-build-optional-packages@5.1.1", "", { "dependencies": { "detect-libc": "^2.0.1" }, "bin": { "node-gyp-build-optional-packages": "bin.js", "node-gyp-build-optional-packages-test": "build-test.js", "node-gyp-build-optional-packages-optional": "optional.js" } }, "sha512-+P72GAjVAbTxjjwUmwjVrqrdZROD4nf8KgpBoDxqXXTiYZZt/ud60dE5yvCSr9lRO8e8yv6kgJIC0K0PfZFVQw=="], + "chrome-launcher/@types/node": ["@types/node@26.1.1", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="], "chromium-edge-launcher/@types/node": ["@types/node@26.1.1", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="], + "cli-highlight/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], + + "cli-highlight/yargs": ["yargs@16.2.2", "", { "dependencies": { "cliui": "^7.0.2", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.0", "y18n": "^5.0.5", "yargs-parser": "^20.2.2" } }, "sha512-Nt9ZJjXTv5R8MHbqby/wXQ6Gi0Bb3TcYZkR1bzuL4yB2OxWPkXknz513gEF0GoA6tn00UpbPvERW8rzCuWCA6w=="], + "cliui/wrap-ansi": ["wrap-ansi@9.0.2", "", { "dependencies": { "ansi-styles": "^6.2.1", "string-width": "^7.0.0", "strip-ansi": "^7.1.0" } }, "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww=="], "compression/debug": ["debug@2.6.9", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="], @@ -3000,10 +3380,22 @@ "express/send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="], + "extract-zip/get-stream": ["get-stream@5.2.0", "", { "dependencies": { "pump": "^3.0.0" } }, "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA=="], + "fbjs/promise": ["promise@7.3.1", "", { "dependencies": { "asap": "~2.0.3" } }, "sha512-nolQXZ/4L+bP/UGlkfaIujX9BKxGwmQ9OT4mOt5yvy8iK1h3wqTEJCijzGANTCCl9nWjY41juyAn2K3Q1hLLTg=="], "gaxios/node-fetch": ["node-fetch@3.3.2", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="], + "googleapis/google-auth-library": ["google-auth-library@9.15.1", "", { "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^6.1.1", "gcp-metadata": "^6.1.0", "gtoken": "^7.0.0", "jws": "^4.0.0" } }, "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng=="], + + "googleapis-common/gaxios": ["gaxios@6.7.1", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "is-stream": "^2.0.0", "node-fetch": "^2.6.9", "uuid": "^9.0.1" } }, "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ=="], + + "googleapis-common/google-auth-library": ["google-auth-library@9.15.1", "", { "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^6.1.1", "gcp-metadata": "^6.1.0", "gtoken": "^7.0.0", "jws": "^4.0.0" } }, "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng=="], + + "googleapis-common/uuid": ["uuid@9.0.1", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA=="], + + "gtoken/gaxios": ["gaxios@6.7.1", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "is-stream": "^2.0.0", "node-fetch": "^2.6.9", "uuid": "^9.0.1" } }, "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ=="], + "hoist-non-react-statics/react-is": ["react-is@16.13.1", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="], "hosted-git-info/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], @@ -3024,6 +3416,8 @@ "jest-worker/supports-color": ["supports-color@8.1.1", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="], + "just-bash/ini": ["ini@6.0.0", "", {}, "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ=="], + "lighthouse-logger/debug": ["debug@2.6.9", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="], "log-symbols/is-unicode-supported": ["is-unicode-supported@1.3.0", "", {}, "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ=="], @@ -3064,8 +3458,14 @@ "parse-png/pngjs": ["pngjs@3.4.0", "", {}, "sha512-NCrCHhWmnQklfH4MtJMRjZ2a8c80qXeMlQMv2uVp9ISJMTt562SbGd6n2oq0PaPgKm7Z6pL9E2UlLIhC+SHL3w=="], + "parse5-htmlparser2-tree-adapter/parse5": ["parse5@6.0.1", "", {}, "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw=="], + "path-scurry/lru-cache": ["lru-cache@11.5.2", "", {}, "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g=="], + "pi-acp/@agentclientprotocol/sdk": ["@agentclientprotocol/sdk@0.12.0", "", { "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" } }, "sha512-V8uH/KK1t7utqyJmTA7y7DzKu6+jKFIXM+ZVouz8E55j8Ej2RV42rEvPKn3/PpBJlliI5crcGk1qQhZ7VwaepA=="], + + "pi-acp/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], + "pkg-up/find-up": ["find-up@3.0.0", "", { "dependencies": { "locate-path": "^3.0.0" } }, "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg=="], "plist/@xmldom/xmldom": ["@xmldom/xmldom@0.9.10", "", {}, "sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw=="], @@ -3080,10 +3480,16 @@ "prop-types/react-is": ["react-is@16.13.1", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="], + "proper-lockfile/retry": ["retry@0.12.0", "", {}, "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow=="], + + "proper-lockfile/signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="], + "protobufjs/@types/node": ["@types/node@26.1.1", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="], "rc/ini": ["ini@1.3.8", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="], + "react-d3-tree/uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="], + "react-devtools-core/ws": ["ws@7.5.13", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA=="], "react-native/commander": ["commander@12.1.0", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="], @@ -3098,6 +3504,8 @@ "restore-cursor/onetime": ["onetime@7.0.0", "", { "dependencies": { "mimic-function": "^5.0.0" } }, "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ=="], + "rivetkit/uuid": ["uuid@12.0.1", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-9obBF8sMIHJWNQaO6IGOG8giGa/jUpKX34bz6o4whVs8M0WAvhID2tNxYp6A2XEBJPuZSX8wsS/6TEKfIDc+nw=="], + "router/path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="], "seek-bzip/commander": ["commander@6.2.1", "", {}, "sha512-U7VdrJFnJgo4xjrHpTzu0yrHPGImdsmD95ZlgYSEajAn2JKzDhDTPG9kBTefmObL2w/ngeZnilk+OV9CG3d7UA=="], @@ -3246,18 +3654,24 @@ "@expo/xcpretty/chalk/supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], + "@google/genai/p-retry/@types/retry": ["@types/retry@0.12.0", "", {}, "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA=="], + "@jest/types/@types/node/undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="], "@jest/types/chalk/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], "@jest/types/chalk/supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], + "@mariozechner/pi-coding-agent/hosted-git-info/lru-cache": ["lru-cache@11.5.2", "", {}, "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g=="], + "@react-native/codegen/yargs/cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="], "@react-native/codegen/yargs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], "@react-native/codegen/yargs/yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="], + "@rivetkit/react/@tanstack/react-store/@tanstack/store": ["@tanstack/store@0.7.7", "", {}, "sha512-xa6pTan1bcaqYDS9BDpSiS63qa6EoDkPN9RsRaxHuDdVDNntzq3xNwR5YKTU/V3SkSyC9T4YVOPh2zRQN0nhIQ=="], + "@tailwindcss/node/lightningcss/lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.32.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ=="], "@tailwindcss/node/lightningcss/lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.32.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w=="], @@ -3280,6 +3694,10 @@ "@testing-library/dom/pretty-format/react-is": ["react-is@17.0.2", "", {}, "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="], + "@types/ws/@types/node/undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="], + + "@types/yauzl/@types/node/undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="], + "@voidzero-dev/vite-plus-core/lightningcss/lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.32.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ=="], "@voidzero-dev/vite-plus-core/lightningcss/lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.32.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w=="], @@ -3308,6 +3726,16 @@ "chromium-edge-launcher/@types/node/undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="], + "cli-highlight/chalk/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], + + "cli-highlight/chalk/supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], + + "cli-highlight/yargs/cliui": ["cliui@7.0.4", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", "wrap-ansi": "^7.0.0" } }, "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ=="], + + "cli-highlight/yargs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + + "cli-highlight/yargs/yargs-parser": ["yargs-parser@20.2.9", "", {}, "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w=="], + "cliui/wrap-ansi/ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="], "compression/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], @@ -3330,6 +3758,18 @@ "gaxios/node-fetch/data-uri-to-buffer": ["data-uri-to-buffer@4.0.1", "", {}, "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A=="], + "googleapis-common/gaxios/is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="], + + "googleapis-common/google-auth-library/gcp-metadata": ["gcp-metadata@6.1.1", "", { "dependencies": { "gaxios": "^6.1.1", "google-logging-utils": "^0.0.2", "json-bigint": "^1.0.0" } }, "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A=="], + + "googleapis/google-auth-library/gaxios": ["gaxios@6.7.1", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "is-stream": "^2.0.0", "node-fetch": "^2.6.9", "uuid": "^9.0.1" } }, "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ=="], + + "googleapis/google-auth-library/gcp-metadata": ["gcp-metadata@6.1.1", "", { "dependencies": { "gaxios": "^6.1.1", "google-logging-utils": "^0.0.2", "json-bigint": "^1.0.0" } }, "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A=="], + + "gtoken/gaxios/is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="], + + "gtoken/gaxios/uuid": ["uuid@9.0.1", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA=="], + "jest-util/@types/node/undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="], "jest-util/chalk/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], @@ -3576,6 +4016,20 @@ "@react-native/codegen/yargs/string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + "cli-highlight/yargs/cliui/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "cli-highlight/yargs/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], + + "cli-highlight/yargs/string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "googleapis-common/google-auth-library/gcp-metadata/google-logging-utils": ["google-logging-utils@0.0.2", "", {}, "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ=="], + + "googleapis/google-auth-library/gaxios/is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="], + + "googleapis/google-auth-library/gaxios/uuid": ["uuid@9.0.1", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA=="], + + "googleapis/google-auth-library/gcp-metadata/google-logging-utils": ["google-logging-utils@0.0.2", "", {}, "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ=="], + "metro/yargs/cliui/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], "metro/yargs/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], diff --git a/package.json b/package.json index d0273f0..95e8ba5 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,10 @@ "dev:tui": "vp run --filter tui dev", "dev:server": "vp run --filter @code/backend dev", "dev:setup": "vp run --filter @code/backend dev:setup", + "dev:daemon": "vp run --filter daemon dev", + "build:daemon": "vp run --filter daemon build", + "docs:update": "bun run scripts/update-docs.ts", + "subtree": "bun run scripts/subtree.ts", "fix": "ultracite fix" }, "dependencies": { @@ -49,6 +53,7 @@ }, "devDependencies": { "@code/config": "workspace:*", + "@types/bun": "latest", "@types/node": "^22.13.14", "oxfmt": "latest", "oxlint": "latest", diff --git a/packages/agents/package.json b/packages/agents/package.json index add5af0..f3348f5 100644 --- a/packages/agents/package.json +++ b/packages/agents/package.json @@ -7,7 +7,8 @@ "build": "flue build", "check-types": "tsc --noEmit", "dev": "flue dev", - "run": "flue run" + "run": "flue run", + "run:zopu": "flue run zopu" }, "dependencies": { "@flue/runtime": "latest" diff --git a/packages/agents/src/agents/hello-world.ts b/packages/agents/src/agents/hello-world.ts deleted file mode 100644 index e782e9e..0000000 --- a/packages/agents/src/agents/hello-world.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { defineAgent } from '@flue/runtime'; - -export default defineAgent(() => ({ - model: 'anthropic/claude-sonnet-4-6', - instructions: 'Give a concise, helpful hello-world response for this project.', -})); diff --git a/packages/agents/src/agents/zopu.ts b/packages/agents/src/agents/zopu.ts new file mode 100644 index 0000000..105e6a0 --- /dev/null +++ b/packages/agents/src/agents/zopu.ts @@ -0,0 +1,11 @@ +import { defineAgent } from "@flue/runtime"; + +export default defineAgent(() => ({ + description: "Zopu is the primary coding agent users collaborate with.", + model: "anthropic/claude-sonnet-4-6", + instructions: `You are Zopu, the primary agent users collaborate with. + +Work as a pragmatic senior coding agent. Understand the user's goal, inspect the current workspace, make the necessary changes, and verify that the result works. Prefer direct, maintainable solutions over unnecessary abstraction. + +Your workspace is an isolated agentOS VM dedicated to this agent. Treat its filesystem, processes, and session state as the complete working environment. Use the capabilities available in the workspace, and do not assume access to resources outside it.`, +})); diff --git a/packages/backend/convex/_generated/api.d.ts b/packages/backend/convex/_generated/api.d.ts index 1c714e6..fc4eb3e 100644 --- a/packages/backend/convex/_generated/api.d.ts +++ b/packages/backend/convex/_generated/api.d.ts @@ -9,6 +9,9 @@ */ import type * as auth from "../auth.js"; +import type * as daemonCommands from "../daemonCommands.js"; +import type * as daemonRuntime from "../daemonRuntime.js"; +import type * as daemons from "../daemons.js"; import type * as healthCheck from "../healthCheck.js"; import type * as http from "../http.js"; import type * as privateData from "../privateData.js"; @@ -22,6 +25,9 @@ import type { declare const fullApi: ApiFromModules<{ auth: typeof auth; + daemonCommands: typeof daemonCommands; + daemonRuntime: typeof daemonRuntime; + daemons: typeof daemons; healthCheck: typeof healthCheck; http: typeof http; privateData: typeof privateData; diff --git a/packages/backend/convex/daemonCommands.ts b/packages/backend/convex/daemonCommands.ts new file mode 100644 index 0000000..e1d0745 --- /dev/null +++ b/packages/backend/convex/daemonCommands.ts @@ -0,0 +1,199 @@ +import { v } from "convex/values"; + +import { mutation, query } from "./_generated/server"; + +const commandStatus = v.union( + v.literal("queued"), + v.literal("claimed"), + v.literal("running"), + v.literal("succeeded"), + v.literal("failed"), + v.literal("cancelled") +); + +export const enqueue = mutation({ + args: { + daemonId: v.string(), + method: v.string(), + args: v.any(), + actorKey: v.array(v.string()), + }, + handler: async (ctx, args) => { + const timestamp = Date.now(); + return await ctx.db.insert("daemonCommands", { + ...args, + status: "queued", + attempts: 0, + createdAt: timestamp, + updatedAt: timestamp, + }); + }, +}); + +export const list = query({ + args: { + daemonId: v.string(), + status: v.optional(commandStatus), + }, + handler: async (ctx, args) => { + if (args.status) { + return await ctx.db + .query("daemonCommands") + .withIndex("by_daemonId_and_status", (q) => + q.eq("daemonId", args.daemonId).eq("status", args.status!) + ) + .order("desc") + .take(100); + } + return await ctx.db + .query("daemonCommands") + .filter((q) => q.eq(q.field("daemonId"), args.daemonId)) + .order("desc") + .take(100); + }, +}); + +export const available = query({ + args: { daemonId: v.string() }, + handler: async (ctx, args) => { + const queued = await ctx.db + .query("daemonCommands") + .withIndex("by_daemonId_and_status", (q) => + q.eq("daemonId", args.daemonId).eq("status", "queued") + ) + .order("asc") + .take(25); + const expiredClaims = await ctx.db + .query("daemonCommands") + .withIndex("by_daemonId_and_status", (q) => + q.eq("daemonId", args.daemonId).eq("status", "claimed") + ) + .filter((q) => q.lt(q.field("leaseExpiresAt"), Date.now())) + .order("asc") + .take(25); + return [...expiredClaims, ...queued].slice(0, 25); + }, +}); + +export const claim = mutation({ + args: { + commandId: v.id("daemonCommands"), + daemonId: v.string(), + sessionId: v.string(), + leaseDurationMs: v.number(), + }, + handler: async (ctx, args) => { + const command = await ctx.db.get("daemonCommands", args.commandId); + if (!command || command.daemonId !== args.daemonId) { + return null; + } + const timestamp = Date.now(); + const canClaim = + command.status === "queued" || + (command.status === "claimed" && + command.leaseExpiresAt !== undefined && + command.leaseExpiresAt <= timestamp); + if (!canClaim) { + return null; + } + await ctx.db.patch("daemonCommands", command._id, { + status: "claimed", + claimedBySessionId: args.sessionId, + leaseExpiresAt: timestamp + args.leaseDurationMs, + attempts: command.attempts + 1, + updatedAt: timestamp, + }); + return { ...command, status: "claimed" as const }; + }, +}); + +export const start = mutation({ + args: { + commandId: v.id("daemonCommands"), + sessionId: v.string(), + }, + handler: async (ctx, args) => { + const command = await ctx.db.get("daemonCommands", args.commandId); + if ( + !command || + command.status !== "claimed" || + command.claimedBySessionId !== args.sessionId + ) { + return false; + } + const timestamp = Date.now(); + await ctx.db.patch("daemonCommands", command._id, { + status: "running", + startedAt: timestamp, + updatedAt: timestamp, + }); + return true; + }, +}); + +export const succeed = mutation({ + args: { + commandId: v.id("daemonCommands"), + sessionId: v.string(), + result: v.any(), + }, + handler: async (ctx, args) => { + const command = await ctx.db.get("daemonCommands", args.commandId); + if (!command || command.claimedBySessionId !== args.sessionId) { + return false; + } + const timestamp = Date.now(); + await ctx.db.patch("daemonCommands", command._id, { + status: "succeeded", + result: args.result, + completedAt: timestamp, + updatedAt: timestamp, + leaseExpiresAt: undefined, + }); + return true; + }, +}); + +export const fail = mutation({ + args: { + commandId: v.id("daemonCommands"), + sessionId: v.string(), + error: v.string(), + }, + handler: async (ctx, args) => { + const command = await ctx.db.get("daemonCommands", args.commandId); + if (!command || command.claimedBySessionId !== args.sessionId) { + return false; + } + const timestamp = Date.now(); + await ctx.db.patch("daemonCommands", command._id, { + status: "failed", + error: args.error, + completedAt: timestamp, + updatedAt: timestamp, + leaseExpiresAt: undefined, + }); + return true; + }, +}); + +export const cancel = mutation({ + args: { commandId: v.id("daemonCommands") }, + handler: async (ctx, args) => { + const command = await ctx.db.get("daemonCommands", args.commandId); + if ( + !command || + ["succeeded", "failed", "cancelled"].includes(command.status) + ) { + return false; + } + const timestamp = Date.now(); + await ctx.db.patch("daemonCommands", command._id, { + status: "cancelled", + completedAt: timestamp, + updatedAt: timestamp, + leaseExpiresAt: undefined, + }); + return true; + }, +}); diff --git a/packages/backend/convex/daemonRuntime.ts b/packages/backend/convex/daemonRuntime.ts new file mode 100644 index 0000000..bdecff6 --- /dev/null +++ b/packages/backend/convex/daemonRuntime.ts @@ -0,0 +1,107 @@ +import { v } from "convex/values"; + +import { mutation, query } from "./_generated/server"; + +export const connect = mutation({ + args: { + daemonId: v.string(), + sessionId: v.string(), + hostname: v.string(), + platform: v.string(), + architecture: v.string(), + version: v.string(), + }, + handler: async (ctx, args) => { + const existing = await ctx.db + .query("daemonPresence") + .withIndex("by_sessionId", (q) => q.eq("sessionId", args.sessionId)) + .unique(); + const timestamp = Date.now(); + if (existing) { + await ctx.db.patch("daemonPresence", existing._id, { + status: "online", + lastHeartbeatAt: timestamp, + }); + return existing._id; + } + return await ctx.db.insert("daemonPresence", { + ...args, + status: "online", + startedAt: timestamp, + lastHeartbeatAt: timestamp, + }); + }, +}); + +export const heartbeat = mutation({ + args: { + daemonId: v.string(), + sessionId: v.string(), + }, + handler: async (ctx, args) => { + const presence = await ctx.db + .query("daemonPresence") + .withIndex("by_sessionId", (q) => q.eq("sessionId", args.sessionId)) + .unique(); + if (!presence || presence.daemonId !== args.daemonId) { + return false; + } + await ctx.db.patch("daemonPresence", presence._id, { + status: "online", + lastHeartbeatAt: Date.now(), + }); + return true; + }, +}); + +export const disconnect = mutation({ + args: { + daemonId: v.string(), + sessionId: v.string(), + }, + handler: async (ctx, args) => { + const presence = await ctx.db + .query("daemonPresence") + .withIndex("by_sessionId", (q) => q.eq("sessionId", args.sessionId)) + .unique(); + if (!presence || presence.daemonId !== args.daemonId) { + return false; + } + await ctx.db.patch("daemonPresence", presence._id, { + status: "offline", + lastHeartbeatAt: Date.now(), + }); + return true; + }, +}); + +export const recordEvent = mutation({ + args: { + daemonId: v.string(), + commandId: v.optional(v.id("daemonCommands")), + kind: v.string(), + data: v.any(), + }, + handler: async (ctx, args) => { + return await ctx.db.insert("daemonCommandEvents", { + ...args, + createdAt: Date.now(), + }); + }, +}); + +export const listEvents = query({ + args: { + daemonId: v.string(), + limit: v.optional(v.number()), + }, + handler: async (ctx, args) => { + return await ctx.db + .query("daemonCommandEvents") + .withIndex("by_daemonId_and_createdAt", (q) => + q.eq("daemonId", args.daemonId) + ) + .order("desc") + .take(Math.min(args.limit ?? 100, 500)); + }, +}); diff --git a/packages/backend/convex/daemons.ts b/packages/backend/convex/daemons.ts new file mode 100644 index 0000000..aeb8eb3 --- /dev/null +++ b/packages/backend/convex/daemons.ts @@ -0,0 +1,60 @@ +import { v } from "convex/values"; + +import { mutation, query } from "./_generated/server"; + +const now = () => Date.now(); + +export const upsert = mutation({ + args: { + daemonId: v.string(), + name: v.string(), + desiredState: v.union(v.literal("online"), v.literal("offline")), + agentOsConfig: v.any(), + }, + handler: async (ctx, args) => { + const existing = await ctx.db + .query("daemonDefinitions") + .withIndex("by_daemonId", (q) => q.eq("daemonId", args.daemonId)) + .unique(); + const timestamp = now(); + if (existing) { + await ctx.db.patch("daemonDefinitions", existing._id, { + name: args.name, + desiredState: args.desiredState, + agentOsConfig: args.agentOsConfig, + configVersion: existing.configVersion + 1, + updatedAt: timestamp, + }); + return existing._id; + } + return await ctx.db.insert("daemonDefinitions", { + ...args, + configVersion: 1, + createdAt: timestamp, + updatedAt: timestamp, + }); + }, +}); + +export const get = query({ + args: { daemonId: v.string() }, + handler: async (ctx, args) => { + const definition = await ctx.db + .query("daemonDefinitions") + .withIndex("by_daemonId", (q) => q.eq("daemonId", args.daemonId)) + .unique(); + const presence = await ctx.db + .query("daemonPresence") + .withIndex("by_daemonId", (q) => q.eq("daemonId", args.daemonId)) + .order("desc") + .first(); + return { definition, presence }; + }, +}); + +export const list = query({ + args: {}, + handler: async (ctx) => { + return await ctx.db.query("daemonDefinitions").order("desc").collect(); + }, +}); diff --git a/packages/backend/convex/schema.ts b/packages/backend/convex/schema.ts index 48e12cc..def8f0b 100644 --- a/packages/backend/convex/schema.ts +++ b/packages/backend/convex/schema.ts @@ -2,6 +2,66 @@ import { defineSchema, defineTable } from "convex/server"; import { v } from "convex/values"; export default defineSchema({ + daemonDefinitions: defineTable({ + daemonId: v.string(), + name: v.string(), + desiredState: v.union(v.literal("online"), v.literal("offline")), + agentOsConfig: v.any(), + configVersion: v.number(), + createdAt: v.number(), + updatedAt: v.number(), + }).index("by_daemonId", ["daemonId"]), + daemonPresence: defineTable({ + daemonId: v.string(), + sessionId: v.string(), + status: v.union( + v.literal("online"), + v.literal("draining"), + v.literal("offline") + ), + hostname: v.string(), + platform: v.string(), + architecture: v.string(), + version: v.string(), + startedAt: v.number(), + lastHeartbeatAt: v.number(), + }) + .index("by_daemonId", ["daemonId"]) + .index("by_sessionId", ["sessionId"]), + daemonCommands: defineTable({ + daemonId: v.string(), + method: v.string(), + args: v.any(), + actorKey: v.array(v.string()), + status: v.union( + v.literal("queued"), + v.literal("claimed"), + v.literal("running"), + v.literal("succeeded"), + v.literal("failed"), + v.literal("cancelled") + ), + attempts: v.number(), + claimedBySessionId: v.optional(v.string()), + leaseExpiresAt: v.optional(v.number()), + createdAt: v.number(), + updatedAt: v.number(), + startedAt: v.optional(v.number()), + completedAt: v.optional(v.number()), + result: v.optional(v.any()), + error: v.optional(v.string()), + }) + .index("by_daemonId_and_status", ["daemonId", "status"]) + .index("by_status_and_leaseExpiresAt", ["status", "leaseExpiresAt"]), + daemonCommandEvents: defineTable({ + daemonId: v.string(), + commandId: v.optional(v.id("daemonCommands")), + kind: v.string(), + data: v.any(), + createdAt: v.number(), + }) + .index("by_daemonId_and_createdAt", ["daemonId", "createdAt"]) + .index("by_commandId_and_createdAt", ["commandId", "createdAt"]), todos: defineTable({ text: v.string(), completed: v.boolean(), diff --git a/packages/env/package.json b/packages/env/package.json index fd326f7..8e930ae 100644 --- a/packages/env/package.json +++ b/packages/env/package.json @@ -5,7 +5,8 @@ "type": "module", "exports": { "./web": "./src/web.ts", - "./native": "./src/native.ts" + "./native": "./src/native.ts", + "./server": "./src/server.ts" }, "dependencies": { "@t3-oss/env-core": "^0.13.11", diff --git a/packages/env/src/server.ts b/packages/env/src/server.ts new file mode 100644 index 0000000..32e5fe2 --- /dev/null +++ b/packages/env/src/server.ts @@ -0,0 +1,22 @@ +import { createEnv } from "@t3-oss/env-core"; +import { z } from "zod"; + +const convexUrlSchema = (exampleHost: string) => + z.url().refine((url) => new URL(url).hostname !== exampleHost, { + message: `Replace the ${exampleHost} placeholder before running the app`, + }); + +export const env = createEnv({ + server: { + CONVEX_URL: convexUrlSchema("example.convex.cloud"), + DAEMON_ID: z.string().min(1), + DAEMON_NAME: z.string().min(1).optional(), + DAEMON_VERSION: z.string().default("0.0.0"), + DAEMON_HEARTBEAT_MS: z.coerce.number().int().positive().default(15_000), + DAEMON_COMMAND_LEASE_MS: z.coerce.number().int().positive().default(60_000), + RIVET_ENDPOINT: z.url().optional(), + }, + runtimeEnv: process.env, + skipValidation: process.env.SKIP_ENV_VALIDATION === "true", + emptyStringAsUndefined: true, +}); diff --git a/packages/primitives/package.json b/packages/primitives/package.json new file mode 100644 index 0000000..d674596 --- /dev/null +++ b/packages/primitives/package.json @@ -0,0 +1,22 @@ +{ + "name": "@code/primitives", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts", + "./agent-os": "./src/agent-os.ts" + }, + "scripts": { + "check-types": "tsc --noEmit" + }, + "dependencies": { + "@rivet-dev/agentos": "^0.2.7", + "effect": "4.0.0-beta.99" + }, + "devDependencies": { + "@code/config": "workspace:*", + "@types/node": "^22.13.14", + "typescript": "^6" + } +} diff --git a/packages/primitives/src/agent-os.ts b/packages/primitives/src/agent-os.ts new file mode 100644 index 0000000..065dc5f --- /dev/null +++ b/packages/primitives/src/agent-os.ts @@ -0,0 +1,64 @@ +import { + agentOS as createAgentOsActor, + type AgentOSConfigInput, +} from "@rivet-dev/agentos"; +import { Context, Effect, Layer, Schema } from "effect"; + +export class AgentOsError extends Schema.TaggedErrorClass()( + "AgentOsError", + { + cause: Schema.Defect(), + } +) {} + +export interface AgentOsOptions { + readonly config?: AgentOSConfigInput; +} + +export class AgentOs extends Context.Service< + AgentOs, + { + readonly createActor: ( + config?: AgentOSConfigInput + ) => Effect.Effect< + ReturnType>, + AgentOsError + >; + } +>()("@code/primitives/agent-os/AgentOs") { + static readonly layer = Layer.succeed( + AgentOs, + AgentOs.of({ + createActor: Effect.fn("AgentOs.createActor")(function* ( + config: AgentOSConfigInput = {} + ) { + return yield* Effect.try({ + try: () => createAgentOsActor(config), + catch: (cause) => new AgentOsError({ cause }), + }); + }), + }) + ); +} + +export const makeAgentOsLayer = (options: AgentOsOptions = {}) => + Layer.succeed( + AgentOs, + AgentOs.of({ + createActor: Effect.fn("AgentOs.createActor")(function* ( + config: AgentOSConfigInput = options.config ?? {} + ) { + return yield* Effect.try({ + try: () => createAgentOsActor(config), + catch: (cause) => new AgentOsError({ cause }), + }); + }), + }) + ); + +export const createAgentOsActorEffect = Effect.fn("createAgentOsActorEffect")( + function* (config?: AgentOSConfigInput) { + const agentOs = yield* AgentOs; + return yield* agentOs.createActor(config); + } +); diff --git a/packages/primitives/src/index.ts b/packages/primitives/src/index.ts new file mode 100644 index 0000000..7c8f0e2 --- /dev/null +++ b/packages/primitives/src/index.ts @@ -0,0 +1 @@ +export * from "./agent-os"; diff --git a/packages/primitives/tsconfig.json b/packages/primitives/tsconfig.json new file mode 100644 index 0000000..a571807 --- /dev/null +++ b/packages/primitives/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "@code/config/tsconfig.base.json", + "include": ["src/**/*.ts"], + "exclude": ["dist"] +} diff --git a/scripts/subtree.ts b/scripts/subtree.ts new file mode 100644 index 0000000..eabc711 --- /dev/null +++ b/scripts/subtree.ts @@ -0,0 +1,321 @@ +import { parseArgs } from "node:util"; + +import manifest from "./subtrees.json"; + +interface Subtree { + readonly name: string; + readonly prefix: string; + readonly upstream: string; + readonly ref: string; + readonly squash: true; + readonly role: string; + readonly refreshPolicy: "allowed" | "pinned"; +} + +interface CommandResult { + readonly exitCode: number; + readonly stdout: string; + readonly stderr: string; +} + +const cwd = process.cwd(); +const subtrees = manifest.subtrees as readonly Subtree[]; + +const run = async ( + command: readonly string[], + options: { readonly inherit?: boolean } = {} +): Promise => { + const process = Bun.spawn([...command], { + cwd, + stdin: options.inherit ? "inherit" : "ignore", + stdout: options.inherit ? "inherit" : "pipe", + stderr: options.inherit ? "inherit" : "pipe", + }); + const [exitCode, stdout, stderr] = await Promise.all([ + process.exited, + options.inherit ? Promise.resolve("") : new Response(process.stdout).text(), + options.inherit ? Promise.resolve("") : new Response(process.stderr).text(), + ]); + return { exitCode, stdout, stderr }; +}; + +const shellQuote = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`; +const formatCommand = (command: readonly string[]) => + command.map(shellQuote).join(" "); + +const requireRepositoryRoot = async () => { + const result = await run(["git", "rev-parse", "--show-toplevel"]); + if (result.exitCode !== 0) { + throw new Error("The current directory is not inside a Git checkout."); + } + if (result.stdout.trim() !== cwd) { + throw new Error( + `Run this script from the repository root: ${result.stdout.trim()}` + ); + } +}; + +const requireCleanWorktree = async () => { + const result = await run(["git", "status", "--porcelain"]); + if (result.exitCode !== 0) { + throw new Error(result.stderr.trim()); + } + if (result.stdout.trim() !== "") { + throw new Error( + "Subtree mutations require a clean worktree. Commit or stash changes first." + ); + } +}; + +const getSubtree = (name: string | undefined) => { + if (name === undefined) { + throw new Error( + `A subtree name is required. Available: ${subtrees.map((entry) => entry.name).join(", ")}` + ); + } + const subtree = subtrees.find((entry) => entry.name === name); + if (subtree === undefined) { + throw new Error( + `Unknown subtree ${shellQuote(name)}. Available: ${subtrees.map((entry) => entry.name).join(", ")}` + ); + } + if ( + !subtree.prefix.startsWith("repos/") || + !subtree.upstream.startsWith("https://") + ) { + throw new Error( + `Unsafe subtree manifest entry ${shellQuote(subtree.name)}.` + ); + } + return subtree; +}; + +const readSubtreeMetadata = async (subtree: Subtree) => { + const merge = await run([ + "git", + "log", + "--all", + "-n", + "1", + "--format=%H%x09%ci%x09%s", + "--", + subtree.prefix, + ]); + if (merge.exitCode !== 0) { + throw new Error(merge.stderr.trim()); + } + const mergeLine = merge.stdout.trim(); + if (mergeLine === "") { + return { mergeLine: "No subtree merge found", split: undefined }; + } + const mergeSha = mergeLine.split("\t")[0]; + if (mergeSha === undefined) { + return { mergeLine, split: undefined }; + } + const squash = await run([ + "git", + "show", + "--no-patch", + "--format=%b", + `${mergeSha}^2`, + ]); + const split = squash.stdout + .split("\n") + .find((line) => line.startsWith("git-subtree-split: ")) + ?.slice("git-subtree-split: ".length); + return { mergeLine, split }; +}; + +const readStatus = async (subtree: Subtree) => { + const [dirty, metadata] = await Promise.all([ + run(["git", "status", "--porcelain", "--", subtree.prefix]), + readSubtreeMetadata(subtree), + ]); + if (dirty.exitCode !== 0) { + throw new Error(dirty.stderr.trim()); + } + return { + dirty: dirty.stdout.trim() !== "", + latest: metadata.mergeLine, + }; +}; + +const updateCommand = (subtree: Subtree) => [ + "git", + "subtree", + "pull", + `--prefix=${subtree.prefix}`, + subtree.upstream, + subtree.ref, + "--squash", +]; + +const addCommand = (subtree: Subtree) => [ + "git", + "subtree", + "add", + `--prefix=${subtree.prefix}`, + subtree.upstream, + subtree.ref, + "--squash", +]; + +const { values, positionals } = parseArgs({ + args: process.argv.slice(2), + options: { + "dry-run": { type: "boolean", default: false }, + "force-pinned": { type: "boolean", default: false }, + help: { type: "boolean", short: "h", default: false }, + yes: { type: "boolean", short: "y", default: false }, + }, + allowPositionals: true, + strict: true, +}); + +const [operation = "list", name, ...extra] = positionals; +if (values.help || extra.length > 0) { + console.log(`Usage: bun run subtree [list|status|preview|add|update] [name] [options] + +Commands: + list List configured vendored subtrees + status [name] Show local subtree metadata and dirtiness + preview Fetch the configured upstream and show incoming commits + add Add an absent manifest entry with git subtree add --squash + update Pull a configured subtree with git subtree pull --squash + +Options: + --dry-run Print mutating/fetch commands without executing them + --yes, -y Required for add and update + --force-pinned Allow updating a pinned historical subtree together with --yes`); + process.exit(extra.length > 0 ? 1 : 0); +} + +try { + await requireRepositoryRoot(); + + switch (operation) { + case "list": { + for (const subtree of subtrees) { + console.log( + `${subtree.name}\t${subtree.prefix}\t${subtree.upstream}#${subtree.ref}\t${subtree.refreshPolicy}` + ); + } + break; + } + case "status": { + const selected = name === undefined ? subtrees : [getSubtree(name)]; + for (const subtree of selected) { + const status = await readStatus(subtree); + console.log(`${subtree.name}:`); + console.log(` prefix: ${subtree.prefix}`); + console.log(` upstream: ${subtree.upstream}#${subtree.ref}`); + console.log(` policy: ${subtree.refreshPolicy}`); + console.log(` prefix dirty: ${status.dirty ? "yes" : "no"}`); + console.log(` latest metadata: ${status.latest}`); + } + break; + } + case "preview": { + const subtree = getSubtree(name); + const fetch = [ + "git", + "fetch", + "--no-tags", + subtree.upstream, + subtree.ref, + ]; + if (values["dry-run"]) { + console.log(formatCommand(fetch)); + console.log( + formatCommand([ + "git", + "log", + "--oneline", + "--decorate", + "..FETCH_HEAD", + ]) + ); + break; + } + const fetched = await run(fetch, { inherit: true }); + if (fetched.exitCode !== 0) { + process.exit(fetched.exitCode); + } + const metadata = await readSubtreeMetadata(subtree); + if (metadata.split === undefined) { + throw new Error( + `No git-subtree-split metadata found for ${subtree.prefix}.` + ); + } + const log = await run([ + "git", + "log", + "--oneline", + "--decorate", + `${metadata.split}..FETCH_HEAD`, + ]); + if (log.exitCode !== 0) { + throw new Error(log.stderr.trim()); + } + console.log(log.stdout.trim() || `${subtree.name} is up to date.`); + break; + } + case "add": + case "update": { + const subtree = getSubtree(name); + const prefixType = await run([ + "git", + "cat-file", + "-t", + `HEAD:${subtree.prefix}`, + ]); + const prefixExists = + prefixType.exitCode === 0 && prefixType.stdout.trim() === "tree"; + if ( + operation === "update" && + subtree.refreshPolicy === "pinned" && + !values["force-pinned"] + ) { + throw new Error( + `${subtree.name} is pinned historical reference material. Pass --force-pinned --yes only when historical synchronization is explicitly required.` + ); + } + if (!values["dry-run"]) { + await requireCleanWorktree(); + } + if (operation === "add" && prefixExists) { + throw new Error( + `Cannot add ${subtree.name}: ${subtree.prefix} already exists.` + ); + } + if (operation === "update" && !prefixExists) { + throw new Error( + `Cannot update ${subtree.name}: ${subtree.prefix} does not exist.` + ); + } + const command = + operation === "add" ? addCommand(subtree) : updateCommand(subtree); + console.log(formatCommand(command)); + if (values["dry-run"]) { + break; + } + if (!values.yes) { + throw new Error( + `Refusing to ${operation} without --yes. Re-run after reviewing the command above.` + ); + } + const result = await run(command, { inherit: true }); + if (result.exitCode !== 0) { + process.exit(result.exitCode); + } + break; + } + default: + throw new Error( + `Unknown command ${shellQuote(operation)}. Use list, status, preview, add, or update.` + ); + } +} catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + process.exit(1); +} diff --git a/scripts/subtrees.json b/scripts/subtrees.json new file mode 100644 index 0000000..3711e0c --- /dev/null +++ b/scripts/subtrees.json @@ -0,0 +1,22 @@ +{ + "subtrees": [ + { + "name": "effect", + "prefix": "repos/effect", + "upstream": "https://github.com/Effect-TS/effect.git", + "ref": "main", + "squash": true, + "role": "Current Effect v4 source of truth", + "refreshPolicy": "allowed" + }, + { + "name": "effect-smol", + "prefix": "repos/effect-smol", + "upstream": "https://github.com/Effect-TS/effect-smol.git", + "ref": "main", + "squash": true, + "role": "Archived historical Effect v4 reference", + "refreshPolicy": "pinned" + } + ] +} diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json new file mode 100644 index 0000000..7cd7042 --- /dev/null +++ b/scripts/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../packages/config/tsconfig.base.json", + "compilerOptions": { + "types": ["node", "bun"] + }, + "include": ["**/*.ts"] +} diff --git a/scripts/update-docs.ts b/scripts/update-docs.ts new file mode 100644 index 0000000..6751fc4 --- /dev/null +++ b/scripts/update-docs.ts @@ -0,0 +1,282 @@ +import { parseArgs } from "node:util"; + +const excludedPrefixes = [ + ".agents/", + ".claude/skills/", + "node_modules/", + "repos/", + "dist/", + "build/", + "apps/web/build/", + "apps/web/.react-router/", + "apps/native/.expo/", + "apps/native/dist/", + "apps/native/web-build/", + "packages/backend/convex/_generated/", +]; + +const documentationNames = new Set([ + "AGENTS.md", + "README.md", + "README.mdx", + "LLMS.md", +]); + +const supportedAgents = ["codex", "opencode", "claude"] as const; +type AgentName = (typeof supportedAgents)[number]; + +interface CommandResult { + readonly exitCode: number; + readonly stdout: string; + readonly stderr: string; +} + +const run = async ( + command: readonly string[], + options: { readonly stdin?: string; readonly inherit?: boolean } = {} +): Promise => { + const process = Bun.spawn([...command], { + cwd: processCwd, + stdin: options.stdin === undefined ? "ignore" : new Blob([options.stdin]), + stdout: options.inherit ? "inherit" : "pipe", + stderr: options.inherit ? "inherit" : "pipe", + }); + const [exitCode, stdout, stderr] = await Promise.all([ + process.exited, + options.inherit ? Promise.resolve("") : new Response(process.stdout).text(), + options.inherit ? Promise.resolve("") : new Response(process.stderr).text(), + ]); + return { exitCode, stdout, stderr }; +}; + +const shellQuote = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`; +const formatCommand = (command: readonly string[]) => + command.map(shellQuote).join(" "); + +const isExcluded = (path: string) => + excludedPrefixes.some((prefix) => { + const directory = prefix.slice(0, -1); + return ( + path === directory || + path.startsWith(prefix) || + path.includes(`/${directory}/`) || + path.endsWith(`/${directory}`) + ); + }); + +const isDocumentation = (path: string) => { + const name = path.split("/").at(-1) ?? path; + return ( + documentationNames.has(name) || + name.endsWith(".md") || + name.endsWith(".mdx") + ); +}; + +const resolveRange = async (revision: string | undefined) => { + const requested = revision ?? "HEAD"; + if (requested.includes("..")) { + const result = await run(["git", "rev-list", "--max-count=1", requested]); + if (result.exitCode !== 0 || result.stdout.trim() === "") { + throw new Error( + `Invalid revision range ${shellQuote(requested)}: ${result.stderr.trim()}` + ); + } + return requested; + } + const verify = await run([ + "git", + "rev-parse", + "--verify", + `${requested}^{commit}`, + ]); + if (verify.exitCode !== 0) { + throw new Error( + `Invalid commit ${shellQuote(requested)}: ${verify.stderr.trim()}` + ); + } + return `${requested}^!`; +}; + +const listChangedFiles = async (range: string) => { + const result = await run([ + "git", + "diff", + "--name-only", + "--diff-filter=ACDMRTUXB", + range, + "--", + ]); + if (result.exitCode !== 0) { + throw new Error( + `Unable to inspect ${shellQuote(range)}: ${result.stderr.trim()}` + ); + } + return result.stdout + .split("\n") + .map((path) => path.trim()) + .filter((path) => path !== "" && !isExcluded(path)); +}; + +const listDocumentationFiles = async () => { + const result = await run(["git", "ls-files", "*.md", "*.mdx"]); + if (result.exitCode !== 0) { + throw new Error( + `Unable to list documentation files: ${result.stderr.trim()}` + ); + } + return result.stdout + .split("\n") + .map((path) => path.trim()) + .filter( + (path) => path !== "" && !isExcluded(path) && isDocumentation(path) + ); +}; + +const resolveAgent = (requested: string | undefined): AgentName => { + const configured = requested ?? process.env.DOCS_AGENT; + if (configured !== undefined) { + if (!supportedAgents.includes(configured as AgentName)) { + throw new Error( + `Unsupported agent ${shellQuote(configured)}. Use codex, opencode, or claude.` + ); + } + if (Bun.which(configured) === null) { + throw new Error( + `Agent executable ${shellQuote(configured)} was not found on PATH.` + ); + } + return configured as AgentName; + } + const detected = supportedAgents.find((agent) => Bun.which(agent) !== null); + if (detected === undefined) { + throw new Error( + "No supported coding agent found. Install codex, opencode, or claude, or set DOCS_AGENT." + ); + } + return detected; +}; + +const agentCommand = (agent: AgentName) => { + switch (agent) { + case "codex": + return [ + "codex", + "exec", + "-", + "--sandbox", + "workspace-write", + "--cd", + processCwd, + "--ephemeral", + ]; + case "opencode": + return ["opencode", "run", "--auto"]; + case "claude": + return ["claude", "--print", "--permission-mode", "acceptEdits"]; + } +}; + +const buildPrompt = (input: { + readonly range: string; + readonly changedFiles: readonly string[]; + readonly documentationFiles: readonly string[]; + readonly diff: string; +}) => `Update repository documentation for revision ${input.range} in the current checkout. + +Requirements: +- Read and follow the root AGENTS.md and any more specific AGENTS.md governing files you edit. +- Inspect the supplied diff and the current code before editing; do not document behavior that is not implemented. +- Update affected README.md, AGENTS.md, LLMS.md, or other first-party Markdown/MDX files when the revision made them stale. +- Keep documentation concise and practical. Preserve generated markers and package-specific instructions. +- Never edit repos/**, .agents/**, .claude/skills/**, generated files, or dependency/build output. +- Do not modify source code, run broad formatting, or commit changes. +- If documentation is already accurate, make no edits and say so. + +Changed first-party files: +${input.changedFiles.map((path) => `- ${path}`).join("\n") || "- None"} + +First-party documentation candidates: +${input.documentationFiles.map((path) => `- ${path}`).join("\n") || "- None"} + +Revision diff: +\`\`\`diff +${input.diff} +\`\`\` +`; + +const processCwd = process.cwd(); +const { values, positionals } = parseArgs({ + args: process.argv.slice(2), + options: { + agent: { type: "string" }, + "dry-run": { type: "boolean", default: false }, + help: { type: "boolean", short: "h", default: false }, + }, + allowPositionals: true, + strict: true, +}); + +if (values.help || positionals.length > 1) { + console.log(`Usage: bun run docs:update [] [--agent codex|opencode|claude] [--dry-run] + +A single commit defaults to HEAD and is converted to ^!. Revision ranges such as main..HEAD and main...HEAD are accepted directly. Set DOCS_AGENT to choose the default coding-agent CLI.`); + process.exit(positionals.length > 1 ? 1 : 0); +} + +try { + const range = await resolveRange(positionals[0]); + const [changedFiles, documentationFiles, diffResult] = await Promise.all([ + listChangedFiles(range), + listDocumentationFiles(), + run([ + "git", + "diff", + "--binary", + "--find-renames", + range, + "--", + ".", + ":(exclude)repos/**", + ]), + ]); + if (diffResult.exitCode !== 0) { + throw new Error( + `Unable to read revision diff: ${diffResult.stderr.trim()}` + ); + } + const agent = resolveAgent(values.agent); + const command = agentCommand(agent); + const prompt = buildPrompt({ + range, + changedFiles, + documentationFiles, + diff: diffResult.stdout, + }); + + console.log(`Revision: ${range}`); + console.log(`Agent: ${agent}`); + console.log(`Changed first-party files: ${changedFiles.length}`); + console.log(`Command: ${formatCommand(command)} < generated-prompt`); + + if (values["dry-run"]) { + console.log("\n--- Generated prompt ---\n"); + console.log(prompt); + process.exit(0); + } + + const result = await run(command, { stdin: prompt, inherit: true }); + if (result.exitCode !== 0) { + process.exit(result.exitCode); + } + const status = await run(["git", "status", "--short", "--", "*.md", "*.mdx"]); + if (status.stdout.trim() !== "") { + console.log("\nDocumentation changes:"); + console.log(status.stdout.trimEnd()); + } else { + console.log("\nNo documentation files changed."); + } +} catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + process.exit(1); +} diff --git a/skills-lock.json b/skills-lock.json new file mode 100644 index 0000000..7f84ca2 --- /dev/null +++ b/skills-lock.json @@ -0,0 +1,53 @@ +{ + "version": 1, + "skills": { + "ai-agent": { + "source": "rivet-dev/skills", + "sourceType": "github", + "skillPath": "ai-agent/SKILL.md", + "computedHash": "2fcfbec0078d8f99d542690d9cfd07b14deaaedfd04cad82907ed701d230ead1" + }, + "ai-agent-workspace": { + "source": "rivet-dev/skills", + "sourceType": "github", + "skillPath": "ai-agent-workspace/SKILL.md", + "computedHash": "29471323f352581f1e565c4630827de4f945211d2311ab312adbd35047d2540e" + }, + "chat-room": { + "source": "rivet-dev/skills", + "sourceType": "github", + "skillPath": "chat-room/SKILL.md", + "computedHash": "e1f4da5c1af055d870b0a6b4d58106b4caf3e2e58db5528059a2baa11e9090ac" + }, + "cron-jobs": { + "source": "rivet-dev/skills", + "sourceType": "github", + "skillPath": "cron-jobs/SKILL.md", + "computedHash": "298eb217e7009f128416a97a172ccaa9325e0d3c2ef3d29fc4b894011ebc539d" + }, + "rivetkit": { + "source": "rivet-dev/skills", + "sourceType": "github", + "skillPath": "rivetkit/SKILL.md", + "computedHash": "514294adb49224f12c6a940c814ffb9a5b27d2a300f7b09c560ff44db1604ec2" + }, + "rivetkit-client-javascript": { + "source": "rivet-dev/skills", + "sourceType": "github", + "skillPath": "rivetkit-client-javascript/SKILL.md", + "computedHash": "26d0ebbb267055d7b5ca99ebf4af0924f74b84c1135d578aced6eb01d3e0613b" + }, + "rivetkit-client-react": { + "source": "rivet-dev/skills", + "sourceType": "github", + "skillPath": "rivetkit-client-react/SKILL.md", + "computedHash": "44100332aaf08ff07470e4af815f9f875b9cb1db750fea349d4d2454c7f375ce" + }, + "sandbox-agent": { + "source": "rivet-dev/skills", + "sourceType": "github", + "skillPath": "skills/sandbox-agent/SKILL.md", + "computedHash": "52d74874f6b15618028981bff02054e392b52e2416396dd384f48ac75d769a58" + } + } +}