Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/agents/openai.yaml +4 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/agents-push.md +156 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/auth-login.md +54 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/connectors-create.md +126 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/connectors-list-available.md +56 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/connectors-push.md +137 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/exec.md +47 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/functions-pull.md +80 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/secrets-list.md +25 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/agents/openai.yaml +4 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/QUICK_REFERENCE.md +178 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/analytics.md +113 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/app-logs.md +120 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/auth.md +770 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/base44-agents.md +386 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/client.md +265 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/connectors.md +157 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/entities.md +399 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/functions.md +291 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/integrations.md +375 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/sso.md +75 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/users.md +82 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-troubleshooter/agents/openai.yaml +4 -0
- data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-troubleshooter/references/project-logs.md +57 -0
- data/.codex/.codex/.tmp/plugins/plugins/carta-crm/.codex-plugin/plugin.json +32 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/.codex-plugin/plugin.json +47 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/assets/cloudflare-small.svg +3 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/commands/build-agent.md +40 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/commands/build-mcp.md +38 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/LICENSE.txt +201 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/SKILL.md +155 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/agents/openai.yaml +6 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/assets/cloudflare-small.svg +3 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/callable.md +92 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/codemode.md +207 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/email.md +146 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/mcp.md +154 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/state-scheduling.md +164 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/streaming-chat.md +178 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/workflows.md +132 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/SKILL.md +400 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/agents/openai.yaml +3 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/agent-patterns.md +461 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/examples.md +188 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/state-patterns.md +360 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/troubleshooting.md +362 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/SKILL.md +266 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/agents/openai.yaml +3 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/references/examples.md +108 -0
- data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/references/oauth-setup.md +338 -0
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/agents/openai.yaml
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
interface:
|
| 2 |
+
display_name: "Base44 CLI"
|
| 3 |
+
short_description: "Initialize, configure, deploy, and manage Base44 projects"
|
| 4 |
+
default_prompt: "Use Base44 CLI guidance to initialize, configure, authenticate, and deploy this Base44 app."
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/agents-push.md
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# base44 agents push
|
| 2 |
+
|
| 3 |
+
Push local AI agent configurations to Base44. Agents are conversational AI assistants that can interact with users, access your app's entities, and call backend functions.
|
| 4 |
+
|
| 5 |
+
## Syntax
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
npx base44 agents push
|
| 9 |
+
```
|
| 10 |
+
|
| 11 |
+
## Authentication
|
| 12 |
+
|
| 13 |
+
**Required**: Yes. If not authenticated, you'll be prompted to login first.
|
| 14 |
+
|
| 15 |
+
## What It Does
|
| 16 |
+
|
| 17 |
+
1. Reads all agent files from the `base44/agents/` directory
|
| 18 |
+
2. Validates agent configurations
|
| 19 |
+
3. Displays the count of agents to be pushed
|
| 20 |
+
4. Uploads agents to the Base44 backend
|
| 21 |
+
5. Reports the results: created, updated, and deleted agents
|
| 22 |
+
|
| 23 |
+
## Prerequisites
|
| 24 |
+
|
| 25 |
+
- Must be run from a Base44 project directory
|
| 26 |
+
- Project must have agent definitions in the `base44/agents/` folder
|
| 27 |
+
|
| 28 |
+
## Output
|
| 29 |
+
|
| 30 |
+
```bash
|
| 31 |
+
$ npx base44 agents push
|
| 32 |
+
|
| 33 |
+
Found 2 agents to push
|
| 34 |
+
Pushing agents to Base44...
|
| 35 |
+
|
| 36 |
+
Created: support_agent
|
| 37 |
+
Updated: order_bot
|
| 38 |
+
Deleted: old_agent
|
| 39 |
+
|
| 40 |
+
✓ Agents pushed to Base44
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
## Agent Synchronization
|
| 44 |
+
|
| 45 |
+
The push operation synchronizes your local agents with Base44:
|
| 46 |
+
|
| 47 |
+
- **Created**: New agents that didn't exist in Base44
|
| 48 |
+
- **Updated**: Existing agents with modified configuration
|
| 49 |
+
- **Deleted**: Agents that were removed from your local configuration
|
| 50 |
+
|
| 51 |
+
**Warning**: This is a full sync operation. Agents removed locally will be deleted from Base44.
|
| 52 |
+
|
| 53 |
+
## Error Handling
|
| 54 |
+
|
| 55 |
+
If no agents are found in your project:
|
| 56 |
+
```bash
|
| 57 |
+
$ npx base44 agents push
|
| 58 |
+
No local agents found - this will delete all remote agents
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
If an agent has an invalid name:
|
| 62 |
+
```bash
|
| 63 |
+
$ npx base44 agents push
|
| 64 |
+
Error: Agent name must be lowercase alphanumeric with underscores
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
## Agent Configuration Schema
|
| 68 |
+
|
| 69 |
+
Each agent file should be a `.jsonc` file in `base44/agents/` with this structure:
|
| 70 |
+
|
| 71 |
+
```jsonc
|
| 72 |
+
{
|
| 73 |
+
"name": "agent_name", // Required: lowercase alphanumeric with underscores, 1-100 chars
|
| 74 |
+
"description": "Brief description of what this agent does", // Required: min 1 char
|
| 75 |
+
"instructions": "Detailed instructions for the agent's behavior", // Required: min 1 char
|
| 76 |
+
"tool_configs": [ // Optional: defaults to []
|
| 77 |
+
// Entity tool - gives agent access to entity operations
|
| 78 |
+
{ "entity_name": "Task", "allowed_operations": ["read", "create", "update", "delete"] },
|
| 79 |
+
// Backend function tool - gives agent access to a function
|
| 80 |
+
{ "function_name": "send_email", "description": "Send an email notification" }
|
| 81 |
+
],
|
| 82 |
+
"whatsapp_greeting": "Hello! How can I help you today?" // Optional
|
| 83 |
+
}
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
**Naming rules:**
|
| 87 |
+
- **Agent names** must match pattern: `/^[a-z0-9_]+$/` (lowercase alphanumeric with underscores only, 1-100 characters)
|
| 88 |
+
- Valid: `support_agent`, `order_bot`, `task_helper`
|
| 89 |
+
- Invalid: `Support-Agent`, `OrderBot`, `task helper`
|
| 90 |
+
- **Agent file names** must use underscores (matching the agent name)
|
| 91 |
+
- Valid: `support_agent.jsonc`, `order_bot.jsonc`
|
| 92 |
+
- Invalid: `support-agent.jsonc` (hyphens not allowed)
|
| 93 |
+
- **Entity names in `tool_configs`** must use PascalCase (matching the entity's `name` field)
|
| 94 |
+
- Valid: `"entity_name": "Task"`, `"entity_name": "TeamMember"`
|
| 95 |
+
- Invalid: `"entity_name": "task"`, `"entity_name": "team_member"`
|
| 96 |
+
|
| 97 |
+
**Required fields:**
|
| 98 |
+
- `name`: Required, must follow naming rules above
|
| 99 |
+
- `description`: Required, minimum 1 character
|
| 100 |
+
- `instructions`: Required, minimum 1 character
|
| 101 |
+
- `tool_configs`: Optional, defaults to empty array
|
| 102 |
+
- `whatsapp_greeting`: Optional
|
| 103 |
+
|
| 104 |
+
### Common Mistake: Wrong tool_configs Format
|
| 105 |
+
|
| 106 |
+
**WRONG** - Do NOT use `tools` with `type` and `entity`:
|
| 107 |
+
```jsonc
|
| 108 |
+
{
|
| 109 |
+
"name": "my_agent",
|
| 110 |
+
"tools": [ // ❌ WRONG
|
| 111 |
+
{ "type": "entity_query", "entity": "Task" }
|
| 112 |
+
]
|
| 113 |
+
}
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
**CORRECT** - Use `tool_configs` with `entity_name` and `allowed_operations`:
|
| 117 |
+
```jsonc
|
| 118 |
+
{
|
| 119 |
+
"name": "my_agent",
|
| 120 |
+
"tool_configs": [ // ✅ CORRECT
|
| 121 |
+
{ "entity_name": "Task", "allowed_operations": ["read"] }
|
| 122 |
+
]
|
| 123 |
+
}
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
### Best Practices for Agent Instructions
|
| 127 |
+
|
| 128 |
+
When giving agents access to entities, be explicit in the instructions about using the tools:
|
| 129 |
+
|
| 130 |
+
```jsonc
|
| 131 |
+
{
|
| 132 |
+
"name": "support_agent",
|
| 133 |
+
"instructions": "You are a helpful support agent.\n\nIMPORTANT: You have access to customer data through entity tools. When users ask about their orders or account:\n1. ALWAYS use the Order entity tool to query their order history\n2. Use the Customer entity tool to look up account details\n3. Analyze the data and provide personalized responses\n\nAlways query the relevant entities first before answering questions about user data.",
|
| 134 |
+
"tool_configs": [
|
| 135 |
+
{ "entity_name": "Order", "allowed_operations": ["read"] },
|
| 136 |
+
{ "entity_name": "Customer", "allowed_operations": ["read"] }
|
| 137 |
+
]
|
| 138 |
+
}
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
Without explicit instructions to use the entity tools, the agent may not proactively query user data when asked.
|
| 142 |
+
|
| 143 |
+
## Use Cases
|
| 144 |
+
|
| 145 |
+
- After defining new agents in your project
|
| 146 |
+
- When modifying existing agent configurations
|
| 147 |
+
- To sync agent changes before testing
|
| 148 |
+
- As part of your development workflow when agent behavior changes
|
| 149 |
+
|
| 150 |
+
## Notes
|
| 151 |
+
|
| 152 |
+
- This command syncs the agent configuration, not conversation data
|
| 153 |
+
- Changes are applied to your Base44 project immediately
|
| 154 |
+
- Make sure to test agent changes in a development environment first
|
| 155 |
+
- Agent definitions are located in the `base44/agents/` directory
|
| 156 |
+
- Use `base44 agents pull` to download agents from Base44
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/auth-login.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# base44 login
|
| 2 |
+
|
| 3 |
+
Authenticate with Base44 using device code flow.
|
| 4 |
+
|
| 5 |
+
## Syntax
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
npx base44 login
|
| 9 |
+
```
|
| 10 |
+
|
| 11 |
+
## Authentication
|
| 12 |
+
|
| 13 |
+
**Required**: No (this is the login command itself)
|
| 14 |
+
|
| 15 |
+
## How It Works
|
| 16 |
+
|
| 17 |
+
The login command uses OAuth 2.0 device code flow for authentication:
|
| 18 |
+
|
| 19 |
+
1. Generates a device code for authentication
|
| 20 |
+
2. Displays a verification code and verification URI
|
| 21 |
+
3. Directs you to visit the URI and enter the code
|
| 22 |
+
4. Polls for authentication completion (up to device code expiration)
|
| 23 |
+
5. Retrieves access and refresh tokens upon successful authentication
|
| 24 |
+
6. Fetches and displays your user information
|
| 25 |
+
7. Saves authentication data locally with expiration timestamp
|
| 26 |
+
|
| 27 |
+
## Interactive Flow
|
| 28 |
+
|
| 29 |
+
```bash
|
| 30 |
+
$ npx base44 login
|
| 31 |
+
|
| 32 |
+
Please visit: https://auth.base44.com/device
|
| 33 |
+
Enter code: ABCD-EFGH
|
| 34 |
+
|
| 35 |
+
Waiting for authentication...
|
| 36 |
+
✓ Successfully authenticated!
|
| 37 |
+
|
| 38 |
+
Logged in as: user@example.com
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
## Session Management
|
| 42 |
+
|
| 43 |
+
- Authentication tokens are stored locally on your device
|
| 44 |
+
- Tokens include expiration timestamps
|
| 45 |
+
- The session persists across CLI sessions
|
| 46 |
+
- Other commands will automatically use your stored credentials
|
| 47 |
+
- Use `npx base44 logout` to clear your session
|
| 48 |
+
- Use `npx base44 whoami` to check your current authentication status
|
| 49 |
+
|
| 50 |
+
## Notes
|
| 51 |
+
|
| 52 |
+
- You only need to login once per device
|
| 53 |
+
- If your session expires, you'll be prompted to login again when running authenticated commands
|
| 54 |
+
- The CLI automatically prompts for login when you run commands that require authentication
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/connectors-create.md
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Creating Connectors
|
| 2 |
+
|
| 3 |
+
Connectors are OAuth integrations that let your Base44 app connect to external services like Google Calendar, Slack, Notion, and more. Once connected, you can use access tokens in backend functions to call external APIs directly.
|
| 4 |
+
|
| 5 |
+
## Key Concepts
|
| 6 |
+
|
| 7 |
+
- **Direct API Access**: Connectors provide raw OAuth access tokens - you call the external APIs directly from backend functions
|
| 8 |
+
- **App Builder's Account**: Connects your account (the app builder), not your end users' accounts
|
| 9 |
+
- **Backend Functions Only**: Tokens are only accessible server-side for security
|
| 10 |
+
|
| 11 |
+
## File Location
|
| 12 |
+
|
| 13 |
+
Create connector files in the `base44/connectors/` directory (or the directory specified by `connectorsDir` in your config.jsonc).
|
| 14 |
+
|
| 15 |
+
**File naming:** `{type}.jsonc` or `{type}.json`
|
| 16 |
+
|
| 17 |
+
Examples:
|
| 18 |
+
- `base44/connectors/googlecalendar.jsonc`
|
| 19 |
+
- `base44/connectors/slack.jsonc`
|
| 20 |
+
- `base44/connectors/notion.json`
|
| 21 |
+
|
| 22 |
+
## Schema
|
| 23 |
+
|
| 24 |
+
Each connector file must specify a `type` and optionally a list of `scopes`:
|
| 25 |
+
|
| 26 |
+
```jsonc
|
| 27 |
+
{
|
| 28 |
+
"type": "googlecalendar",
|
| 29 |
+
"scopes": [
|
| 30 |
+
"https://www.googleapis.com/auth/calendar.readonly",
|
| 31 |
+
"https://www.googleapis.com/auth/calendar.events"
|
| 32 |
+
]
|
| 33 |
+
}
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
### Fields
|
| 37 |
+
|
| 38 |
+
| Field | Type | Required | Description |
|
| 39 |
+
|-------|------|----------|-------------|
|
| 40 |
+
| `type` | string | Yes | The integration type (run `npx base44 connectors list-available` to see options) |
|
| 41 |
+
| `scopes` | string[] | No | OAuth scopes to request (defaults to `[]`) |
|
| 42 |
+
|
| 43 |
+
## Discovering Available Connector Types
|
| 44 |
+
|
| 45 |
+
Run the following command to get the up-to-date list of supported connector types. Note: `stripe` is also a valid type but is not returned by this command — treat it as supported (see Stripe example below).
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
npx base44 connectors list-available
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
This returns a JSON object with all available integrations, their display names, descriptions, and any required connection config fields. Example output (trimmed):
|
| 52 |
+
|
| 53 |
+
```json
|
| 54 |
+
{
|
| 55 |
+
"integrations": [
|
| 56 |
+
{
|
| 57 |
+
"integration_type": "googlecalendar",
|
| 58 |
+
"display_name": "Google Calendar",
|
| 59 |
+
"description": "Access and manage Google Calendar events",
|
| 60 |
+
"connection_config_fields": []
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"integration_type": "slack",
|
| 64 |
+
"display_name": "Slack User",
|
| 65 |
+
"description": "Send messages and interact with Slack as yourself (user integration)",
|
| 66 |
+
"connection_config_fields": []
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"integration_type": "share_point",
|
| 70 |
+
"display_name": "SharePoint",
|
| 71 |
+
"description": "Manage documents, lists, sites, and collaboration content in SharePoint",
|
| 72 |
+
"connection_config_fields": [
|
| 73 |
+
{
|
| 74 |
+
"name": "subdomain",
|
| 75 |
+
"display_name": "SharePoint Site",
|
| 76 |
+
"description": "The name of your SharePoint site (e.g., sites/mysite)",
|
| 77 |
+
"placeholder": "sites/mysite",
|
| 78 |
+
"required": true,
|
| 79 |
+
"validation_pattern": "^[a-zA-Z0-9/_-]+$",
|
| 80 |
+
"validation_error": "Please enter a valid SharePoint site path"
|
| 81 |
+
}
|
| 82 |
+
]
|
| 83 |
+
}
|
| 84 |
+
]
|
| 85 |
+
}
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
Use the `integration_type` value from this output as the `type` field in your connector file. Some connectors require additional `connection_config_fields` — check the output for details.
|
| 89 |
+
|
| 90 |
+
### Stripe (Sandbox)
|
| 91 |
+
|
| 92 |
+
```jsonc
|
| 93 |
+
// base44/connectors/stripe.jsonc
|
| 94 |
+
{
|
| 95 |
+
"type": "stripe",
|
| 96 |
+
"scopes": []
|
| 97 |
+
}
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
Note: Stripe does not require an OAuth browser flow. When you push this connector, Base44 automatically provisions a Stripe sandbox account on the server side. You may receive a claim URL in the push output to link the sandbox to your Stripe account.
|
| 101 |
+
|
| 102 |
+
## Rules and Constraints
|
| 103 |
+
|
| 104 |
+
1. **One connector per type**: You cannot have multiple connectors of the same type (e.g., two `googlecalendar` connectors)
|
| 105 |
+
|
| 106 |
+
2. **Type must be valid**: The `type` field must be a valid integration type (run `npx base44 connectors list-available` to see available types)
|
| 107 |
+
|
| 108 |
+
3. **Scopes are provider-specific**: Each service has its own scope format - refer to the provider's documentation
|
| 109 |
+
|
| 110 |
+
## Next Steps
|
| 111 |
+
|
| 112 |
+
After creating connector files, push them to Base44:
|
| 113 |
+
|
| 114 |
+
```bash
|
| 115 |
+
npx base44 connectors push
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
This will prompt you to authorize each new OAuth connector in your browser. Stripe is the exception — it is provisioned automatically without a browser flow. See [connectors-push.md](connectors-push.md) for details.
|
| 119 |
+
|
| 120 |
+
To pull existing connectors from Base44 to local files:
|
| 121 |
+
|
| 122 |
+
```bash
|
| 123 |
+
npx base44 connectors pull
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
See [connectors-pull.md](connectors-pull.md) for details.
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/connectors-list-available.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# base44 connectors list-available
|
| 2 |
+
|
| 3 |
+
List all integration types available in the Base44 connector catalog.
|
| 4 |
+
|
| 5 |
+
## Syntax
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
npx base44 connectors list-available
|
| 9 |
+
```
|
| 10 |
+
|
| 11 |
+
## Authentication
|
| 12 |
+
|
| 13 |
+
**Required**: Yes. If not authenticated, you'll be prompted to login first.
|
| 14 |
+
|
| 15 |
+
## What It Does
|
| 16 |
+
|
| 17 |
+
Fetches the catalog of available integration types from Base44 and displays each one with its display name, description, and any required configuration fields.
|
| 18 |
+
|
| 19 |
+
## Output
|
| 20 |
+
|
| 21 |
+
```bash
|
| 22 |
+
$ npx base44 connectors list-available
|
| 23 |
+
|
| 24 |
+
✓ Available integrations fetched successfully
|
| 25 |
+
|
| 26 |
+
Google Calendar
|
| 27 |
+
integrationType: googlecalendar
|
| 28 |
+
description: Access Google Calendar events and schedules
|
| 29 |
+
connectionConfigFields: []
|
| 30 |
+
|
| 31 |
+
Slack
|
| 32 |
+
integrationType: slack
|
| 33 |
+
description: Send messages and interact with Slack workspaces
|
| 34 |
+
connectionConfigFields: []
|
| 35 |
+
|
| 36 |
+
Stripe
|
| 37 |
+
integrationType: stripe
|
| 38 |
+
description: Process payments and manage Stripe accounts
|
| 39 |
+
connectionConfigFields: []
|
| 40 |
+
|
| 41 |
+
Found 14 available integrations.
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
Each integration is displayed in YAML format showing the integration type, description, and any connection configuration fields required for setup.
|
| 45 |
+
|
| 46 |
+
## Use Cases
|
| 47 |
+
|
| 48 |
+
- Discover all supported connector types before creating connector files
|
| 49 |
+
- Check if a specific integration is available in your Base44 plan
|
| 50 |
+
- See what configuration fields (if any) a connector requires
|
| 51 |
+
|
| 52 |
+
## Related Commands
|
| 53 |
+
|
| 54 |
+
- [connectors-create.md](connectors-create.md) - How to create connector configuration files
|
| 55 |
+
- [connectors-push.md](connectors-push.md) - Push local connectors to Base44
|
| 56 |
+
- [connectors-pull.md](connectors-pull.md) - Pull connectors from Base44 to local files
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/connectors-push.md
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# base44 connectors push
|
| 2 |
+
|
| 3 |
+
Push local connector configurations to Base44, synchronizing scopes and handling OAuth authorization.
|
| 4 |
+
|
| 5 |
+
## Usage
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
npx base44 connectors push
|
| 9 |
+
```
|
| 10 |
+
|
| 11 |
+
## What It Does
|
| 12 |
+
|
| 13 |
+
1. **Reads local connectors** from your `base44/connectors/` directory
|
| 14 |
+
2. **Syncs with Base44** - updates scopes for existing connectors
|
| 15 |
+
3. **Adds new connectors** - new OAuth connector types trigger authorization; Stripe is provisioned automatically
|
| 16 |
+
4. **Removes unlisted connectors** - connectors not in your local files are removed from Base44
|
| 17 |
+
|
| 18 |
+
## OAuth Authorization Flow
|
| 19 |
+
|
| 20 |
+
When you add a new connector, it needs to be authorized:
|
| 21 |
+
|
| 22 |
+
1. The CLI detects which connectors need authorization
|
| 23 |
+
2. You're prompted: "Open browser to authorize now?"
|
| 24 |
+
3. If you accept, the browser opens to the OAuth provider (Google, Slack, etc.)
|
| 25 |
+
4. You log into your account and approve the requested permissions
|
| 26 |
+
5. The browser closes and the CLI confirms authorization
|
| 27 |
+
|
| 28 |
+
**Important**: You choose which account to connect by logging into it during the OAuth flow. For example, if you have multiple Google accounts, you select which one to use in the Google login screen.
|
| 29 |
+
|
| 30 |
+
## Example Output
|
| 31 |
+
|
| 32 |
+
### Pushing connectors (no new authorization needed)
|
| 33 |
+
|
| 34 |
+
```
|
| 35 |
+
Found 2 connectors to push: googlecalendar, slack
|
| 36 |
+
✓ Connectors pushed
|
| 37 |
+
|
| 38 |
+
Summary:
|
| 39 |
+
Synced: googlecalendar, slack
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
### Pushing new connectors (authorization required)
|
| 43 |
+
|
| 44 |
+
```
|
| 45 |
+
Found 3 connectors to push: googlecalendar, slack, notion
|
| 46 |
+
✓ Connectors pushed
|
| 47 |
+
|
| 48 |
+
2 connector(s) require authorization in your browser:
|
| 49 |
+
slack: https://auth.base44.io/oauth/...
|
| 50 |
+
notion: https://auth.base44.io/oauth/...
|
| 51 |
+
|
| 52 |
+
? Open browser to authorize now? › Yes
|
| 53 |
+
|
| 54 |
+
Opening browser for slack...
|
| 55 |
+
✓ slack authorization complete
|
| 56 |
+
|
| 57 |
+
Opening browser for notion...
|
| 58 |
+
✓ notion authorization complete
|
| 59 |
+
|
| 60 |
+
Summary:
|
| 61 |
+
Synced: googlecalendar
|
| 62 |
+
Added: slack, notion
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
### Pushing Stripe (no OAuth required)
|
| 66 |
+
|
| 67 |
+
Stripe is provisioned automatically — no browser flow is needed:
|
| 68 |
+
|
| 69 |
+
```
|
| 70 |
+
Found 2 connectors to push: googlecalendar, stripe
|
| 71 |
+
✓ Connectors pushed
|
| 72 |
+
|
| 73 |
+
Summary:
|
| 74 |
+
✓ Stripe sandbox provisioned
|
| 75 |
+
Claim your Stripe sandbox: https://dashboard.stripe.com/...
|
| 76 |
+
Connectors dashboard: https://app.base44.com/...
|
| 77 |
+
Synced: googlecalendar
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
### Removing connectors
|
| 81 |
+
|
| 82 |
+
If you delete a connector file locally and push, it will be removed:
|
| 83 |
+
|
| 84 |
+
```
|
| 85 |
+
Found 1 connectors to push: googlecalendar
|
| 86 |
+
✓ Connectors pushed
|
| 87 |
+
|
| 88 |
+
Summary:
|
| 89 |
+
Synced: googlecalendar
|
| 90 |
+
Removed: slack
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
## CI/CD Environments
|
| 94 |
+
|
| 95 |
+
In non-interactive environments (no TTY, such as CI/CD pipelines), the OAuth flow is skipped automatically:
|
| 96 |
+
|
| 97 |
+
```
|
| 98 |
+
Skipped OAuth in non-interactive mode. Run 'base44 connectors push' locally or open the links above to authorize.
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
You must run `npx base44 connectors push` locally to complete authorization for new connectors.
|
| 102 |
+
|
| 103 |
+
## Skipping Authorization
|
| 104 |
+
|
| 105 |
+
If you choose not to authorize immediately, the connectors remain in a pending state:
|
| 106 |
+
|
| 107 |
+
```
|
| 108 |
+
? Open browser to authorize now? › No
|
| 109 |
+
|
| 110 |
+
Authorization skipped. Pending: slack, notion. Run 'base44 connectors push' again to complete.
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
Run the command again when you're ready to authorize.
|
| 114 |
+
|
| 115 |
+
## Summary Status Meanings
|
| 116 |
+
|
| 117 |
+
| Status | Meaning |
|
| 118 |
+
|--------|---------|
|
| 119 |
+
| Provisioned | Stripe sandbox was created automatically (no OAuth needed) |
|
| 120 |
+
| Synced | Connector already existed, scopes updated if needed |
|
| 121 |
+
| Added | New connector successfully authorized via OAuth |
|
| 122 |
+
| Removed | Connector was deleted from Base44 (not in local files) |
|
| 123 |
+
| Failed | Authorization timed out, failed, or was skipped |
|
| 124 |
+
|
| 125 |
+
## Troubleshooting
|
| 126 |
+
|
| 127 |
+
| Problem | Solution |
|
| 128 |
+
|---------|----------|
|
| 129 |
+
| Authorization timed out | Re-run `npx base44 connectors push` and complete OAuth faster |
|
| 130 |
+
| Authorization failed | Check that you approved all requested permissions |
|
| 131 |
+
| Wrong account connected | Remove the connector file, push to delete it, then add it back and authorize with the correct account |
|
| 132 |
+
| Browser didn't open | Copy the URL shown in the terminal and open it manually |
|
| 133 |
+
|
| 134 |
+
## Related Commands
|
| 135 |
+
|
| 136 |
+
- [connectors-create.md](connectors-create.md) - How to create connector configuration files
|
| 137 |
+
- [connectors-pull.md](connectors-pull.md) - Pull connectors from Base44 to local files
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/exec.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# base44 exec
|
| 2 |
+
|
| 3 |
+
Run a script with the Base44 SDK pre-authenticated as the current user. Reads the script from stdin.
|
| 4 |
+
|
| 5 |
+
## Syntax
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
cat ./script.ts | npx base44 exec
|
| 9 |
+
echo "<code>" | npx base44 exec
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
## How It Works
|
| 13 |
+
|
| 14 |
+
The `exec` command reads a script from stdin and runs it server-side with the Base44 SDK pre-authenticated as the currently logged-in user. This allows you to run one-off scripts against your app's data without writing a full function.
|
| 15 |
+
|
| 16 |
+
## Available Globals
|
| 17 |
+
|
| 18 |
+
> **`base44`** — a preinitialized SDK client, available as a global variable in every exec script. You do not need to import or configure it — it is ready to use immediately.
|
| 19 |
+
|
| 20 |
+
Use it to interact with your app's resources:
|
| 21 |
+
|
| 22 |
+
- `base44.entities.<EntityName>` — CRUD operations on entities (`.list()`, `.get(id)`, `.create(data)`, `.update(id, data)`, `.delete(id)`)
|
| 23 |
+
- `base44.functions.invoke(name, data?)` — call a backend function
|
| 24 |
+
- `base44.agents.<AgentName>` — invoke AI agents
|
| 25 |
+
- For more available resources and methods, see the [Base44 SDK reference](../../base44-sdk/SKILL.md)
|
| 26 |
+
|
| 27 |
+
## Examples
|
| 28 |
+
|
| 29 |
+
```bash
|
| 30 |
+
# Run a script file
|
| 31 |
+
cat ./script.ts | npx base44 exec
|
| 32 |
+
|
| 33 |
+
# Inline script
|
| 34 |
+
echo "const users = await base44.entities.User.list(); console.log(users)" | npx base44 exec
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
## Requirements
|
| 38 |
+
|
| 39 |
+
- Must be authenticated (`npx base44 login`)
|
| 40 |
+
- Must be run from a linked Base44 project directory
|
| 41 |
+
- Script must be piped via stdin (non-interactive mode)
|
| 42 |
+
|
| 43 |
+
## Notes
|
| 44 |
+
|
| 45 |
+
- The script runs with the Base44 SDK pre-authenticated — you can use `base44.entities`, `base44.functions`, etc. directly
|
| 46 |
+
- Exit code from the script is forwarded as the CLI process exit code
|
| 47 |
+
- This command requires stdin to be piped (it does not accept input in interactive TTY mode)
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/functions-pull.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# base44 functions pull
|
| 2 |
+
|
| 3 |
+
Pull deployed functions from Base44 to local files.
|
| 4 |
+
|
| 5 |
+
## Syntax
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
npx base44 functions pull [name]
|
| 9 |
+
```
|
| 10 |
+
|
| 11 |
+
## Arguments
|
| 12 |
+
|
| 13 |
+
| Argument | Description | Required |
|
| 14 |
+
|----------|-------------|----------|
|
| 15 |
+
| `[name]` | Function name to pull (pulls all if omitted) | No |
|
| 16 |
+
|
| 17 |
+
## Authentication
|
| 18 |
+
|
| 19 |
+
**Required**: Yes. If not authenticated, you'll be prompted to login first.
|
| 20 |
+
|
| 21 |
+
## What It Does
|
| 22 |
+
|
| 23 |
+
1. Fetches deployed functions from Base44
|
| 24 |
+
2. Filters to the specified function if `[name]` is provided
|
| 25 |
+
3. Writes function files to the local `functions/` directory (configured in `base44/config.jsonc`)
|
| 26 |
+
4. Reports each file as `written` (new/updated) or `unchanged`
|
| 27 |
+
|
| 28 |
+
## Examples
|
| 29 |
+
|
| 30 |
+
```bash
|
| 31 |
+
# Pull all deployed functions
|
| 32 |
+
npx base44 functions pull
|
| 33 |
+
|
| 34 |
+
# Pull a specific function
|
| 35 |
+
npx base44 functions pull process-order
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
## Output
|
| 39 |
+
|
| 40 |
+
```bash
|
| 41 |
+
$ npx base44 functions pull
|
| 42 |
+
✓ Functions fetched successfully
|
| 43 |
+
✓ Function files written successfully
|
| 44 |
+
✓ process-order written
|
| 45 |
+
◆ send-notification unchanged
|
| 46 |
+
|
| 47 |
+
✓ Pulled 2 functions to base44/functions
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
Single function:
|
| 51 |
+
```bash
|
| 52 |
+
$ npx base44 functions pull process-order
|
| 53 |
+
✓ Functions fetched successfully
|
| 54 |
+
✓ Function files written successfully
|
| 55 |
+
✓ process-order written
|
| 56 |
+
|
| 57 |
+
✓ Pulled 1 function to base44/functions
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
## Error Handling
|
| 61 |
+
|
| 62 |
+
If the specified function is not found on remote:
|
| 63 |
+
```bash
|
| 64 |
+
$ npx base44 functions pull nonexistent
|
| 65 |
+
✓ Function "nonexistent" not found on remote
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
If no functions exist on remote:
|
| 69 |
+
```bash
|
| 70 |
+
$ npx base44 functions pull
|
| 71 |
+
✓ No functions found on remote
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
## Notes
|
| 75 |
+
|
| 76 |
+
- Files are written to the `functionsDir` configured in `base44/config.jsonc` (defaults to `functions/`)
|
| 77 |
+
- Files already matching remote content are skipped (reported as `unchanged`)
|
| 78 |
+
- This overwrites existing local function files with remote versions — commit local changes first
|
| 79 |
+
- Use `npx base44 functions deploy` to push local changes back to Base44
|
| 80 |
+
- Use `npx base44 functions list` to see what functions are deployed on remote
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-cli/references/secrets-list.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# base44 secrets list
|
| 2 |
+
|
| 3 |
+
List the names of all secrets configured for the current project.
|
| 4 |
+
|
| 5 |
+
## Syntax
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
npx base44 secrets list
|
| 9 |
+
```
|
| 10 |
+
|
| 11 |
+
## Options
|
| 12 |
+
|
| 13 |
+
No options. The command takes no arguments or flags.
|
| 14 |
+
|
| 15 |
+
## Examples
|
| 16 |
+
|
| 17 |
+
```bash
|
| 18 |
+
npx base44 secrets list
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
## Notes
|
| 22 |
+
|
| 23 |
+
- Only secret **names** are listed (values are never displayed)
|
| 24 |
+
- Returns "No secrets configured." if there are none
|
| 25 |
+
- Requires authentication
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/agents/openai.yaml
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
interface:
|
| 2 |
+
display_name: "Base44 SDK"
|
| 3 |
+
short_description: "Build features with the Base44 JavaScript and TypeScript SDK"
|
| 4 |
+
default_prompt: "Use Base44 SDK guidance to implement this feature against entities, functions, auth, and integrations."
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/QUICK_REFERENCE.md
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Base44 SDK Quick Reference
|
| 2 |
+
|
| 3 |
+
Compact method signatures for all SDK modules. **Verify against this before writing code.**
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## Auth (`base44.auth.*`)
|
| 8 |
+
|
| 9 |
+
```
|
| 10 |
+
loginViaEmailPassword(email, password, turnstileToken?) → Promise<{access_token, user}>
|
| 11 |
+
loginWithProvider('google' | 'microsoft' | 'facebook', fromUrl?) → void
|
| 12 |
+
me() → Promise<User | null>
|
| 13 |
+
updateMe(data) → Promise<User>
|
| 14 |
+
isAuthenticated() → Promise<boolean>
|
| 15 |
+
logout(redirectUrl?) → void
|
| 16 |
+
redirectToLogin(nextUrl) → void # ⚠️ Avoid - prefer custom login UI
|
| 17 |
+
register({email, password, turnstile_token?, referral_code?}) → Promise<any>
|
| 18 |
+
verifyOtp({email, otpCode}) → Promise<any>
|
| 19 |
+
resendOtp(email) → Promise<any>
|
| 20 |
+
inviteUser(userEmail, role) → Promise<any>
|
| 21 |
+
resetPasswordRequest(email) → Promise<any>
|
| 22 |
+
resetPassword({resetToken, newPassword}) → Promise<any>
|
| 23 |
+
changePassword({userId, currentPassword, newPassword}) → Promise<any>
|
| 24 |
+
setToken(token, saveToStorage?) → void
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
---
|
| 28 |
+
|
| 29 |
+
## Entities (`base44.entities.EntityName.*`)
|
| 30 |
+
|
| 31 |
+
```
|
| 32 |
+
create(data) → Promise<T>
|
| 33 |
+
bulkCreate(dataArray) → Promise<T[]>
|
| 34 |
+
list(sort?, limit?, skip?, fields?) → Promise<Pick<T, K>[]>
|
| 35 |
+
filter(query, sort?, limit?, skip?, fields?) → Promise<Pick<T, K>[]>
|
| 36 |
+
get(id) → Promise<T>
|
| 37 |
+
update(id, data) → Promise<T>
|
| 38 |
+
updateMany(query, mongoUpdateOp) → Promise<UpdateManyResult> // e.g. { $set: { field: val } }
|
| 39 |
+
bulkUpdate(dataArray) → Promise<T[]> // each item must have id
|
| 40 |
+
delete(id) → Promise<DeleteResult>
|
| 41 |
+
deleteMany(query) → Promise<DeleteManyResult>
|
| 42 |
+
importEntities(file) → Promise<ImportResult<T>> // frontend only
|
| 43 |
+
subscribe(callback) → () => void // returns unsubscribe fn
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
**Sort:** Use `SortField<T>`: `-fieldName` for descending (e.g., `-created_date`). Max 5,000 per request for list/filter.
|
| 47 |
+
|
| 48 |
+
---
|
| 49 |
+
|
| 50 |
+
## Functions (`base44.functions.*`)
|
| 51 |
+
|
| 52 |
+
```
|
| 53 |
+
invoke(functionName, data?) → Promise<any>
|
| 54 |
+
fetch(path, init?) → Promise<Response> // low-level, for streaming/custom methods
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
**Backend:** Use `base44.asServiceRole.functions.invoke()` for admin access.
|
| 58 |
+
|
| 59 |
+
---
|
| 60 |
+
|
| 61 |
+
## Integrations (`base44.integrations.Core.*`)
|
| 62 |
+
|
| 63 |
+
```
|
| 64 |
+
InvokeLLM({prompt, add_context_from_internet?, response_json_schema?, file_urls?}) → Promise<string | object>
|
| 65 |
+
GenerateImage({prompt}) → Promise<{url}>
|
| 66 |
+
SendEmail({to, subject, body, from_name?}) → Promise<any>
|
| 67 |
+
UploadFile({file}) → Promise<{file_url}>
|
| 68 |
+
UploadPrivateFile({file}) → Promise<{file_uri}>
|
| 69 |
+
CreateFileSignedUrl({file_uri, expires_in?}) → Promise<{signed_url}>
|
| 70 |
+
ExtractDataFromUploadedFile({file_url, json_schema}) → Promise<object>
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
### Custom Integrations (`base44.integrations.custom.*`)
|
| 74 |
+
|
| 75 |
+
```
|
| 76 |
+
call(slug, operationId, {payload?, pathParams?, queryParams?}?) → Promise<{success, status_code, data}>
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
**operationId format:** `"method:/path"` (e.g., `"get:/contacts"`, `"post:/users/{id}"`)
|
| 80 |
+
|
| 81 |
+
---
|
| 82 |
+
|
| 83 |
+
## Analytics (`base44.analytics.*`)
|
| 84 |
+
|
| 85 |
+
```
|
| 86 |
+
track({eventName, properties?}) → void
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
---
|
| 90 |
+
|
| 91 |
+
## App Logs (`base44.appLogs.*`)
|
| 92 |
+
|
| 93 |
+
```
|
| 94 |
+
logUserInApp(pageName) → Promise<void>
|
| 95 |
+
fetchLogs(params?) → Promise<any>
|
| 96 |
+
getStats(params?) → Promise<any>
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
---
|
| 100 |
+
|
| 101 |
+
## Users (`base44.users.*`)
|
| 102 |
+
|
| 103 |
+
```
|
| 104 |
+
inviteUser(userEmail, role) → Promise<any> // role: 'user' | 'admin'
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
---
|
| 108 |
+
|
| 109 |
+
## Service Role Connectors (`base44.asServiceRole.connectors.*`)
|
| 110 |
+
|
| 111 |
+
**Backend only, service role required.** App-scoped (shared account).
|
| 112 |
+
|
| 113 |
+
```
|
| 114 |
+
getConnection(integrationType) → Promise<{accessToken, connectionConfig}> // recommended
|
| 115 |
+
getAccessToken(integrationType) → Promise<string> // deprecated
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
**Types:** Run `npx base44 connectors list-available` to see all available integration types.
|
| 119 |
+
|
| 120 |
+
---
|
| 121 |
+
|
| 122 |
+
## SSO (`base44.asServiceRole.sso.*`)
|
| 123 |
+
|
| 124 |
+
**Backend only, service role required.**
|
| 125 |
+
|
| 126 |
+
```
|
| 127 |
+
getAccessToken(userId) → Promise<{access_token}>
|
| 128 |
+
```
|
| 129 |
+
|
| 130 |
+
---
|
| 131 |
+
|
| 132 |
+
## Service Role Access
|
| 133 |
+
|
| 134 |
+
**Backend functions only.** Prefix any module with `asServiceRole` for admin access:
|
| 135 |
+
|
| 136 |
+
```javascript
|
| 137 |
+
base44.asServiceRole.entities.Task.list()
|
| 138 |
+
base44.asServiceRole.functions.invoke('name', data)
|
| 139 |
+
base44.asServiceRole.connectors.getConnection('slack')
|
| 140 |
+
base44.asServiceRole.sso.getAccessToken(userId)
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
---
|
| 144 |
+
|
| 145 |
+
## Backend Function Template
|
| 146 |
+
|
| 147 |
+
```javascript
|
| 148 |
+
import { createClientFromRequest } from "@base44/sdk";
|
| 149 |
+
|
| 150 |
+
Deno.serve(async (req) => {
|
| 151 |
+
const base44 = createClientFromRequest(req);
|
| 152 |
+
const data = await req.json();
|
| 153 |
+
|
| 154 |
+
// User context
|
| 155 |
+
const user = await base44.auth.me();
|
| 156 |
+
|
| 157 |
+
// Service role for admin operations
|
| 158 |
+
const allRecords = await base44.asServiceRole.entities.Task.list();
|
| 159 |
+
|
| 160 |
+
return Response.json({ success: true });
|
| 161 |
+
});
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
---
|
| 165 |
+
|
| 166 |
+
## Client Initialization (External Apps)
|
| 167 |
+
|
| 168 |
+
```javascript
|
| 169 |
+
import { createClient } from "@base44/sdk";
|
| 170 |
+
|
| 171 |
+
const base44 = createClient({ appId: "your-app-id" }); // MUST use 'appId'
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
---
|
| 175 |
+
|
| 176 |
+
## TypeScript type registries
|
| 177 |
+
|
| 178 |
+
For typed entities, function names, and agent names (autocomplete and type checking), the Base44 CLI generates types and wires them into your project. Use the **base44-cli** skill for how to generate types.
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/analytics.md
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Analytics Module
|
| 2 |
+
|
| 3 |
+
Track custom events and user activity via `base44.analytics`.
|
| 4 |
+
|
| 5 |
+
## Contents
|
| 6 |
+
- [Methods](#methods)
|
| 7 |
+
- [Examples](#examples)
|
| 8 |
+
- [Automatic Tracking](#automatic-tracking)
|
| 9 |
+
- [Best Practices](#best-practices)
|
| 10 |
+
|
| 11 |
+
## Methods
|
| 12 |
+
|
| 13 |
+
| Method | Signature | Description |
|
| 14 |
+
|--------|-----------|-------------|
|
| 15 |
+
| `track(params)` | `void` | Track a custom event |
|
| 16 |
+
|
| 17 |
+
## Examples
|
| 18 |
+
|
| 19 |
+
### Track Custom Event
|
| 20 |
+
|
| 21 |
+
```javascript
|
| 22 |
+
// Track a simple event
|
| 23 |
+
base44.analytics.track({
|
| 24 |
+
eventName: "button_clicked"
|
| 25 |
+
});
|
| 26 |
+
|
| 27 |
+
// Track event with properties
|
| 28 |
+
base44.analytics.track({
|
| 29 |
+
eventName: "purchase_completed",
|
| 30 |
+
properties: {
|
| 31 |
+
product_id: "prod-123",
|
| 32 |
+
amount: 99.99,
|
| 33 |
+
currency: "USD"
|
| 34 |
+
}
|
| 35 |
+
});
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
### Track User Actions
|
| 39 |
+
|
| 40 |
+
```javascript
|
| 41 |
+
// Track page view
|
| 42 |
+
base44.analytics.track({
|
| 43 |
+
eventName: "page_view",
|
| 44 |
+
properties: {
|
| 45 |
+
page: "/dashboard",
|
| 46 |
+
referrer: document.referrer
|
| 47 |
+
}
|
| 48 |
+
});
|
| 49 |
+
|
| 50 |
+
// Track feature usage
|
| 51 |
+
base44.analytics.track({
|
| 52 |
+
eventName: "feature_used",
|
| 53 |
+
properties: {
|
| 54 |
+
feature: "export_data",
|
| 55 |
+
format: "csv"
|
| 56 |
+
}
|
| 57 |
+
});
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
## Automatic Tracking
|
| 61 |
+
|
| 62 |
+
The analytics module automatically tracks:
|
| 63 |
+
- **Initialization events**: When the app loads
|
| 64 |
+
- **Heartbeat events**: Periodic activity signals
|
| 65 |
+
- **Session duration**: Time spent in the app
|
| 66 |
+
|
| 67 |
+
These internal events help measure user engagement without manual instrumentation.
|
| 68 |
+
|
| 69 |
+
## Best Practices
|
| 70 |
+
|
| 71 |
+
1. **Use descriptive event names**: `order_completed` instead of `click`
|
| 72 |
+
2. **Include relevant properties**: Add context that helps analyze the event
|
| 73 |
+
3. **Be consistent**: Use the same event names and property keys across your app
|
| 74 |
+
4. **Don't track sensitive data**: Avoid PII in event properties
|
| 75 |
+
|
| 76 |
+
```javascript
|
| 77 |
+
// Good: Descriptive with relevant properties
|
| 78 |
+
base44.analytics.track({
|
| 79 |
+
eventName: "subscription_started",
|
| 80 |
+
properties: {
|
| 81 |
+
plan: "pro",
|
| 82 |
+
billing_cycle: "annual"
|
| 83 |
+
}
|
| 84 |
+
});
|
| 85 |
+
|
| 86 |
+
// Avoid: Vague event name, no context
|
| 87 |
+
base44.analytics.track({
|
| 88 |
+
eventName: "click"
|
| 89 |
+
});
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
## Type Definitions
|
| 93 |
+
|
| 94 |
+
```typescript
|
| 95 |
+
/** Properties that can be attached to a tracked event. */
|
| 96 |
+
type TrackEventProperties = {
|
| 97 |
+
[key: string]: string | number | boolean | null | undefined;
|
| 98 |
+
};
|
| 99 |
+
|
| 100 |
+
/** Parameters for the track() method. */
|
| 101 |
+
interface TrackEventParams {
|
| 102 |
+
/** The name of the event to track. */
|
| 103 |
+
eventName: string;
|
| 104 |
+
/** Optional properties to attach to the event. */
|
| 105 |
+
properties?: TrackEventProperties;
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
/** The analytics module interface. */
|
| 109 |
+
interface AnalyticsModule {
|
| 110 |
+
/** Track a custom event with optional properties. */
|
| 111 |
+
track(params: TrackEventParams): void;
|
| 112 |
+
}
|
| 113 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/app-logs.md
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# App Logs Module
|
| 2 |
+
|
| 3 |
+
Log user activity in your app via `base44.appLogs`.
|
| 4 |
+
|
| 5 |
+
## Contents
|
| 6 |
+
- [Methods](#methods)
|
| 7 |
+
- [Examples](#examples)
|
| 8 |
+
- [Use Cases](#use-cases)
|
| 9 |
+
|
| 10 |
+
## Methods
|
| 11 |
+
|
| 12 |
+
| Method | Signature | Description |
|
| 13 |
+
|--------|-----------|-------------|
|
| 14 |
+
| `logUserInApp(pageName)` | `Promise<void>` | Log user activity on a page |
|
| 15 |
+
| `fetchLogs(params?)` | `Promise<any>` | Fetch app logs with optional filter parameters |
|
| 16 |
+
| `getStats(params?)` | `Promise<any>` | Get app usage statistics |
|
| 17 |
+
|
| 18 |
+
## Examples
|
| 19 |
+
|
| 20 |
+
### Log User Activity
|
| 21 |
+
|
| 22 |
+
```javascript
|
| 23 |
+
// Log when user visits a page
|
| 24 |
+
await base44.appLogs.logUserInApp("dashboard");
|
| 25 |
+
|
| 26 |
+
// Log specific page visits
|
| 27 |
+
await base44.appLogs.logUserInApp("settings");
|
| 28 |
+
await base44.appLogs.logUserInApp("profile");
|
| 29 |
+
|
| 30 |
+
// Log feature usage
|
| 31 |
+
await base44.appLogs.logUserInApp("export-button-click");
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
The page name doesn't have to be an actual page - it can be any string you want to track.
|
| 35 |
+
|
| 36 |
+
## Use Cases
|
| 37 |
+
|
| 38 |
+
### Track Page Views in React
|
| 39 |
+
|
| 40 |
+
```javascript
|
| 41 |
+
// Log page views on route change
|
| 42 |
+
useEffect(() => {
|
| 43 |
+
base44.appLogs.logUserInApp(window.location.pathname);
|
| 44 |
+
}, [location.pathname]);
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
### Track Feature Usage
|
| 48 |
+
|
| 49 |
+
```javascript
|
| 50 |
+
// Log when user uses specific features
|
| 51 |
+
function handleExport() {
|
| 52 |
+
base44.appLogs.logUserInApp("export-data");
|
| 53 |
+
// ... export logic
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
function handleSettingsChange() {
|
| 57 |
+
base44.appLogs.logUserInApp("settings-updated");
|
| 58 |
+
// ... save settings
|
| 59 |
+
}
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
### Fetch Logs
|
| 63 |
+
|
| 64 |
+
```javascript
|
| 65 |
+
// Fetch all logs
|
| 66 |
+
const logs = await base44.appLogs.fetchLogs();
|
| 67 |
+
|
| 68 |
+
// Fetch logs with filters
|
| 69 |
+
const recentLogs = await base44.appLogs.fetchLogs({
|
| 70 |
+
limit: 50,
|
| 71 |
+
page: "/dashboard"
|
| 72 |
+
});
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
### Get Stats
|
| 76 |
+
|
| 77 |
+
```javascript
|
| 78 |
+
// Get usage statistics for the app
|
| 79 |
+
const stats = await base44.appLogs.getStats();
|
| 80 |
+
|
| 81 |
+
// Get stats with date range params
|
| 82 |
+
const weekStats = await base44.appLogs.getStats({
|
| 83 |
+
from: "2024-01-01",
|
| 84 |
+
to: "2024-01-07"
|
| 85 |
+
});
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
## Notes
|
| 89 |
+
|
| 90 |
+
- Logs appear in the Analytics page of your app dashboard
|
| 91 |
+
- App logs track page-level and feature-level activity
|
| 92 |
+
- Use `analytics.track()` for custom events with properties, `appLogs.logUserInApp()` for simple page/feature tracking
|
| 93 |
+
|
| 94 |
+
## Type Definitions
|
| 95 |
+
|
| 96 |
+
```typescript
|
| 97 |
+
/** App Logs module for tracking and analyzing app usage. */
|
| 98 |
+
interface AppLogsModule {
|
| 99 |
+
/**
|
| 100 |
+
* Log user activity in the app.
|
| 101 |
+
* @param pageName - Name of the page or section being visited.
|
| 102 |
+
* @returns Promise that resolves when the log is recorded.
|
| 103 |
+
*/
|
| 104 |
+
logUserInApp(pageName: string): Promise<void>;
|
| 105 |
+
|
| 106 |
+
/**
|
| 107 |
+
* Fetch app logs with optional filter parameters.
|
| 108 |
+
* @param params - Optional filter parameters (e.g., limit, page name, date range).
|
| 109 |
+
* @returns Promise resolving to the logs data.
|
| 110 |
+
*/
|
| 111 |
+
fetchLogs(params?: Record<string, any>): Promise<any>;
|
| 112 |
+
|
| 113 |
+
/**
|
| 114 |
+
* Get app usage statistics.
|
| 115 |
+
* @param params - Optional filter parameters (e.g., date range).
|
| 116 |
+
* @returns Promise resolving to the statistics data.
|
| 117 |
+
*/
|
| 118 |
+
getStats(params?: Record<string, any>): Promise<any>;
|
| 119 |
+
}
|
| 120 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/auth.md
ADDED
|
@@ -0,0 +1,770 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Auth Module
|
| 2 |
+
|
| 3 |
+
User authentication, registration, and session management via `base44.auth`.
|
| 4 |
+
|
| 5 |
+
## Contents
|
| 6 |
+
- [TypeScript Types](#typescript-types)
|
| 7 |
+
- [Methods](#methods)
|
| 8 |
+
- [Examples](#examples)
|
| 9 |
+
- [Error Handling](#error-handling)
|
| 10 |
+
- [Auth Providers](#auth-providers)
|
| 11 |
+
- [Environment Availability](#environment-availability)
|
| 12 |
+
- [App Visibility](#app-visibility)
|
| 13 |
+
- [Limitations](#limitations)
|
| 14 |
+
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
## TypeScript Types
|
| 18 |
+
|
| 19 |
+
### User Interface
|
| 20 |
+
```typescript
|
| 21 |
+
interface User {
|
| 22 |
+
id: string;
|
| 23 |
+
created_date: string;
|
| 24 |
+
updated_date: string;
|
| 25 |
+
email: string;
|
| 26 |
+
full_name: string | null;
|
| 27 |
+
disabled: boolean | null;
|
| 28 |
+
is_verified: boolean;
|
| 29 |
+
app_id: string;
|
| 30 |
+
is_service: boolean;
|
| 31 |
+
role: string;
|
| 32 |
+
[key: string]: any; // Custom schema fields
|
| 33 |
+
}
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
### LoginResponse Interface
|
| 37 |
+
```typescript
|
| 38 |
+
interface LoginResponse {
|
| 39 |
+
access_token: string; // JWT token
|
| 40 |
+
user: User; // Complete user object
|
| 41 |
+
}
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
### Parameter Interfaces
|
| 45 |
+
|
| 46 |
+
#### RegisterParams
|
| 47 |
+
```typescript
|
| 48 |
+
interface RegisterParams {
|
| 49 |
+
email: string; // Required
|
| 50 |
+
password: string; // Required
|
| 51 |
+
turnstile_token?: string | null; // Optional: Cloudflare Turnstile for bot protection
|
| 52 |
+
referral_code?: string | null; // Optional: Referral code
|
| 53 |
+
}
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
#### VerifyOtpParams
|
| 57 |
+
```typescript
|
| 58 |
+
interface VerifyOtpParams {
|
| 59 |
+
email: string; // User's email
|
| 60 |
+
otpCode: string; // OTP code from email
|
| 61 |
+
}
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
#### ResetPasswordParams
|
| 65 |
+
```typescript
|
| 66 |
+
interface ResetPasswordParams {
|
| 67 |
+
resetToken: string; // Token from password reset email
|
| 68 |
+
newPassword: string; // New password to set
|
| 69 |
+
}
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
#### ChangePasswordParams
|
| 73 |
+
```typescript
|
| 74 |
+
interface ChangePasswordParams {
|
| 75 |
+
userId: string; // User ID
|
| 76 |
+
currentPassword: string; // Current password for verification
|
| 77 |
+
newPassword: string; // New password to set
|
| 78 |
+
}
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
### Provider Type
|
| 82 |
+
```typescript
|
| 83 |
+
type Provider = 'google' | 'microsoft' | 'facebook';
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
---
|
| 87 |
+
|
| 88 |
+
## Methods
|
| 89 |
+
|
| 90 |
+
### Module Interface
|
| 91 |
+
```typescript
|
| 92 |
+
interface AuthModule {
|
| 93 |
+
// User Info
|
| 94 |
+
me(): Promise<User>;
|
| 95 |
+
updateMe(data: Partial<Omit<User, 'id' | 'created_date' | 'updated_date' | 'app_id' | 'is_service'>>): Promise<User>;
|
| 96 |
+
isAuthenticated(): Promise<boolean>;
|
| 97 |
+
|
| 98 |
+
// Login/Logout
|
| 99 |
+
loginViaEmailPassword(email: string, password: string, turnstileToken?: string): Promise<LoginResponse>;
|
| 100 |
+
loginWithProvider(provider: Provider, fromUrl?: string): void;
|
| 101 |
+
logout(redirectUrl?: string): void;
|
| 102 |
+
redirectToLogin(nextUrl: string): void;
|
| 103 |
+
|
| 104 |
+
// Token Management
|
| 105 |
+
setToken(token: string, saveToStorage?: boolean): void;
|
| 106 |
+
|
| 107 |
+
// Registration
|
| 108 |
+
register(params: RegisterParams): Promise<any>;
|
| 109 |
+
verifyOtp(params: VerifyOtpParams): Promise<any>;
|
| 110 |
+
resendOtp(email: string): Promise<any>;
|
| 111 |
+
|
| 112 |
+
// User Management
|
| 113 |
+
inviteUser(userEmail: string, role: string): Promise<any>;
|
| 114 |
+
|
| 115 |
+
// Password Management
|
| 116 |
+
resetPasswordRequest(email: string): Promise<any>;
|
| 117 |
+
resetPassword(params: ResetPasswordParams): Promise<any>;
|
| 118 |
+
changePassword(params: ChangePasswordParams): Promise<any>;
|
| 119 |
+
}
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
### Method Reference Table
|
| 123 |
+
|
| 124 |
+
| Method | Parameters | Return Type | Description |
|
| 125 |
+
|--------|-----------|-------------|-------------|
|
| 126 |
+
| `register()` | `params: RegisterParams` | `Promise<any>` | Create new user account |
|
| 127 |
+
| `loginViaEmailPassword()` | `email: string, password: string, turnstileToken?: string` | `Promise<LoginResponse>` | Authenticate with email/password |
|
| 128 |
+
| `loginWithProvider()` | `provider: Provider, fromUrl?: string` | `void` | Initiate OAuth login flow. Providers: `'google'` (default), `'microsoft'`, `'facebook'` (enable in app settings) |
|
| 129 |
+
| `me()` | None | `Promise<User>` | Get current authenticated user |
|
| 130 |
+
| `updateMe()` | `data: Partial<User>` | `Promise<User>` | Update current user's profile |
|
| 131 |
+
| `logout()` | `redirectUrl?: string` | `void` | Redirect to server-side logout (clears HTTP-only cookies and session), then to redirectUrl or current URL |
|
| 132 |
+
| `redirectToLogin()` | `nextUrl: string` | `void` | ⚠️ **Avoid** - Prefer custom login UI with `loginViaEmailPassword()` or `loginWithProvider()` |
|
| 133 |
+
| `isAuthenticated()` | None | `Promise<boolean>` | Check if user is logged in |
|
| 134 |
+
| `setToken()` | `token: string, saveToStorage?: boolean` | `void` | Manually set auth token |
|
| 135 |
+
| `inviteUser()` | `userEmail: string, role: string` | `Promise<any>` | Send invitation email |
|
| 136 |
+
| `verifyOtp()` | `params: VerifyOtpParams` | `Promise<any>` | Verify OTP code |
|
| 137 |
+
| `resendOtp()` | `email: string` | `Promise<any>` | Resend OTP code |
|
| 138 |
+
| `resetPasswordRequest()` | `email: string` | `Promise<any>` | Request password reset |
|
| 139 |
+
| `resetPassword()` | `params: ResetPasswordParams` | `Promise<any>` | Reset password with token |
|
| 140 |
+
| `changePassword()` | `params: ChangePasswordParams` | `Promise<any>` | Change user password |
|
| 141 |
+
|
| 142 |
+
---
|
| 143 |
+
|
| 144 |
+
## Examples
|
| 145 |
+
|
| 146 |
+
### Register New User (Complete Flow)
|
| 147 |
+
|
| 148 |
+
Registration requires email verification before login. Complete flow:
|
| 149 |
+
|
| 150 |
+
1. **Register** - Create the user account
|
| 151 |
+
2. **Verification email sent** - User receives an OTP code
|
| 152 |
+
3. **Verify OTP** - User enters code to verify email
|
| 153 |
+
4. **Login** - User can now log in
|
| 154 |
+
|
| 155 |
+
```javascript
|
| 156 |
+
try {
|
| 157 |
+
// Step 1: Register the user
|
| 158 |
+
await base44.auth.register({
|
| 159 |
+
email: "user@example.com",
|
| 160 |
+
password: "securePassword123",
|
| 161 |
+
referral_code: "OPTIONAL_CODE", // optional
|
| 162 |
+
turnstile_token: "CAPTCHA_TOKEN" // optional, for bot protection
|
| 163 |
+
});
|
| 164 |
+
console.log('Registration successful. Check email for OTP code.');
|
| 165 |
+
|
| 166 |
+
// Step 2: User receives email with OTP code (e.g., "123456")
|
| 167 |
+
|
| 168 |
+
// Step 3: Verify the OTP code
|
| 169 |
+
await base44.auth.verifyOtp({
|
| 170 |
+
email: "user@example.com",
|
| 171 |
+
otpCode: "123456" // code from verification email
|
| 172 |
+
});
|
| 173 |
+
console.log('Email verified successfully.');
|
| 174 |
+
|
| 175 |
+
// Step 4: Now the user can log in
|
| 176 |
+
const loginResponse = await base44.auth.loginViaEmailPassword(
|
| 177 |
+
"user@example.com",
|
| 178 |
+
"securePassword123"
|
| 179 |
+
);
|
| 180 |
+
console.log('Login successful:', loginResponse.user);
|
| 181 |
+
|
| 182 |
+
} catch (error) {
|
| 183 |
+
console.error('Registration flow failed:', error.message);
|
| 184 |
+
// Handle specific errors (see Error Handling section)
|
| 185 |
+
}
|
| 186 |
+
```
|
| 187 |
+
|
| 188 |
+
> **Important**: Users cannot log in until they complete OTP verification. Attempting to call `loginViaEmailPassword` before verification will fail.
|
| 189 |
+
|
| 190 |
+
### Login with Email/Password
|
| 191 |
+
|
| 192 |
+
```javascript
|
| 193 |
+
try {
|
| 194 |
+
const response = await base44.auth.loginViaEmailPassword(
|
| 195 |
+
"user@example.com",
|
| 196 |
+
"password123",
|
| 197 |
+
turnstileToken // optional: for bot protection
|
| 198 |
+
);
|
| 199 |
+
|
| 200 |
+
console.log('Login successful');
|
| 201 |
+
console.log('User:', response.user);
|
| 202 |
+
console.log('Token:', response.access_token);
|
| 203 |
+
|
| 204 |
+
// JWT is automatically stored for subsequent requests
|
| 205 |
+
|
| 206 |
+
} catch (error) {
|
| 207 |
+
console.error('Login failed:', error.message);
|
| 208 |
+
if (error.status === 401) {
|
| 209 |
+
console.error('Invalid credentials');
|
| 210 |
+
} else if (error.status === 403) {
|
| 211 |
+
console.error('Email not verified. Please check your email for OTP.');
|
| 212 |
+
}
|
| 213 |
+
}
|
| 214 |
+
```
|
| 215 |
+
|
| 216 |
+
### Login with OAuth Provider
|
| 217 |
+
|
| 218 |
+
Supported providers: `'google'` (enabled by default), `'microsoft'`, and `'facebook'`. Enable Microsoft or Facebook in your app's authentication settings before using them.
|
| 219 |
+
|
| 220 |
+
```javascript
|
| 221 |
+
// Redirect to Google OAuth
|
| 222 |
+
base44.auth.loginWithProvider('google');
|
| 223 |
+
|
| 224 |
+
// Redirect to Google OAuth and return to current page after
|
| 225 |
+
base44.auth.loginWithProvider('google', window.location.href);
|
| 226 |
+
|
| 227 |
+
// Microsoft or Facebook (enable in app settings first)
|
| 228 |
+
base44.auth.loginWithProvider('microsoft');
|
| 229 |
+
base44.auth.loginWithProvider('facebook', '/dashboard');
|
| 230 |
+
```
|
| 231 |
+
|
| 232 |
+
### Get Current User
|
| 233 |
+
|
| 234 |
+
```javascript
|
| 235 |
+
try {
|
| 236 |
+
const user = await base44.auth.me();
|
| 237 |
+
|
| 238 |
+
if (user) {
|
| 239 |
+
console.log('User ID:', user.id);
|
| 240 |
+
console.log('Email:', user.email);
|
| 241 |
+
console.log('Name:', user.full_name);
|
| 242 |
+
console.log('Role:', user.role);
|
| 243 |
+
console.log('Verified:', user.is_verified);
|
| 244 |
+
} else {
|
| 245 |
+
console.log('User not authenticated');
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
} catch (error) {
|
| 249 |
+
console.error('Failed to fetch user:', error.message);
|
| 250 |
+
if (error.status === 401) {
|
| 251 |
+
// Token expired or invalid - navigate to your custom login page
|
| 252 |
+
navigate('/login');
|
| 253 |
+
}
|
| 254 |
+
}
|
| 255 |
+
```
|
| 256 |
+
|
| 257 |
+
### Update User Profile
|
| 258 |
+
|
| 259 |
+
```javascript
|
| 260 |
+
try {
|
| 261 |
+
const updatedUser = await base44.auth.updateMe({
|
| 262 |
+
full_name: "John Doe",
|
| 263 |
+
// Custom schema fields can be updated here
|
| 264 |
+
phone: "+1234567890",
|
| 265 |
+
preferences: { theme: "dark" }
|
| 266 |
+
});
|
| 267 |
+
|
| 268 |
+
console.log('Profile updated:', updatedUser);
|
| 269 |
+
|
| 270 |
+
} catch (error) {
|
| 271 |
+
console.error('Profile update failed:', error.message);
|
| 272 |
+
if (error.status === 400) {
|
| 273 |
+
console.error('Invalid data provided');
|
| 274 |
+
} else if (error.status === 401) {
|
| 275 |
+
console.error('Authentication required');
|
| 276 |
+
navigate('/login');
|
| 277 |
+
}
|
| 278 |
+
}
|
| 279 |
+
```
|
| 280 |
+
|
| 281 |
+
### Check Authentication Status
|
| 282 |
+
|
| 283 |
+
```javascript
|
| 284 |
+
try {
|
| 285 |
+
const isLoggedIn = await base44.auth.isAuthenticated();
|
| 286 |
+
|
| 287 |
+
if (isLoggedIn) {
|
| 288 |
+
// Show authenticated UI
|
| 289 |
+
console.log('User is authenticated');
|
| 290 |
+
} else {
|
| 291 |
+
// Show login button
|
| 292 |
+
console.log('User is not authenticated');
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
} catch (error) {
|
| 296 |
+
console.error('Failed to check authentication:', error.message);
|
| 297 |
+
// On error, treat as not authenticated
|
| 298 |
+
}
|
| 299 |
+
```
|
| 300 |
+
|
| 301 |
+
### Logout
|
| 302 |
+
|
| 303 |
+
Logout redirects the user to the server-side logout endpoint (`/api/apps/auth/logout`) to clear HTTP-only cookies and the session, then redirects to the given URL (or the current page if omitted). Requires a browser environment.
|
| 304 |
+
|
| 305 |
+
```javascript
|
| 306 |
+
// Logout: clears session via server, then redirects to current page
|
| 307 |
+
base44.auth.logout();
|
| 308 |
+
|
| 309 |
+
// Logout and redirect to goodbye page after
|
| 310 |
+
base44.auth.logout("/goodbye");
|
| 311 |
+
|
| 312 |
+
// Logout and redirect to homepage
|
| 313 |
+
base44.auth.logout("/");
|
| 314 |
+
```
|
| 315 |
+
|
| 316 |
+
### Protected Route Pattern
|
| 317 |
+
|
| 318 |
+
```javascript
|
| 319 |
+
// Using a navigation function (e.g., React Router's useNavigate, Next.js router)
|
| 320 |
+
async function requireAuth(navigate) {
|
| 321 |
+
try {
|
| 322 |
+
const user = await base44.auth.me();
|
| 323 |
+
|
| 324 |
+
if (!user) {
|
| 325 |
+
// Navigate to your custom login page
|
| 326 |
+
navigate('/login', { state: { returnTo: window.location.pathname } });
|
| 327 |
+
return null;
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
return user;
|
| 331 |
+
|
| 332 |
+
} catch (error) {
|
| 333 |
+
console.error('Authentication check failed:', error.message);
|
| 334 |
+
navigate('/login', { state: { returnTo: window.location.pathname } });
|
| 335 |
+
return null;
|
| 336 |
+
}
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
// Usage in your app
|
| 340 |
+
async function loadProtectedPage(navigate) {
|
| 341 |
+
const user = await requireAuth(navigate);
|
| 342 |
+
if (!user) {
|
| 343 |
+
// Will navigate to login
|
| 344 |
+
return;
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
// Continue with authenticated logic
|
| 348 |
+
console.log('Welcome,', user.full_name);
|
| 349 |
+
}
|
| 350 |
+
```
|
| 351 |
+
|
| 352 |
+
### Set Authentication Token
|
| 353 |
+
|
| 354 |
+
```javascript
|
| 355 |
+
// SECURITY WARNING: Never hardcode tokens or expose them in client code
|
| 356 |
+
// Tokens should only be received from secure authentication flows
|
| 357 |
+
|
| 358 |
+
// Set token and save to localStorage (default)
|
| 359 |
+
base44.auth.setToken(receivedToken);
|
| 360 |
+
|
| 361 |
+
// Set token without saving to localStorage (temporary session)
|
| 362 |
+
base44.auth.setToken(receivedToken, false);
|
| 363 |
+
|
| 364 |
+
// Verify token was set
|
| 365 |
+
try {
|
| 366 |
+
const isAuthenticated = await base44.auth.isAuthenticated();
|
| 367 |
+
if (!isAuthenticated) {
|
| 368 |
+
console.error('Token validation failed');
|
| 369 |
+
}
|
| 370 |
+
} catch (error) {
|
| 371 |
+
console.error('Failed to set token:', error.message);
|
| 372 |
+
}
|
| 373 |
+
```
|
| 374 |
+
|
| 375 |
+
### Invite User to Application
|
| 376 |
+
|
| 377 |
+
```javascript
|
| 378 |
+
try {
|
| 379 |
+
// Note: Typically requires admin privileges
|
| 380 |
+
const response = await base44.auth.inviteUser(
|
| 381 |
+
"newuser@example.com",
|
| 382 |
+
"user" // or "admin"
|
| 383 |
+
);
|
| 384 |
+
|
| 385 |
+
console.log('Invitation sent successfully');
|
| 386 |
+
|
| 387 |
+
} catch (error) {
|
| 388 |
+
console.error('Failed to invite user:', error.message);
|
| 389 |
+
if (error.status === 403) {
|
| 390 |
+
console.error('Insufficient permissions to invite users');
|
| 391 |
+
} else if (error.status === 400) {
|
| 392 |
+
console.error('Invalid email or role');
|
| 393 |
+
}
|
| 394 |
+
}
|
| 395 |
+
```
|
| 396 |
+
|
| 397 |
+
### OTP Verification
|
| 398 |
+
|
| 399 |
+
```javascript
|
| 400 |
+
try {
|
| 401 |
+
// Verify OTP code sent to user's email
|
| 402 |
+
await base44.auth.verifyOtp({
|
| 403 |
+
email: "user@example.com",
|
| 404 |
+
otpCode: "123456"
|
| 405 |
+
});
|
| 406 |
+
|
| 407 |
+
console.log('OTP verified successfully');
|
| 408 |
+
|
| 409 |
+
} catch (error) {
|
| 410 |
+
console.error('OTP verification failed:', error.message);
|
| 411 |
+
if (error.status === 400) {
|
| 412 |
+
console.error('Invalid or expired OTP code');
|
| 413 |
+
} else if (error.status === 429) {
|
| 414 |
+
console.error('Too many attempts. Please try again later.');
|
| 415 |
+
}
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
// Resend OTP if needed
|
| 419 |
+
try {
|
| 420 |
+
await base44.auth.resendOtp("user@example.com");
|
| 421 |
+
console.log('OTP resent successfully');
|
| 422 |
+
|
| 423 |
+
} catch (error) {
|
| 424 |
+
console.error('Failed to resend OTP:', error.message);
|
| 425 |
+
if (error.status === 429) {
|
| 426 |
+
console.error('Too many requests. Please wait before trying again.');
|
| 427 |
+
}
|
| 428 |
+
}
|
| 429 |
+
```
|
| 430 |
+
|
| 431 |
+
### Password Reset Flow
|
| 432 |
+
|
| 433 |
+
```javascript
|
| 434 |
+
// Step 1: Request password reset
|
| 435 |
+
try {
|
| 436 |
+
await base44.auth.resetPasswordRequest("user@example.com");
|
| 437 |
+
console.log('Password reset email sent. Check your inbox.');
|
| 438 |
+
|
| 439 |
+
} catch (error) {
|
| 440 |
+
console.error('Password reset request failed:', error.message);
|
| 441 |
+
if (error.status === 429) {
|
| 442 |
+
console.error('Too many requests. Please try again later.');
|
| 443 |
+
}
|
| 444 |
+
// Note: For security, don't reveal if email exists
|
| 445 |
+
}
|
| 446 |
+
|
| 447 |
+
// Step 2: Reset password with token from email
|
| 448 |
+
try {
|
| 449 |
+
await base44.auth.resetPassword({
|
| 450 |
+
resetToken: "token-from-email",
|
| 451 |
+
newPassword: "newSecurePassword123"
|
| 452 |
+
});
|
| 453 |
+
|
| 454 |
+
console.log('Password reset successfully. You can now log in.');
|
| 455 |
+
|
| 456 |
+
} catch (error) {
|
| 457 |
+
console.error('Password reset failed:', error.message);
|
| 458 |
+
if (error.status === 400) {
|
| 459 |
+
console.error('Invalid or expired reset token');
|
| 460 |
+
} else if (error.status === 422) {
|
| 461 |
+
console.error('Password does not meet requirements');
|
| 462 |
+
}
|
| 463 |
+
}
|
| 464 |
+
```
|
| 465 |
+
|
| 466 |
+
### Change Password
|
| 467 |
+
|
| 468 |
+
```javascript
|
| 469 |
+
try {
|
| 470 |
+
const currentUser = await base44.auth.me();
|
| 471 |
+
|
| 472 |
+
if (!currentUser) {
|
| 473 |
+
throw new Error('User must be authenticated to change password');
|
| 474 |
+
}
|
| 475 |
+
|
| 476 |
+
await base44.auth.changePassword({
|
| 477 |
+
userId: currentUser.id,
|
| 478 |
+
currentPassword: "oldPassword123",
|
| 479 |
+
newPassword: "newSecurePassword456"
|
| 480 |
+
});
|
| 481 |
+
|
| 482 |
+
console.log('Password changed successfully');
|
| 483 |
+
|
| 484 |
+
} catch (error) {
|
| 485 |
+
console.error('Password change failed:', error.message);
|
| 486 |
+
if (error.status === 401) {
|
| 487 |
+
console.error('Current password is incorrect');
|
| 488 |
+
} else if (error.status === 422) {
|
| 489 |
+
console.error('New password does not meet requirements');
|
| 490 |
+
} else if (error.status === 403) {
|
| 491 |
+
console.error('Not authorized to change this password');
|
| 492 |
+
}
|
| 493 |
+
}
|
| 494 |
+
```
|
| 495 |
+
|
| 496 |
+
---
|
| 497 |
+
|
| 498 |
+
## Error Handling
|
| 499 |
+
|
| 500 |
+
### Common Error Scenarios
|
| 501 |
+
|
| 502 |
+
The auth module can throw various errors. Here are common scenarios and how to handle them:
|
| 503 |
+
|
| 504 |
+
#### Authentication Errors (401/403)
|
| 505 |
+
```javascript
|
| 506 |
+
try {
|
| 507 |
+
const user = await base44.auth.me();
|
| 508 |
+
} catch (error) {
|
| 509 |
+
if (error.status === 401) {
|
| 510 |
+
// Token expired or invalid - navigate to your custom login page
|
| 511 |
+
navigate('/login');
|
| 512 |
+
} else if (error.status === 403) {
|
| 513 |
+
// Email not verified or insufficient permissions
|
| 514 |
+
console.error('Access denied:', error.message);
|
| 515 |
+
}
|
| 516 |
+
}
|
| 517 |
+
```
|
| 518 |
+
|
| 519 |
+
#### Validation Errors (400/422)
|
| 520 |
+
```javascript
|
| 521 |
+
try {
|
| 522 |
+
await base44.auth.register({
|
| 523 |
+
email: "invalid-email",
|
| 524 |
+
password: "weak"
|
| 525 |
+
});
|
| 526 |
+
} catch (error) {
|
| 527 |
+
if (error.status === 400) {
|
| 528 |
+
console.error('Invalid input:', error.message);
|
| 529 |
+
// Handle validation errors
|
| 530 |
+
} else if (error.status === 422) {
|
| 531 |
+
console.error('Data validation failed:', error.details);
|
| 532 |
+
}
|
| 533 |
+
}
|
| 534 |
+
```
|
| 535 |
+
|
| 536 |
+
#### Rate Limiting (429)
|
| 537 |
+
```javascript
|
| 538 |
+
try {
|
| 539 |
+
await base44.auth.resendOtp("user@example.com");
|
| 540 |
+
} catch (error) {
|
| 541 |
+
if (error.status === 429) {
|
| 542 |
+
console.error('Too many requests. Please wait before trying again.');
|
| 543 |
+
// Show countdown or disable button temporarily
|
| 544 |
+
}
|
| 545 |
+
}
|
| 546 |
+
```
|
| 547 |
+
|
| 548 |
+
#### Generic Error Handler
|
| 549 |
+
```javascript
|
| 550 |
+
function handleAuthError(error) {
|
| 551 |
+
switch (error.status) {
|
| 552 |
+
case 400:
|
| 553 |
+
return 'Invalid input. Please check your data.';
|
| 554 |
+
case 401:
|
| 555 |
+
return 'Authentication required. Redirecting to login...';
|
| 556 |
+
case 403:
|
| 557 |
+
return 'Access denied. You may need to verify your email.';
|
| 558 |
+
case 404:
|
| 559 |
+
return 'Resource not found.';
|
| 560 |
+
case 422:
|
| 561 |
+
return 'Validation failed. Please check your input.';
|
| 562 |
+
case 429:
|
| 563 |
+
return 'Too many requests. Please try again later.';
|
| 564 |
+
case 500:
|
| 565 |
+
return 'Server error. Please try again.';
|
| 566 |
+
default:
|
| 567 |
+
return 'An unexpected error occurred.';
|
| 568 |
+
}
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
// Usage
|
| 572 |
+
try {
|
| 573 |
+
await base44.auth.loginViaEmailPassword(email, password);
|
| 574 |
+
} catch (error) {
|
| 575 |
+
console.error(handleAuthError(error));
|
| 576 |
+
}
|
| 577 |
+
```
|
| 578 |
+
|
| 579 |
+
---
|
| 580 |
+
|
| 581 |
+
## Auth Providers
|
| 582 |
+
|
| 583 |
+
Configure authentication providers in your app dashboard:
|
| 584 |
+
|
| 585 |
+
### Available Providers
|
| 586 |
+
|
| 587 |
+
**Built-in (All Plans):**
|
| 588 |
+
- **Email/Password** - Default, always enabled
|
| 589 |
+
- **Google** - OAuth authentication
|
| 590 |
+
- **Microsoft** - OAuth authentication
|
| 591 |
+
- **Facebook** - OAuth authentication
|
| 592 |
+
|
| 593 |
+
**SSO Providers (Elite Plan):**
|
| 594 |
+
- **Okta**
|
| 595 |
+
- **Azure AD**
|
| 596 |
+
- **GitHub**
|
| 597 |
+
|
| 598 |
+
### Using OAuth Providers
|
| 599 |
+
|
| 600 |
+
- **Google** – enabled by default.
|
| 601 |
+
- **Microsoft** – enable in your app's authentication settings before use.
|
| 602 |
+
- **Facebook** – enable in your app's authentication settings before use.
|
| 603 |
+
|
| 604 |
+
```javascript
|
| 605 |
+
// Initiate OAuth login flow
|
| 606 |
+
base44.auth.loginWithProvider('google');
|
| 607 |
+
|
| 608 |
+
// Return to specific page after authentication
|
| 609 |
+
base44.auth.loginWithProvider('microsoft', '/dashboard');
|
| 610 |
+
|
| 611 |
+
// Supported values: 'google', 'microsoft', 'facebook'
|
| 612 |
+
```
|
| 613 |
+
|
| 614 |
+
---
|
| 615 |
+
|
| 616 |
+
## Environment Availability
|
| 617 |
+
|
| 618 |
+
| Environment | Availability | Notes |
|
| 619 |
+
|------------|--------------|-------|
|
| 620 |
+
| **Frontend** | ✅ Yes | All methods available |
|
| 621 |
+
| **Backend Functions** | ✅ Yes | Use `createClientFromRequest(req)` for authenticated client |
|
| 622 |
+
| **Service Role** | ❌ No | Auth methods not available in service role context |
|
| 623 |
+
|
| 624 |
+
### Frontend Usage
|
| 625 |
+
```javascript
|
| 626 |
+
// Standard browser usage
|
| 627 |
+
const user = await base44.auth.me();
|
| 628 |
+
```
|
| 629 |
+
|
| 630 |
+
### Backend Functions Usage
|
| 631 |
+
```javascript
|
| 632 |
+
import { createClientFromRequest } from "@base44/sdk";
|
| 633 |
+
|
| 634 |
+
Deno.serve(async (req) => {
|
| 635 |
+
const base44 = createClientFromRequest(req);
|
| 636 |
+
|
| 637 |
+
// Get user from request context
|
| 638 |
+
const user = await base44.auth.me();
|
| 639 |
+
|
| 640 |
+
// User operations here...
|
| 641 |
+
return Response.json({ user });
|
| 642 |
+
});
|
| 643 |
+
```
|
| 644 |
+
|
| 645 |
+
---
|
| 646 |
+
|
| 647 |
+
## App Visibility
|
| 648 |
+
|
| 649 |
+
Control who can access your app in the app settings:
|
| 650 |
+
|
| 651 |
+
### Public Apps
|
| 652 |
+
- No login required for basic access
|
| 653 |
+
- Users can view public content without authentication
|
| 654 |
+
- Authenticated users get additional features/data
|
| 655 |
+
|
| 656 |
+
### Private Apps
|
| 657 |
+
- Login required to access any content
|
| 658 |
+
- Unauthenticated users are automatically redirected to login
|
| 659 |
+
- All content is protected by default
|
| 660 |
+
|
| 661 |
+
---
|
| 662 |
+
|
| 663 |
+
## Limitations
|
| 664 |
+
|
| 665 |
+
### Authentication UI Options
|
| 666 |
+
- **Recommended:** Build custom login/signup UI using `loginViaEmailPassword()` and `loginWithProvider()` for full control over user experience and branding
|
| 667 |
+
- **Alternative:** `redirectToLogin()` uses Base44's hosted authentication pages with limited customization
|
| 668 |
+
|
| 669 |
+
### Hosted Login (via redirectToLogin)
|
| 670 |
+
- `redirectToLogin()` shows both login and signup options on the same page
|
| 671 |
+
- No separate `redirectToSignup()` method
|
| 672 |
+
- Users can switch between login/signup on the hosted page
|
| 673 |
+
- ⚠️ **Note:** Prefer building custom login UI for better user experience
|
| 674 |
+
|
| 675 |
+
### Password Requirements
|
| 676 |
+
- Minimum length and complexity requirements enforced
|
| 677 |
+
- Requirements not exposed via API
|
| 678 |
+
- Validation errors returned when requirements not met
|
| 679 |
+
|
| 680 |
+
### Rate Limiting
|
| 681 |
+
- OTP requests are rate-limited to prevent abuse
|
| 682 |
+
- Password reset requests are rate-limited
|
| 683 |
+
- Login attempts may be rate-limited with Turnstile protection
|
| 684 |
+
|
| 685 |
+
### Token Management
|
| 686 |
+
- JWTs are automatically stored in localStorage by default
|
| 687 |
+
- Token expiration and refresh not exposed in API
|
| 688 |
+
- Call `me()` or `isAuthenticated()` to verify token validity
|
| 689 |
+
|
| 690 |
+
---
|
| 691 |
+
|
| 692 |
+
## Best Practices
|
| 693 |
+
|
| 694 |
+
### 1. Always Handle Errors
|
| 695 |
+
```javascript
|
| 696 |
+
try {
|
| 697 |
+
await base44.auth.loginViaEmailPassword(email, password);
|
| 698 |
+
} catch (error) {
|
| 699 |
+
// Always handle authentication errors
|
| 700 |
+
console.error('Login failed:', error.message);
|
| 701 |
+
}
|
| 702 |
+
```
|
| 703 |
+
|
| 704 |
+
### 2. Verify Authentication Before Protected Actions
|
| 705 |
+
```javascript
|
| 706 |
+
const user = await requireAuth();
|
| 707 |
+
if (!user) return; // Will redirect to login
|
| 708 |
+
// Proceed with authenticated action
|
| 709 |
+
```
|
| 710 |
+
|
| 711 |
+
### 3. Use Type Safety with TypeScript
|
| 712 |
+
```typescript
|
| 713 |
+
import type { User, LoginResponse } from '@base44/sdk';
|
| 714 |
+
|
| 715 |
+
const user: User = await base44.auth.me();
|
| 716 |
+
const response: LoginResponse = await base44.auth.loginViaEmailPassword(email, password);
|
| 717 |
+
```
|
| 718 |
+
|
| 719 |
+
### 4. Don't Hardcode Credentials
|
| 720 |
+
```javascript
|
| 721 |
+
// ❌ BAD
|
| 722 |
+
base44.auth.setToken("hardcoded-token-here");
|
| 723 |
+
|
| 724 |
+
// ✅ GOOD
|
| 725 |
+
const token = await secureAuthFlow();
|
| 726 |
+
base44.auth.setToken(token);
|
| 727 |
+
```
|
| 728 |
+
|
| 729 |
+
### 5. Provide User Feedback
|
| 730 |
+
```javascript
|
| 731 |
+
try {
|
| 732 |
+
await base44.auth.register(params);
|
| 733 |
+
showSuccessMessage('Registration successful! Check your email for verification code.');
|
| 734 |
+
} catch (error) {
|
| 735 |
+
showErrorMessage('Registration failed: ' + error.message);
|
| 736 |
+
}
|
| 737 |
+
```
|
| 738 |
+
|
| 739 |
+
### 6. Handle Token Expiration Gracefully
|
| 740 |
+
```javascript
|
| 741 |
+
try {
|
| 742 |
+
const user = await base44.auth.me();
|
| 743 |
+
} catch (error) {
|
| 744 |
+
if (error.status === 401) {
|
| 745 |
+
// Clear local state and navigate to login
|
| 746 |
+
localStorage.clear();
|
| 747 |
+
navigate('/login');
|
| 748 |
+
}
|
| 749 |
+
}
|
| 750 |
+
```
|
| 751 |
+
|
| 752 |
+
### 7. Build Custom Login UI (Recommended)
|
| 753 |
+
```javascript
|
| 754 |
+
// ✅ RECOMMENDED - Custom login form with direct methods
|
| 755 |
+
const handleLogin = async (email, password) => {
|
| 756 |
+
try {
|
| 757 |
+
const { user } = await base44.auth.loginViaEmailPassword(email, password);
|
| 758 |
+
navigate('/dashboard');
|
| 759 |
+
} catch (error) {
|
| 760 |
+
setError(error.message);
|
| 761 |
+
}
|
| 762 |
+
};
|
| 763 |
+
|
| 764 |
+
const handleGoogleLogin = () => {
|
| 765 |
+
base44.auth.loginWithProvider('google', '/dashboard');
|
| 766 |
+
};
|
| 767 |
+
|
| 768 |
+
// ❌ AVOID - Redirecting to hosted login page
|
| 769 |
+
// base44.auth.redirectToLogin(window.location.href);
|
| 770 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/base44-agents.md
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Agents Module
|
| 2 |
+
|
| 3 |
+
AI agent conversations and messages via `base44.agents`.
|
| 4 |
+
|
| 5 |
+
> **Note:** This module requires a logged-in user. All agent methods work in the context of the authenticated user.
|
| 6 |
+
|
| 7 |
+
## Contents
|
| 8 |
+
- [Concepts](#concepts)
|
| 9 |
+
- [Methods](#methods)
|
| 10 |
+
- [Examples](#examples) (Create, Get Conversations, List, Subscribe, Send Message, WhatsApp)
|
| 11 |
+
- [Message Structure](#message-structure)
|
| 12 |
+
- [Conversation Structure](#conversation-structure)
|
| 13 |
+
- [Common Patterns](#common-patterns)
|
| 14 |
+
|
| 15 |
+
## Concepts
|
| 16 |
+
|
| 17 |
+
- **Conversation**: A dialogue between user and an AI agent. Has unique ID, agent name, user reference, and metadata.
|
| 18 |
+
- **Message**: Single message in a conversation. Has role (`user`, `assistant`, `system`), content, timestamps, and optional metadata.
|
| 19 |
+
|
| 20 |
+
## Methods
|
| 21 |
+
|
| 22 |
+
| Method | Signature | Description |
|
| 23 |
+
|--------|-----------|-------------|
|
| 24 |
+
| `createConversation(params)` | `Promise<Conversation>` | Create a new conversation with an agent |
|
| 25 |
+
| `getConversations()` | `Promise<Conversation[]>` | Get all user's conversations |
|
| 26 |
+
| `getConversation(id)` | `Promise<Conversation>` | Get conversation with messages (includes full tool call results) |
|
| 27 |
+
| `listConversations(filterParams)` | `Promise<Conversation[]>` | Filter/sort/paginate conversations |
|
| 28 |
+
| `subscribeToConversation(id, onUpdate?)` | `() => void` | Realtime updates via WebSocket; tool call data truncated (returns unsubscribe function) |
|
| 29 |
+
| `addMessage(conversation, message)` | `Promise<Message>` | Send a message |
|
| 30 |
+
| `getWhatsAppConnectURL(agentName)` | `string` | Get WhatsApp connection URL for agent |
|
| 31 |
+
|
| 32 |
+
## Examples
|
| 33 |
+
|
| 34 |
+
### Create Conversation
|
| 35 |
+
|
| 36 |
+
```javascript
|
| 37 |
+
const conversation = await base44.agents.createConversation({
|
| 38 |
+
agent_name: "support-agent",
|
| 39 |
+
metadata: {
|
| 40 |
+
order_id: "ORD-123",
|
| 41 |
+
category: "billing"
|
| 42 |
+
}
|
| 43 |
+
});
|
| 44 |
+
|
| 45 |
+
console.log(conversation.id);
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
### Get All Conversations
|
| 49 |
+
|
| 50 |
+
```javascript
|
| 51 |
+
const conversations = await base44.agents.getConversations();
|
| 52 |
+
|
| 53 |
+
conversations.forEach(conv => {
|
| 54 |
+
console.log(conv.id, conv.agent_name, conv.created_date);
|
| 55 |
+
});
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
### Get Single Conversation (with messages)
|
| 59 |
+
|
| 60 |
+
Returns the complete stored conversation including full tool call results (unlike the realtime subscription, which truncates tool call data).
|
| 61 |
+
|
| 62 |
+
```javascript
|
| 63 |
+
const conversation = await base44.agents.getConversation("conv-id-123");
|
| 64 |
+
|
| 65 |
+
console.log(conversation.messages);
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
### List with Filters
|
| 69 |
+
|
| 70 |
+
```javascript
|
| 71 |
+
// Using filterParams object with q, sort, limit, skip, fields
|
| 72 |
+
const recent = await base44.agents.listConversations({
|
| 73 |
+
q: { agent_name: "support-agent" },
|
| 74 |
+
sort: "-created_date",
|
| 75 |
+
limit: 10,
|
| 76 |
+
skip: 0
|
| 77 |
+
});
|
| 78 |
+
|
| 79 |
+
// Filter by metadata
|
| 80 |
+
const highPriority = await base44.agents.listConversations({
|
| 81 |
+
q: {
|
| 82 |
+
agent_name: "support-agent",
|
| 83 |
+
"metadata.priority": "high"
|
| 84 |
+
},
|
| 85 |
+
sort: "-updated_date",
|
| 86 |
+
limit: 20
|
| 87 |
+
});
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
### Subscribe to Updates (Realtime)
|
| 91 |
+
|
| 92 |
+
When receiving messages through this subscription, tool call data is truncated for efficiency (`arguments_string` limited to 500 characters, `results` to 50). Use `getConversation()` after the message completes to retrieve full tool call data.
|
| 93 |
+
|
| 94 |
+
```javascript
|
| 95 |
+
const unsubscribe = base44.agents.subscribeToConversation(
|
| 96 |
+
"conv-id-123",
|
| 97 |
+
(updatedConversation) => {
|
| 98 |
+
// Called when new messages arrive
|
| 99 |
+
console.log("New messages:", updatedConversation.messages);
|
| 100 |
+
}
|
| 101 |
+
);
|
| 102 |
+
|
| 103 |
+
// Later: unsubscribe
|
| 104 |
+
unsubscribe();
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
### Send a Message
|
| 108 |
+
|
| 109 |
+
```javascript
|
| 110 |
+
const conversation = await base44.agents.getConversation("conv-id-123");
|
| 111 |
+
|
| 112 |
+
await base44.agents.addMessage(conversation, {
|
| 113 |
+
role: "user",
|
| 114 |
+
content: "What's the weather like today?"
|
| 115 |
+
});
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
### Get WhatsApp Connection URL
|
| 119 |
+
|
| 120 |
+
```javascript
|
| 121 |
+
const whatsappUrl = base44.agents.getWhatsAppConnectURL("support-agent");
|
| 122 |
+
// Returns URL for users to connect with agent via WhatsApp
|
| 123 |
+
console.log(whatsappUrl);
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
## Message Structure
|
| 127 |
+
|
| 128 |
+
```javascript
|
| 129 |
+
{
|
| 130 |
+
role: "user" | "assistant" | "system",
|
| 131 |
+
content: "Message text or structured object",
|
| 132 |
+
created_date: "2024-01-15T10:30:00Z",
|
| 133 |
+
updated_date: "2024-01-15T10:30:00Z",
|
| 134 |
+
|
| 135 |
+
// Optional fields
|
| 136 |
+
reasoning: {
|
| 137 |
+
content: "Agent's reasoning process",
|
| 138 |
+
timing: 1500
|
| 139 |
+
},
|
| 140 |
+
tool_calls: [{
|
| 141 |
+
name: "search",
|
| 142 |
+
arguments: { query: "weather" },
|
| 143 |
+
result: { ... },
|
| 144 |
+
status: "success"
|
| 145 |
+
}],
|
| 146 |
+
file_urls: ["https://..."],
|
| 147 |
+
usage: {
|
| 148 |
+
prompt_tokens: 150,
|
| 149 |
+
completion_tokens: 50
|
| 150 |
+
},
|
| 151 |
+
metadata: { ... },
|
| 152 |
+
custom_context: { ... }
|
| 153 |
+
}
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
## Conversation Structure
|
| 157 |
+
|
| 158 |
+
```javascript
|
| 159 |
+
{
|
| 160 |
+
id: "conv-id-123",
|
| 161 |
+
app_id: "app-id",
|
| 162 |
+
agent_name: "support-agent",
|
| 163 |
+
created_by_id: "user-id",
|
| 164 |
+
created_date: "2024-01-15T10:00:00Z",
|
| 165 |
+
updated_date: "2024-01-15T10:30:00Z",
|
| 166 |
+
messages: [ ... ],
|
| 167 |
+
metadata: { ... }
|
| 168 |
+
}
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
## Common Patterns
|
| 172 |
+
|
| 173 |
+
### Chat Interface
|
| 174 |
+
|
| 175 |
+
```javascript
|
| 176 |
+
// Load conversation
|
| 177 |
+
const conv = await base44.agents.getConversation(conversationId);
|
| 178 |
+
setMessages(conv.messages);
|
| 179 |
+
|
| 180 |
+
// Subscribe to updates
|
| 181 |
+
const unsubscribe = base44.agents.subscribeToConversation(conversationId, (updated) => {
|
| 182 |
+
setMessages(updated.messages);
|
| 183 |
+
});
|
| 184 |
+
|
| 185 |
+
// Send message
|
| 186 |
+
async function sendMessage(text) {
|
| 187 |
+
await base44.agents.addMessage(conv, { role: "user", content: text });
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
// Cleanup on unmount
|
| 191 |
+
return () => unsubscribe();
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
## Type Definitions
|
| 195 |
+
|
| 196 |
+
### AgentNameRegistry and AgentName
|
| 197 |
+
|
| 198 |
+
**How to get typed agent names:** The Base44 CLI can generate an augmentation of `AgentNameRegistry` from your project. For how to run it, use the **base44-cli** skill.
|
| 199 |
+
|
| 200 |
+
```typescript
|
| 201 |
+
/**
|
| 202 |
+
* Registry of agent names.
|
| 203 |
+
* Augment this interface to enable autocomplete for agent names.
|
| 204 |
+
* Typically populated by the Base44 CLI type generator.
|
| 205 |
+
*/
|
| 206 |
+
interface AgentNameRegistry {}
|
| 207 |
+
|
| 208 |
+
/**
|
| 209 |
+
* Agent name type - uses registry keys if augmented, otherwise string.
|
| 210 |
+
*/
|
| 211 |
+
type AgentName = keyof AgentNameRegistry extends never ? string : keyof AgentNameRegistry;
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
### AgentConversation
|
| 215 |
+
|
| 216 |
+
```typescript
|
| 217 |
+
/** An agent conversation containing messages exchanged with an AI agent. */
|
| 218 |
+
interface AgentConversation {
|
| 219 |
+
/** Unique identifier for the conversation. */
|
| 220 |
+
id: string;
|
| 221 |
+
/** Application ID. */
|
| 222 |
+
app_id: string;
|
| 223 |
+
/** Name of the agent in this conversation. */
|
| 224 |
+
agent_name: string;
|
| 225 |
+
/** ID of the user who created the conversation. */
|
| 226 |
+
created_by_id: string;
|
| 227 |
+
/** When the conversation was created. */
|
| 228 |
+
created_date: string;
|
| 229 |
+
/** When the conversation was last updated. */
|
| 230 |
+
updated_date: string;
|
| 231 |
+
/** Array of messages in the conversation. */
|
| 232 |
+
messages: AgentMessage[];
|
| 233 |
+
/** Optional metadata associated with the conversation. */
|
| 234 |
+
metadata?: Record<string, any>;
|
| 235 |
+
}
|
| 236 |
+
```
|
| 237 |
+
|
| 238 |
+
### AgentMessage
|
| 239 |
+
|
| 240 |
+
```typescript
|
| 241 |
+
/** A message in an agent conversation. */
|
| 242 |
+
interface AgentMessage {
|
| 243 |
+
/** Unique identifier for the message. */
|
| 244 |
+
id: string;
|
| 245 |
+
/** Role of the message sender. */
|
| 246 |
+
role: "user" | "assistant" | "system";
|
| 247 |
+
/** When the message was created. */
|
| 248 |
+
created_date: string;
|
| 249 |
+
/** When the message was last updated. */
|
| 250 |
+
updated_date: string;
|
| 251 |
+
/** Message content. */
|
| 252 |
+
content?: string | Record<string, any>;
|
| 253 |
+
/** Optional reasoning information for the message. */
|
| 254 |
+
reasoning?: AgentMessageReasoning | null;
|
| 255 |
+
/** URLs to files attached to the message. */
|
| 256 |
+
file_urls?: string[];
|
| 257 |
+
/** Tool calls made by the agent. */
|
| 258 |
+
tool_calls?: AgentMessageToolCall[];
|
| 259 |
+
/** Token usage statistics. */
|
| 260 |
+
usage?: AgentMessageUsage;
|
| 261 |
+
/** Whether the message is hidden from the user. */
|
| 262 |
+
hidden?: boolean;
|
| 263 |
+
/** Custom context provided with the message. */
|
| 264 |
+
custom_context?: AgentMessageCustomContext[];
|
| 265 |
+
/** Model used to generate the message. */
|
| 266 |
+
model?: string;
|
| 267 |
+
/** Checkpoint ID for the message. */
|
| 268 |
+
checkpoint_id?: string;
|
| 269 |
+
/** Metadata about when and by whom the message was created. */
|
| 270 |
+
metadata?: AgentMessageMetadata;
|
| 271 |
+
}
|
| 272 |
+
```
|
| 273 |
+
|
| 274 |
+
### Supporting Types
|
| 275 |
+
|
| 276 |
+
```typescript
|
| 277 |
+
/** Reasoning information for an agent message. */
|
| 278 |
+
interface AgentMessageReasoning {
|
| 279 |
+
/** When reasoning started. */
|
| 280 |
+
start_date: string;
|
| 281 |
+
/** When reasoning ended. */
|
| 282 |
+
end_date?: string;
|
| 283 |
+
/** Reasoning content. */
|
| 284 |
+
content: string;
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
/** A tool call made by the agent. */
|
| 288 |
+
interface AgentMessageToolCall {
|
| 289 |
+
/** Tool call ID. */
|
| 290 |
+
id: string;
|
| 291 |
+
/** Name of the tool called. */
|
| 292 |
+
name: string;
|
| 293 |
+
/** Arguments passed to the tool as JSON string. */
|
| 294 |
+
arguments_string: string;
|
| 295 |
+
/** Status of the tool call. */
|
| 296 |
+
status: "running" | "success" | "error" | "stopped";
|
| 297 |
+
/** Results from the tool call. */
|
| 298 |
+
results?: string;
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
/** Token usage statistics for an agent message. */
|
| 302 |
+
interface AgentMessageUsage {
|
| 303 |
+
/** Number of tokens in the prompt. */
|
| 304 |
+
prompt_tokens?: number;
|
| 305 |
+
/** Number of tokens in the completion. */
|
| 306 |
+
completion_tokens?: number;
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
/** Custom context provided with an agent message. */
|
| 310 |
+
interface AgentMessageCustomContext {
|
| 311 |
+
/** Context message. */
|
| 312 |
+
message: string;
|
| 313 |
+
/** Associated data for the context. */
|
| 314 |
+
data: Record<string, any>;
|
| 315 |
+
/** Type of context. */
|
| 316 |
+
type: string;
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
/** Metadata about when and by whom a message was created. */
|
| 320 |
+
interface AgentMessageMetadata {
|
| 321 |
+
/** When the message was created. */
|
| 322 |
+
created_date: string;
|
| 323 |
+
/** Email of the user who created the message. */
|
| 324 |
+
created_by_email: string;
|
| 325 |
+
/** Full name of the user who created the message. */
|
| 326 |
+
created_by_full_name: string;
|
| 327 |
+
}
|
| 328 |
+
```
|
| 329 |
+
|
| 330 |
+
### CreateConversationParams
|
| 331 |
+
|
| 332 |
+
```typescript
|
| 333 |
+
/** Parameters for creating a new conversation. */
|
| 334 |
+
interface CreateConversationParams {
|
| 335 |
+
/** The name of the agent to create a conversation with. */
|
| 336 |
+
agent_name: AgentName;
|
| 337 |
+
/** Optional metadata to attach to the conversation. */
|
| 338 |
+
metadata?: Record<string, any>;
|
| 339 |
+
}
|
| 340 |
+
```
|
| 341 |
+
|
| 342 |
+
### ModelFilterParams
|
| 343 |
+
|
| 344 |
+
```typescript
|
| 345 |
+
/** Parameters for filtering, sorting, and paginating conversations. */
|
| 346 |
+
interface ModelFilterParams {
|
| 347 |
+
/** Query object with field-value pairs for filtering. */
|
| 348 |
+
q?: Record<string, any>;
|
| 349 |
+
/** Sort parameter (e.g., "-created_date" for descending). */
|
| 350 |
+
sort?: string | null;
|
| 351 |
+
/** Maximum number of results to return. */
|
| 352 |
+
limit?: number | null;
|
| 353 |
+
/** Number of results to skip for pagination. */
|
| 354 |
+
skip?: number | null;
|
| 355 |
+
/** Array of field names to include in the response. */
|
| 356 |
+
fields?: string[] | null;
|
| 357 |
+
}
|
| 358 |
+
```
|
| 359 |
+
|
| 360 |
+
### AgentsModule
|
| 361 |
+
|
| 362 |
+
```typescript
|
| 363 |
+
/** Agents module for managing AI agent conversations. */
|
| 364 |
+
interface AgentsModule {
|
| 365 |
+
/** Gets all conversations from all agents in the app. */
|
| 366 |
+
getConversations(): Promise<AgentConversation[]>;
|
| 367 |
+
|
| 368 |
+
/** Gets a specific conversation by ID. Returns complete stored conversation including full tool call results. */
|
| 369 |
+
getConversation(conversationId: string): Promise<AgentConversation | undefined>;
|
| 370 |
+
|
| 371 |
+
/** Lists conversations with filtering, sorting, and pagination. */
|
| 372 |
+
listConversations(filterParams: ModelFilterParams): Promise<AgentConversation[]>;
|
| 373 |
+
|
| 374 |
+
/** Creates a new conversation with an agent. */
|
| 375 |
+
createConversation(conversation: CreateConversationParams): Promise<AgentConversation>;
|
| 376 |
+
|
| 377 |
+
/** Adds a message to a conversation. */
|
| 378 |
+
addMessage(conversation: AgentConversation, message: Partial<AgentMessage>): Promise<AgentMessage>;
|
| 379 |
+
|
| 380 |
+
/** Subscribes to realtime updates for a conversation. Returns unsubscribe function. */
|
| 381 |
+
subscribeToConversation(conversationId: string, onUpdate?: (conversation: AgentConversation) => void): () => void;
|
| 382 |
+
|
| 383 |
+
/** Gets WhatsApp connection URL for an agent. */
|
| 384 |
+
getWhatsAppConnectURL(agentName: AgentName): string;
|
| 385 |
+
}
|
| 386 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/client.md
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Client Setup
|
| 2 |
+
|
| 3 |
+
How to create and configure the Base44 client.
|
| 4 |
+
|
| 5 |
+
## Contents
|
| 6 |
+
- [In Base44-Generated Apps](#in-base44-generated-apps)
|
| 7 |
+
- [In External Apps](#in-external-apps)
|
| 8 |
+
- [In Backend Functions](#in-backend-functions)
|
| 9 |
+
- [Authentication Modes](#authentication-modes) (Anonymous, User, Service Role)
|
| 10 |
+
- [Available Modules](#available-modules)
|
| 11 |
+
- [Client Methods](#client-methods)
|
| 12 |
+
- [Client Configuration Options](#client-configuration-options)
|
| 13 |
+
|
| 14 |
+
## In Base44-Generated Apps
|
| 15 |
+
|
| 16 |
+
Inside a Base44 app, the client is automatically created and configured. Import it from `@/api/base44Client` and use it as `base44`:
|
| 17 |
+
|
| 18 |
+
```javascript
|
| 19 |
+
const tasks = await base44.entities.Task.list();
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
## In External Apps
|
| 23 |
+
|
| 24 |
+
When using Base44 as a backend from an external app, install the SDK and create a client by calling `createClient()` directly:
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
npm install @base44/sdk
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
```javascript
|
| 31 |
+
import { createClient } from "@base44/sdk";
|
| 32 |
+
|
| 33 |
+
// IMPORTANT: The parameter name is 'appId' (NOT 'clientId', NOT 'id')
|
| 34 |
+
// IMPORTANT: onError must be nested inside 'options' object
|
| 35 |
+
const base44 = createClient({
|
| 36 |
+
appId: "your-app-id", // Required: Use 'appId' parameter
|
| 37 |
+
token: "optional-user-token", // Optional: for pre-authenticated requests
|
| 38 |
+
options: { // Optional: configuration options
|
| 39 |
+
onError: (error) => { // Optional: error handler (must be in options)
|
| 40 |
+
console.error("Base44 error:", error);
|
| 41 |
+
}
|
| 42 |
+
}
|
| 43 |
+
});
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
**Common Mistakes:**
|
| 47 |
+
- ❌ `createClient({ clientId: "..." })` - WRONG parameter name
|
| 48 |
+
- ❌ `createClient({ id: "..." })` - WRONG parameter name
|
| 49 |
+
- ❌ `createClient({ appId: "...", onError: ... })` - WRONG: onError must be in options
|
| 50 |
+
- ✅ `createClient({ appId: "..." })` - CORRECT parameter name
|
| 51 |
+
- ✅ `createClient({ appId: "...", options: { onError: ... } })` - CORRECT: onError in options
|
| 52 |
+
|
| 53 |
+
## In Backend Functions
|
| 54 |
+
|
| 55 |
+
`createClientFromRequest()` is designed for Base44-hosted backend functions. It extracts auth from request headers that Base44 injects and returns a client that includes service role access (`base44.asServiceRole`). For frontends and external backends, use `createClient()` instead.
|
| 56 |
+
|
| 57 |
+
```javascript
|
| 58 |
+
import { createClientFromRequest } from "@base44/sdk";
|
| 59 |
+
|
| 60 |
+
Deno.serve(async (req) => {
|
| 61 |
+
const base44 = createClientFromRequest(req);
|
| 62 |
+
|
| 63 |
+
// Client inherits authentication from the request
|
| 64 |
+
const user = await base44.auth.me();
|
| 65 |
+
|
| 66 |
+
return Response.json({ user });
|
| 67 |
+
});
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
## Authentication Modes
|
| 71 |
+
|
| 72 |
+
| Mode | How to Get | Permissions |
|
| 73 |
+
|------|-----------|-------------|
|
| 74 |
+
| **Anonymous** | `createClient({ appId })` without token | Public data only |
|
| 75 |
+
| **User** | After `loginViaEmailPassword()` or via `createClientFromRequest` | User's own data |
|
| 76 |
+
| **Service Role** | `base44.asServiceRole.*` in backend | Full admin access |
|
| 77 |
+
|
| 78 |
+
## Anonymous Mode
|
| 79 |
+
|
| 80 |
+
No authentication. Can only access public resources.
|
| 81 |
+
|
| 82 |
+
```javascript
|
| 83 |
+
const base44 = createClient({ appId: "your-app-id" });
|
| 84 |
+
|
| 85 |
+
// Only works if Task entity allows anonymous read
|
| 86 |
+
const publicTasks = await base44.entities.Task.list();
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
## User Mode
|
| 90 |
+
|
| 91 |
+
After user logs in, the client automatically includes their token.
|
| 92 |
+
|
| 93 |
+
```javascript
|
| 94 |
+
const base44 = createClient({ appId: "your-app-id" });
|
| 95 |
+
|
| 96 |
+
// Login sets the token
|
| 97 |
+
await base44.auth.loginViaEmailPassword("user@example.com", "password");
|
| 98 |
+
|
| 99 |
+
// Subsequent requests are authenticated
|
| 100 |
+
const user = await base44.auth.me();
|
| 101 |
+
const myTasks = await base44.entities.Task.list(); // filtered by permissions
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
## Service Role Mode
|
| 105 |
+
|
| 106 |
+
Admin-level access. **Backend only.**
|
| 107 |
+
|
| 108 |
+
```javascript
|
| 109 |
+
// Inside a backend function
|
| 110 |
+
Deno.serve(async (req) => {
|
| 111 |
+
const base44 = createClientFromRequest(req);
|
| 112 |
+
|
| 113 |
+
// User mode - respects permissions
|
| 114 |
+
const myTasks = await base44.entities.Task.list();
|
| 115 |
+
|
| 116 |
+
// Service role - bypasses permissions
|
| 117 |
+
const allTasks = await base44.asServiceRole.entities.Task.list();
|
| 118 |
+
const allUsers = await base44.asServiceRole.entities.User.list();
|
| 119 |
+
const oauthToken = await base44.asServiceRole.connectors.getAccessToken("slack");
|
| 120 |
+
|
| 121 |
+
return Response.json({ myTasks, allTasks });
|
| 122 |
+
});
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
## Available Modules
|
| 126 |
+
|
| 127 |
+
The client exposes these modules:
|
| 128 |
+
|
| 129 |
+
```javascript
|
| 130 |
+
base44.agents // AI conversations
|
| 131 |
+
base44.analytics // Event tracking
|
| 132 |
+
base44.appLogs // App usage logging
|
| 133 |
+
base44.auth // Authentication
|
| 134 |
+
base44.connectors // Per-user OAuth flows (UserConnectorsModule)
|
| 135 |
+
base44.entities // CRUD operations
|
| 136 |
+
base44.functions // Backend function invocation
|
| 137 |
+
base44.integrations // Third-party services
|
| 138 |
+
base44.users // User invitations
|
| 139 |
+
|
| 140 |
+
// Service role only (backend)
|
| 141 |
+
base44.asServiceRole.agents
|
| 142 |
+
base44.asServiceRole.appLogs
|
| 143 |
+
base44.asServiceRole.connectors // App-scoped OAuth tokens (ConnectorsModule)
|
| 144 |
+
base44.asServiceRole.entities
|
| 145 |
+
base44.asServiceRole.functions
|
| 146 |
+
base44.asServiceRole.integrations
|
| 147 |
+
base44.asServiceRole.sso // SSO token generation
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
+
## Client Methods
|
| 151 |
+
|
| 152 |
+
The client provides these methods:
|
| 153 |
+
|
| 154 |
+
```javascript
|
| 155 |
+
// Set authentication token for all subsequent requests
|
| 156 |
+
base44.setToken(newToken);
|
| 157 |
+
|
| 158 |
+
// Cleanup WebSocket connections (call when done with client)
|
| 159 |
+
base44.cleanup();
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
### setToken
|
| 163 |
+
|
| 164 |
+
Updates the authentication token for all subsequent API requests and WebSocket connections.
|
| 165 |
+
|
| 166 |
+
```javascript
|
| 167 |
+
// After receiving a token (e.g., from external auth)
|
| 168 |
+
base44.setToken("new-jwt-token");
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
### cleanup
|
| 172 |
+
|
| 173 |
+
Disconnects WebSocket connections. Call when you're done with the client or when the component unmounts.
|
| 174 |
+
|
| 175 |
+
```javascript
|
| 176 |
+
// Cleanup on component unmount (React example)
|
| 177 |
+
useEffect(() => {
|
| 178 |
+
return () => base44.cleanup();
|
| 179 |
+
}, []);
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
## Client Configuration Options
|
| 183 |
+
|
| 184 |
+
```javascript
|
| 185 |
+
createClient({
|
| 186 |
+
appId: "your-app-id", // Required: MUST use 'appId' (not 'clientId' or 'id')
|
| 187 |
+
token: "jwt-token", // Optional: pre-set auth token
|
| 188 |
+
options: { // Optional: configuration options
|
| 189 |
+
onError: (error) => {} // Optional: global error handler (must be in options)
|
| 190 |
+
}
|
| 191 |
+
});
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
**⚠️ Critical:**
|
| 195 |
+
- The parameter name is `appId`, not `clientId` or `id`. Using the wrong parameter name will cause errors.
|
| 196 |
+
- The `onError` handler must be nested inside the `options` object, not at the top level.
|
| 197 |
+
|
| 198 |
+
## Type Definitions
|
| 199 |
+
|
| 200 |
+
### CreateClientConfig
|
| 201 |
+
|
| 202 |
+
```typescript
|
| 203 |
+
/** Configuration for creating a Base44 client. */
|
| 204 |
+
interface CreateClientConfig {
|
| 205 |
+
/** The Base44 app ID (required). */
|
| 206 |
+
appId: string;
|
| 207 |
+
/** User authentication token. Used to authenticate as a specific user. */
|
| 208 |
+
token?: string;
|
| 209 |
+
/** @internal Service role token; only set automatically in Base44-hosted backend functions. */
|
| 210 |
+
serviceToken?: string;
|
| 211 |
+
/** Additional client options. */
|
| 212 |
+
options?: CreateClientOptions;
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
/** Options for creating a Base44 client. */
|
| 216 |
+
interface CreateClientOptions {
|
| 217 |
+
/** Optional error handler called whenever an API error occurs. */
|
| 218 |
+
onError?: (error: Error) => void;
|
| 219 |
+
}
|
| 220 |
+
```
|
| 221 |
+
|
| 222 |
+
### Base44Client
|
| 223 |
+
|
| 224 |
+
```typescript
|
| 225 |
+
/** The Base44 client instance. */
|
| 226 |
+
interface Base44Client {
|
| 227 |
+
/** Agents module for managing AI agent conversations. */
|
| 228 |
+
agents: AgentsModule;
|
| 229 |
+
/** Analytics module for tracking custom events. */
|
| 230 |
+
analytics: AnalyticsModule;
|
| 231 |
+
/** App logs module for tracking app usage. */
|
| 232 |
+
appLogs: AppLogsModule;
|
| 233 |
+
/** Auth module for user authentication and management. */
|
| 234 |
+
auth: AuthModule;
|
| 235 |
+
/** Entities module for CRUD operations on your data models. */
|
| 236 |
+
entities: EntitiesModule;
|
| 237 |
+
/** Functions module for invoking custom backend functions. */
|
| 238 |
+
functions: FunctionsModule;
|
| 239 |
+
/** Integrations module for calling pre-built integration methods. */
|
| 240 |
+
integrations: IntegrationsModule;
|
| 241 |
+
|
| 242 |
+
/** Cleanup function to disconnect WebSocket connections. */
|
| 243 |
+
cleanup(): void;
|
| 244 |
+
|
| 245 |
+
/** Sets a new authentication token for all subsequent requests. */
|
| 246 |
+
setToken(newToken: string): void;
|
| 247 |
+
|
| 248 |
+
/** Per-user OAuth flows. Each end user has their own connection. */
|
| 249 |
+
connectors: UserConnectorsModule;
|
| 250 |
+
|
| 251 |
+
/** Provides access to modules with elevated service role permissions (backend only). */
|
| 252 |
+
readonly asServiceRole: {
|
| 253 |
+
agents: AgentsModule;
|
| 254 |
+
appLogs: AppLogsModule;
|
| 255 |
+
/** App-scoped OAuth tokens. All users share the same connected account. */
|
| 256 |
+
connectors: ConnectorsModule;
|
| 257 |
+
entities: EntitiesModule;
|
| 258 |
+
functions: FunctionsModule;
|
| 259 |
+
integrations: IntegrationsModule;
|
| 260 |
+
/** SSO token generation for users. */
|
| 261 |
+
sso: SsoModule;
|
| 262 |
+
cleanup(): void;
|
| 263 |
+
};
|
| 264 |
+
}
|
| 265 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/connectors.md
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Connectors Module
|
| 2 |
+
|
| 3 |
+
OAuth token management for external services.
|
| 4 |
+
|
| 5 |
+
- **`base44.asServiceRole.connectors`** — App-scoped OAuth tokens (backend/service role only). All users share the same connected account.
|
| 6 |
+
|
| 7 |
+
## Contents
|
| 8 |
+
- [Service Role Connectors (`base44.asServiceRole.connectors`)](#service-role-connectors-base44asserviceroleconnectors)
|
| 9 |
+
- [Available Services](#available-services)
|
| 10 |
+
- [Type Definitions](#type-definitions)
|
| 11 |
+
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
## Service Role Connectors (`base44.asServiceRole.connectors`)
|
| 15 |
+
|
| 16 |
+
App-scoped OAuth tokens. The app builder connects the account once; all users share it. **Backend/service role only.**
|
| 17 |
+
|
| 18 |
+
### Methods
|
| 19 |
+
|
| 20 |
+
| Method | Signature | Description |
|
| 21 |
+
|--------|-----------|-------------|
|
| 22 |
+
| `getConnection(integrationType)` | `Promise<ConnectorConnectionResponse>` | Get access token and optional connection config |
|
| 23 |
+
| `getAccessToken(integrationType)` | `Promise<string>` | ⚠️ **Deprecated** — use `getConnection()` instead |
|
| 24 |
+
|
| 25 |
+
### Examples
|
| 26 |
+
|
| 27 |
+
```javascript
|
| 28 |
+
// Backend function only
|
| 29 |
+
Deno.serve(async (req) => {
|
| 30 |
+
const base44 = createClientFromRequest(req);
|
| 31 |
+
|
| 32 |
+
// Recommended: use getConnection() for token + optional config
|
| 33 |
+
const { accessToken, connectionConfig } = await base44.asServiceRole.connectors.getConnection("slack");
|
| 34 |
+
|
| 35 |
+
const response = await fetch("https://slack.com/api/chat.postMessage", {
|
| 36 |
+
method: "POST",
|
| 37 |
+
headers: {
|
| 38 |
+
"Authorization": `Bearer ${accessToken}`,
|
| 39 |
+
"Content-Type": "application/json"
|
| 40 |
+
},
|
| 41 |
+
body: JSON.stringify({ channel: "#general", text: "Hello from Base44!" })
|
| 42 |
+
});
|
| 43 |
+
|
| 44 |
+
return Response.json(await response.json());
|
| 45 |
+
});
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
```javascript
|
| 49 |
+
// Using connectionConfig (for services that need extra params, e.g. a subdomain)
|
| 50 |
+
const { accessToken, connectionConfig } = await base44.asServiceRole.connectors.getConnection("myservice");
|
| 51 |
+
const subdomain = connectionConfig?.subdomain;
|
| 52 |
+
const response = await fetch(`https://${subdomain}.example.com/api/v1/data`, {
|
| 53 |
+
headers: { "Authorization": `Bearer ${accessToken}` }
|
| 54 |
+
});
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
```javascript
|
| 58 |
+
// Google Calendar example
|
| 59 |
+
const { accessToken } = await base44.asServiceRole.connectors.getConnection("googlecalendar");
|
| 60 |
+
|
| 61 |
+
const events = await fetch(
|
| 62 |
+
"https://www.googleapis.com/calendar/v3/calendars/primary/events?" +
|
| 63 |
+
new URLSearchParams({ maxResults: "10", orderBy: "startTime", singleEvents: "true", timeMin: new Date().toISOString() }),
|
| 64 |
+
{ headers: { "Authorization": `Bearer ${accessToken}` } }
|
| 65 |
+
).then(r => r.json());
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
---
|
| 69 |
+
|
| 70 |
+
## Available Services
|
| 71 |
+
|
| 72 |
+
| Service | Type identifier |
|
| 73 |
+
|---------|----------------|
|
| 74 |
+
| Airtable | `airtable` |
|
| 75 |
+
| Box | `box` |
|
| 76 |
+
| ClickUp | `clickup` |
|
| 77 |
+
| Discord | `discord` |
|
| 78 |
+
| Dropbox | `dropbox` |
|
| 79 |
+
| GitHub | `github` |
|
| 80 |
+
| Gmail | `gmail` |
|
| 81 |
+
| Google Analytics | `google_analytics` |
|
| 82 |
+
| Google BigQuery | `googlebigquery` |
|
| 83 |
+
| Google Calendar | `googlecalendar` |
|
| 84 |
+
| Google Classroom | `google_classroom` |
|
| 85 |
+
| Google Docs | `googledocs` |
|
| 86 |
+
| Google Drive | `googledrive` |
|
| 87 |
+
| Google Search Console | `google_search_console` |
|
| 88 |
+
| Google Sheets | `googlesheets` |
|
| 89 |
+
| Google Slides | `googleslides` |
|
| 90 |
+
| HubSpot | `hubspot` |
|
| 91 |
+
| Linear | `linear` |
|
| 92 |
+
| LinkedIn | `linkedin` |
|
| 93 |
+
| Microsoft Teams | `microsoft_teams` |
|
| 94 |
+
| Microsoft OneDrive | `one_drive` |
|
| 95 |
+
| Notion | `notion` |
|
| 96 |
+
| Outlook | `outlook` |
|
| 97 |
+
| Salesforce | `salesforce` |
|
| 98 |
+
| SharePoint | `share_point` |
|
| 99 |
+
| Slack User | `slack` |
|
| 100 |
+
| Slack Bot | `slackbot` |
|
| 101 |
+
| Splitwise | `splitwise` |
|
| 102 |
+
| TikTok | `tiktok` |
|
| 103 |
+
| Typeform | `typeform` |
|
| 104 |
+
| Wix | `wix` |
|
| 105 |
+
| Wrike | `wrike` |
|
| 106 |
+
|
| 107 |
+
Run `npx base44 connectors list-available` from the CLI to see all available types.
|
| 108 |
+
|
| 109 |
+
---
|
| 110 |
+
|
| 111 |
+
## Setup Requirements
|
| 112 |
+
|
| 113 |
+
1. **Builder plan** or higher
|
| 114 |
+
2. **Backend functions** enabled (for service role connectors)
|
| 115 |
+
3. **Connector configured** in Base44 dashboard (OAuth flow completed)
|
| 116 |
+
|
| 117 |
+
## Important Notes
|
| 118 |
+
|
| 119 |
+
- **Service role connectors**: One account per connector per app — all users share the same connected account
|
| 120 |
+
- **You handle the API calls**: Base44 provides the token; you make the actual API requests
|
| 121 |
+
- **Token refresh**: Base44 handles token refresh automatically
|
| 122 |
+
|
| 123 |
+
---
|
| 124 |
+
|
| 125 |
+
## Type Definitions
|
| 126 |
+
|
| 127 |
+
```typescript
|
| 128 |
+
/**
|
| 129 |
+
* The type of external integration/connector (for service role connectors).
|
| 130 |
+
* Examples: 'googlecalendar', 'slack', 'github', 'notion', etc.
|
| 131 |
+
*/
|
| 132 |
+
type ConnectorIntegrationType = string;
|
| 133 |
+
|
| 134 |
+
/** Connection details returned by getConnection(). */
|
| 135 |
+
interface ConnectorConnectionResponse {
|
| 136 |
+
/** The OAuth access token for the external service. */
|
| 137 |
+
accessToken: string;
|
| 138 |
+
/** Key-value configuration for the connection, or null if not needed. */
|
| 139 |
+
connectionConfig: Record<string, string> | null;
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
/** Service role connectors module (app-scoped OAuth). Backend only. */
|
| 143 |
+
interface ConnectorsModule {
|
| 144 |
+
/**
|
| 145 |
+
* Retrieves the OAuth access token and optional connection config.
|
| 146 |
+
* @param integrationType - e.g., 'googlecalendar', 'slack', 'github'.
|
| 147 |
+
*/
|
| 148 |
+
getConnection(integrationType: ConnectorIntegrationType): Promise<ConnectorConnectionResponse>;
|
| 149 |
+
|
| 150 |
+
/**
|
| 151 |
+
* @deprecated Use getConnection() instead.
|
| 152 |
+
* Retrieves only the OAuth access token string.
|
| 153 |
+
*/
|
| 154 |
+
getAccessToken(integrationType: ConnectorIntegrationType): Promise<string>;
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/entities.md
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Entities Module
|
| 2 |
+
|
| 3 |
+
CRUD operations on data models. Access via `base44.entities.EntityName.method()`.
|
| 4 |
+
|
| 5 |
+
## Contents
|
| 6 |
+
- [Methods](#methods)
|
| 7 |
+
- [Examples](#examples) (Create, Bulk Create, List, Filter, Get, Update, Delete, Subscribe)
|
| 8 |
+
- [User Entity](#user-entity)
|
| 9 |
+
- [Service Role Access](#service-role-access)
|
| 10 |
+
- [Permissions](#permissions)
|
| 11 |
+
|
| 12 |
+
## Methods
|
| 13 |
+
|
| 14 |
+
**Note:** The maximum limit for `list()` and `filter()` is 5,000 items per request.
|
| 15 |
+
|
| 16 |
+
| Method | Signature | Description |
|
| 17 |
+
|--------|-----------|-------------|
|
| 18 |
+
| `create(data)` | `Promise<T>` | Create one record |
|
| 19 |
+
| `bulkCreate(dataArray)` | `Promise<T[]>` | Create multiple records |
|
| 20 |
+
| `list(sort?, limit?, skip?, fields?)` | `Promise<Pick<T, K>[]>` | Get all records (paginated) |
|
| 21 |
+
| `filter(query, sort?, limit?, skip?, fields?)` | `Promise<Pick<T, K>[]>` | Get records matching conditions |
|
| 22 |
+
| `get(id)` | `Promise<T>` | Get single record by ID |
|
| 23 |
+
| `update(id, data)` | `Promise<T>` | Update record (partial update) |
|
| 24 |
+
| `updateMany(query, data)` | `Promise<UpdateManyResult>` | Update all matching records using MongoDB update operators |
|
| 25 |
+
| `bulkUpdate(dataArray)` | `Promise<T[]>` | Update multiple records by ID, each with its own data |
|
| 26 |
+
| `delete(id)` | `Promise<DeleteResult>` | Delete record by ID |
|
| 27 |
+
| `deleteMany(query)` | `Promise<DeleteManyResult>` | Delete all matching records |
|
| 28 |
+
| `importEntities(file)` | `Promise<ImportResult<T>>` | Import from CSV (frontend only) |
|
| 29 |
+
| `subscribe(callback)` | `() => void` | Subscribe to realtime updates (returns unsubscribe function) |
|
| 30 |
+
|
| 31 |
+
## Examples
|
| 32 |
+
|
| 33 |
+
### Create
|
| 34 |
+
|
| 35 |
+
```javascript
|
| 36 |
+
const task = await base44.entities.Task.create({
|
| 37 |
+
title: "Complete documentation",
|
| 38 |
+
status: "pending",
|
| 39 |
+
dueDate: "2024-12-31"
|
| 40 |
+
});
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
### Bulk Create
|
| 44 |
+
|
| 45 |
+
```javascript
|
| 46 |
+
const tasks = await base44.entities.Task.bulkCreate([
|
| 47 |
+
{ title: "Task 1", status: "pending" },
|
| 48 |
+
{ title: "Task 2", status: "pending" }
|
| 49 |
+
]);
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
### List with Pagination
|
| 53 |
+
|
| 54 |
+
```javascript
|
| 55 |
+
// Get first 10 records, sorted by created_date descending (max 5,000 per request)
|
| 56 |
+
const tasks = await base44.entities.Task.list(
|
| 57 |
+
"-created_date", // sort (SortField: prefix with - for descending)
|
| 58 |
+
10, // limit
|
| 59 |
+
0 // skip
|
| 60 |
+
);
|
| 61 |
+
|
| 62 |
+
// Get next page
|
| 63 |
+
const page2 = await base44.entities.Task.list("-created_date", 10, 10);
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
### Filter
|
| 67 |
+
|
| 68 |
+
```javascript
|
| 69 |
+
// Simple filter
|
| 70 |
+
const pending = await base44.entities.Task.filter({ status: "pending" });
|
| 71 |
+
|
| 72 |
+
// Multiple conditions
|
| 73 |
+
const myPending = await base44.entities.Task.filter({
|
| 74 |
+
status: "pending",
|
| 75 |
+
assignedTo: userId
|
| 76 |
+
});
|
| 77 |
+
|
| 78 |
+
// With sort, limit, skip (max 5,000 per request)
|
| 79 |
+
const recent = await base44.entities.Task.filter(
|
| 80 |
+
{ status: "pending" },
|
| 81 |
+
"-created_date", // sort (SortField: prefix with - for descending)
|
| 82 |
+
5,
|
| 83 |
+
0
|
| 84 |
+
);
|
| 85 |
+
|
| 86 |
+
// Select specific fields
|
| 87 |
+
const titles = await base44.entities.Task.filter(
|
| 88 |
+
{ status: "pending" },
|
| 89 |
+
null,
|
| 90 |
+
null,
|
| 91 |
+
null,
|
| 92 |
+
["id", "title"]
|
| 93 |
+
);
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
### Get by ID
|
| 97 |
+
|
| 98 |
+
```javascript
|
| 99 |
+
const task = await base44.entities.Task.get("task-id-123");
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
### Update
|
| 103 |
+
|
| 104 |
+
```javascript
|
| 105 |
+
// Partial update - only specified fields change
|
| 106 |
+
await base44.entities.Task.update("task-id-123", {
|
| 107 |
+
status: "completed",
|
| 108 |
+
completedAt: new Date().toISOString()
|
| 109 |
+
});
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
### Delete
|
| 113 |
+
|
| 114 |
+
```javascript
|
| 115 |
+
// Single record
|
| 116 |
+
const result = await base44.entities.Task.delete("task-id-123");
|
| 117 |
+
console.log("Deleted:", result.success);
|
| 118 |
+
|
| 119 |
+
// Multiple records matching query
|
| 120 |
+
const manyResult = await base44.entities.Task.deleteMany({ status: "archived" });
|
| 121 |
+
console.log("Deleted:", manyResult.deleted);
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
### Update Many (MongoDB-style)
|
| 125 |
+
|
| 126 |
+
```javascript
|
| 127 |
+
// Update all pending tasks to status "in-progress"
|
| 128 |
+
const result = await base44.entities.Task.updateMany(
|
| 129 |
+
{ status: "pending" }, // query: which records to update
|
| 130 |
+
{ $set: { status: "in-progress" } } // MongoDB update operator
|
| 131 |
+
);
|
| 132 |
+
console.log("Updated:", result.updated);
|
| 133 |
+
|
| 134 |
+
// Increment a counter field
|
| 135 |
+
await base44.entities.Task.updateMany(
|
| 136 |
+
{ category: "bugs" },
|
| 137 |
+
{ $inc: { priority: 1 } }
|
| 138 |
+
);
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
### Bulk Update (by ID)
|
| 142 |
+
|
| 143 |
+
```javascript
|
| 144 |
+
// Update multiple records, each with different data
|
| 145 |
+
const updated = await base44.entities.Task.bulkUpdate([
|
| 146 |
+
{ id: "task-1", status: "done", completedAt: new Date().toISOString() },
|
| 147 |
+
{ id: "task-2", status: "in-progress", assignedTo: userId },
|
| 148 |
+
{ id: "task-3", priority: 5 }
|
| 149 |
+
]);
|
| 150 |
+
```
|
| 151 |
+
|
| 152 |
+
### Import from File
|
| 153 |
+
|
| 154 |
+
```javascript
|
| 155 |
+
// Frontend only: import from CSV/file
|
| 156 |
+
const result = await base44.entities.Task.importEntities(file);
|
| 157 |
+
if (result.status === "success" && result.output) {
|
| 158 |
+
console.log(`Imported ${result.output.length} records`);
|
| 159 |
+
} else {
|
| 160 |
+
console.error(result.details);
|
| 161 |
+
}
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
### Subscribe to Realtime Updates
|
| 165 |
+
|
| 166 |
+
```javascript
|
| 167 |
+
// Subscribe to all changes on Task entity
|
| 168 |
+
const unsubscribe = base44.entities.Task.subscribe((event) => {
|
| 169 |
+
console.log(`Task ${event.id} was ${event.type}:`, event.data);
|
| 170 |
+
// event.type is "create", "update", or "delete"
|
| 171 |
+
});
|
| 172 |
+
|
| 173 |
+
// Later: unsubscribe to stop receiving updates
|
| 174 |
+
unsubscribe();
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
**Event structure:**
|
| 178 |
+
```javascript
|
| 179 |
+
{
|
| 180 |
+
type: "create" | "update" | "delete",
|
| 181 |
+
data: { ... }, // the entity data
|
| 182 |
+
id: "entity-id", // the affected entity's ID
|
| 183 |
+
timestamp: "2024-01-15T10:30:00Z"
|
| 184 |
+
}
|
| 185 |
+
```
|
| 186 |
+
|
| 187 |
+
## User Entity
|
| 188 |
+
|
| 189 |
+
Every app has a built-in `User` entity with special rules:
|
| 190 |
+
|
| 191 |
+
- Regular users can only read/update **their own** record
|
| 192 |
+
- Cannot create users via `entities.create()` - use `auth.register()` instead
|
| 193 |
+
- Service role has full access to all user records
|
| 194 |
+
|
| 195 |
+
```javascript
|
| 196 |
+
// Get current user's record
|
| 197 |
+
const me = await base44.entities.User.get(currentUserId);
|
| 198 |
+
|
| 199 |
+
// Service role: get any user
|
| 200 |
+
const anyUser = await base44.asServiceRole.entities.User.get(userId);
|
| 201 |
+
```
|
| 202 |
+
|
| 203 |
+
## Service Role Access
|
| 204 |
+
|
| 205 |
+
For admin-level operations (bypass user permissions):
|
| 206 |
+
|
| 207 |
+
```javascript
|
| 208 |
+
// Backend only
|
| 209 |
+
const allTasks = await base44.asServiceRole.entities.Task.list();
|
| 210 |
+
const allUsers = await base44.asServiceRole.entities.User.list();
|
| 211 |
+
```
|
| 212 |
+
|
| 213 |
+
## Permissions (RLS & FLS)
|
| 214 |
+
|
| 215 |
+
Data access is controlled by **Row Level Security (RLS)** and **Field Level Security (FLS)** rules defined in entity schemas.
|
| 216 |
+
|
| 217 |
+
1. **Authentication level**: anonymous, authenticated, or service role
|
| 218 |
+
2. **RLS rules**: Control which records (rows) users can create/read/update/delete
|
| 219 |
+
3. **FLS rules**: Control which fields users can read/write within accessible records
|
| 220 |
+
|
| 221 |
+
Operations succeed or fail based on these rules - no partial results.
|
| 222 |
+
|
| 223 |
+
RLS and FLS are configured in entity schema files (`base44/entities/*.jsonc`). See [entities-create.md](../../base44-cli/references/entities-create.md#row-level-security-rls) for configuration details.
|
| 224 |
+
|
| 225 |
+
**Note:** `asServiceRole` sets the user's role to `"admin"` but does NOT bypass RLS. Your RLS rules must include admin access (e.g., `{ "user_condition": { "role": "admin" } }`) for service role operations to succeed.
|
| 226 |
+
|
| 227 |
+
## Type Definitions
|
| 228 |
+
|
| 229 |
+
### RealtimeEvent
|
| 230 |
+
|
| 231 |
+
```typescript
|
| 232 |
+
/** Event types for realtime entity updates. */
|
| 233 |
+
type RealtimeEventType = "create" | "update" | "delete";
|
| 234 |
+
|
| 235 |
+
/** Payload received when a realtime event occurs. */
|
| 236 |
+
interface RealtimeEvent<T = any> {
|
| 237 |
+
/** The type of change that occurred. */
|
| 238 |
+
type: RealtimeEventType;
|
| 239 |
+
/** The entity data. */
|
| 240 |
+
data: T;
|
| 241 |
+
/** The unique identifier of the affected entity. */
|
| 242 |
+
id: string;
|
| 243 |
+
/** ISO 8601 timestamp of when the event occurred. */
|
| 244 |
+
timestamp: string;
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
/** Callback function invoked when a realtime event occurs. */
|
| 248 |
+
type RealtimeCallback<T = any> = (event: RealtimeEvent<T>) => void;
|
| 249 |
+
```
|
| 250 |
+
|
| 251 |
+
### Result Types
|
| 252 |
+
|
| 253 |
+
```typescript
|
| 254 |
+
/** Result returned when updating multiple entities. */
|
| 255 |
+
interface UpdateManyResult {
|
| 256 |
+
/** Whether the update was successful. */
|
| 257 |
+
success: boolean;
|
| 258 |
+
/** Number of entities that were updated. */
|
| 259 |
+
updated: number;
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
/** Result returned when deleting a single entity. */
|
| 263 |
+
interface DeleteResult {
|
| 264 |
+
/** Whether the deletion was successful. */
|
| 265 |
+
success: boolean;
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
/** Result returned when deleting multiple entities. */
|
| 269 |
+
interface DeleteManyResult {
|
| 270 |
+
/** Whether the deletion was successful. */
|
| 271 |
+
success: boolean;
|
| 272 |
+
/** Number of entities that were deleted. */
|
| 273 |
+
deleted: number;
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
/** Result returned when importing entities from a file. */
|
| 277 |
+
interface ImportResult<T = any> {
|
| 278 |
+
/** Status of the import operation. */
|
| 279 |
+
status: "success" | "error";
|
| 280 |
+
/** Details message, e.g., "Successfully imported 3 entities with RLS enforcement". */
|
| 281 |
+
details: string | null;
|
| 282 |
+
/** Array of created entity objects when successful, or null on error. */
|
| 283 |
+
output: T[] | null;
|
| 284 |
+
}
|
| 285 |
+
```
|
| 286 |
+
|
| 287 |
+
### SortField and Server Fields
|
| 288 |
+
|
| 289 |
+
```typescript
|
| 290 |
+
/**
|
| 291 |
+
* Sort field type for entity queries.
|
| 292 |
+
* Supports ascending (no prefix or '+') and descending ('-') sorting.
|
| 293 |
+
* Example: 'created_date', '+created_date', '-created_date'
|
| 294 |
+
*/
|
| 295 |
+
type SortField<T> = (keyof T & string) | `+${keyof T & string}` | `-${keyof T & string}`;
|
| 296 |
+
|
| 297 |
+
/** Fields added by the server to every entity record. */
|
| 298 |
+
interface ServerEntityFields {
|
| 299 |
+
id: string;
|
| 300 |
+
created_date: string;
|
| 301 |
+
updated_date: string;
|
| 302 |
+
created_by?: string | null;
|
| 303 |
+
created_by_id?: string | null;
|
| 304 |
+
is_sample?: boolean;
|
| 305 |
+
}
|
| 306 |
+
```
|
| 307 |
+
|
| 308 |
+
### Type Registry (for typed entities)
|
| 309 |
+
|
| 310 |
+
**How to get typed entities:** The Base44 CLI can generate entity interfaces and an augmentation of `EntityTypeRegistry` from your project. For how to run it, use the **base44-cli** skill.
|
| 311 |
+
|
| 312 |
+
```typescript
|
| 313 |
+
/**
|
| 314 |
+
* Registry mapping entity names to their TypeScript types.
|
| 315 |
+
* Augment this interface with your entity schema (user-defined fields only).
|
| 316 |
+
* Typically populated by the Base44 CLI type generator.
|
| 317 |
+
*/
|
| 318 |
+
interface EntityTypeRegistry {}
|
| 319 |
+
|
| 320 |
+
/**
|
| 321 |
+
* Full record type for each entity: schema fields + server-injected fields.
|
| 322 |
+
*/
|
| 323 |
+
type EntityRecord = {
|
| 324 |
+
[K in keyof EntityTypeRegistry]: EntityTypeRegistry[K] & ServerEntityFields;
|
| 325 |
+
};
|
| 326 |
+
```
|
| 327 |
+
|
| 328 |
+
### EntityHandler
|
| 329 |
+
|
| 330 |
+
```typescript
|
| 331 |
+
/** Entity handler providing CRUD operations for a specific entity type. */
|
| 332 |
+
interface EntityHandler<T = any> {
|
| 333 |
+
/** Lists records with optional pagination and sorting. Max 5,000 per request. */
|
| 334 |
+
list<K extends keyof T = keyof T>(
|
| 335 |
+
sort?: SortField<T>,
|
| 336 |
+
limit?: number,
|
| 337 |
+
skip?: number,
|
| 338 |
+
fields?: K[]
|
| 339 |
+
): Promise<Pick<T, K>[]>;
|
| 340 |
+
|
| 341 |
+
/** Filters records based on a query. Max 5,000 per request. */
|
| 342 |
+
filter<K extends keyof T = keyof T>(
|
| 343 |
+
query: Partial<T>,
|
| 344 |
+
sort?: SortField<T>,
|
| 345 |
+
limit?: number,
|
| 346 |
+
skip?: number,
|
| 347 |
+
fields?: K[]
|
| 348 |
+
): Promise<Pick<T, K>[]>;
|
| 349 |
+
|
| 350 |
+
/** Gets a single record by ID. */
|
| 351 |
+
get(id: string): Promise<T>;
|
| 352 |
+
|
| 353 |
+
/** Creates a new record. */
|
| 354 |
+
create(data: Partial<T>): Promise<T>;
|
| 355 |
+
|
| 356 |
+
/** Updates an existing record. */
|
| 357 |
+
update(id: string, data: Partial<T>): Promise<T>;
|
| 358 |
+
|
| 359 |
+
/** Deletes a single record by ID. */
|
| 360 |
+
delete(id: string): Promise<DeleteResult>;
|
| 361 |
+
|
| 362 |
+
/** Deletes multiple records matching a query. */
|
| 363 |
+
deleteMany(query: Partial<T>): Promise<DeleteManyResult>;
|
| 364 |
+
|
| 365 |
+
/** Creates multiple records in a single request. */
|
| 366 |
+
bulkCreate(data: Partial<T>[]): Promise<T[]>;
|
| 367 |
+
|
| 368 |
+
/**
|
| 369 |
+
* Updates multiple records matching a query using MongoDB update operators.
|
| 370 |
+
* @param query - Filter to select which records to update.
|
| 371 |
+
* @param data - MongoDB update operator object (e.g., `{ $set: { field: value } }`).
|
| 372 |
+
*/
|
| 373 |
+
updateMany(query: Partial<T>, data: Record<string, Record<string, any>>): Promise<UpdateManyResult>;
|
| 374 |
+
|
| 375 |
+
/** Updates multiple records by ID, each with its own update data. */
|
| 376 |
+
bulkUpdate(data: (Partial<T> & { id: string })[]): Promise<T[]>;
|
| 377 |
+
|
| 378 |
+
/** Imports records from a file (frontend only). */
|
| 379 |
+
importEntities(file: File): Promise<ImportResult<T>>;
|
| 380 |
+
|
| 381 |
+
/** Subscribes to realtime updates. Returns unsubscribe function. */
|
| 382 |
+
subscribe(callback: RealtimeCallback<T>): () => void;
|
| 383 |
+
}
|
| 384 |
+
```
|
| 385 |
+
|
| 386 |
+
### EntitiesModule
|
| 387 |
+
|
| 388 |
+
```typescript
|
| 389 |
+
/** Entities module: typed registry keys get typed handlers; dynamic access remains untyped. */
|
| 390 |
+
type EntitiesModule = TypedEntitiesModule & DynamicEntitiesModule;
|
| 391 |
+
|
| 392 |
+
type TypedEntitiesModule = {
|
| 393 |
+
[K in keyof EntityTypeRegistry]: EntityHandler<EntityRecord[K]>;
|
| 394 |
+
};
|
| 395 |
+
|
| 396 |
+
type DynamicEntitiesModule = {
|
| 397 |
+
[entityName: string]: EntityHandler<any>;
|
| 398 |
+
};
|
| 399 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/functions.md
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Functions Module
|
| 2 |
+
|
| 3 |
+
Invoke custom backend functions via `base44.functions`.
|
| 4 |
+
|
| 5 |
+
## Contents
|
| 6 |
+
- [Method](#method)
|
| 7 |
+
- [Invoking Functions](#invoking-functions) (Frontend, File Upload, Service Role, REST API)
|
| 8 |
+
- [Writing Backend Functions](#writing-backend-functions) (Basic, Service Role, Secrets, Errors)
|
| 9 |
+
- [Setup Requirements](#setup-requirements)
|
| 10 |
+
- [Authentication Modes](#authentication-modes)
|
| 11 |
+
|
| 12 |
+
## Methods
|
| 13 |
+
|
| 14 |
+
### `invoke`
|
| 15 |
+
|
| 16 |
+
```javascript
|
| 17 |
+
base44.functions.invoke(functionName, data?): Promise<any>
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
- `functionName`: Name of the backend function
|
| 21 |
+
- `data`: Optional object of parameters (sent as JSON, or multipart if contains File objects)
|
| 22 |
+
- Returns: Whatever the function returns
|
| 23 |
+
|
| 24 |
+
### `fetch`
|
| 25 |
+
|
| 26 |
+
```javascript
|
| 27 |
+
base44.functions.fetch(path, init?): Promise<Response>
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
Low-level method that performs a direct HTTP request to a backend function path and returns the native `Response` object. Use when you need streaming responses, custom HTTP methods, or raw response access.
|
| 31 |
+
|
| 32 |
+
- `path`: Function path (e.g., `/streaming_demo` or `/my-function/endpoint`)
|
| 33 |
+
- `init`: Optional native fetch options (`RequestInit`)
|
| 34 |
+
- Returns: Native `Response` object
|
| 35 |
+
|
| 36 |
+
## Invoking Functions
|
| 37 |
+
|
| 38 |
+
### From Frontend
|
| 39 |
+
|
| 40 |
+
```javascript
|
| 41 |
+
const result = await base44.functions.invoke("processOrder", {
|
| 42 |
+
orderId: "order-123",
|
| 43 |
+
action: "ship"
|
| 44 |
+
});
|
| 45 |
+
|
| 46 |
+
console.log(result);
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
### Streaming Response (using fetch)
|
| 50 |
+
|
| 51 |
+
```javascript
|
| 52 |
+
// Use fetch() for streaming responses (SSE, chunked text, etc.)
|
| 53 |
+
const response = await base44.functions.fetch("/stream-data", {
|
| 54 |
+
method: "POST",
|
| 55 |
+
headers: { "Content-Type": "application/json" },
|
| 56 |
+
body: JSON.stringify({ prompt: "Tell me a story" })
|
| 57 |
+
});
|
| 58 |
+
|
| 59 |
+
// Read as a stream
|
| 60 |
+
const reader = response.body.getReader();
|
| 61 |
+
const decoder = new TextDecoder();
|
| 62 |
+
while (true) {
|
| 63 |
+
const { done, value } = await reader.read();
|
| 64 |
+
if (done) break;
|
| 65 |
+
console.log(decoder.decode(value));
|
| 66 |
+
}
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
### Custom HTTP Methods (using fetch)
|
| 70 |
+
|
| 71 |
+
```javascript
|
| 72 |
+
// PUT, PATCH, DELETE, or other methods
|
| 73 |
+
const response = await base44.functions.fetch("/my-resource/123", {
|
| 74 |
+
method: "DELETE"
|
| 75 |
+
});
|
| 76 |
+
console.log(response.status); // 204
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
### With File Upload
|
| 80 |
+
|
| 81 |
+
```javascript
|
| 82 |
+
const fileInput = document.querySelector('input[type="file"]');
|
| 83 |
+
const file = fileInput.files[0];
|
| 84 |
+
|
| 85 |
+
// Automatically uses multipart/form-data when File objects present
|
| 86 |
+
const result = await base44.functions.invoke("uploadDocument", {
|
| 87 |
+
file: file,
|
| 88 |
+
category: "invoices"
|
| 89 |
+
});
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
### With Service Role (Backend)
|
| 93 |
+
|
| 94 |
+
```javascript
|
| 95 |
+
// Inside another backend function
|
| 96 |
+
const result = await base44.asServiceRole.functions.invoke("adminTask", {
|
| 97 |
+
userId: "user-123"
|
| 98 |
+
});
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
### Via REST API (curl)
|
| 102 |
+
|
| 103 |
+
Functions can be called via HTTP POST to your app domain:
|
| 104 |
+
|
| 105 |
+
```bash
|
| 106 |
+
curl -X POST "https://<app-domain>/functions/<function-name>" \
|
| 107 |
+
-H "Content-Type: application/json" \
|
| 108 |
+
-d '{"key": "value"}'
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
## Writing Backend Functions
|
| 112 |
+
|
| 113 |
+
Backend functions run on Deno. Must export using `Deno.serve()`.
|
| 114 |
+
|
| 115 |
+
### Required Directory Structure
|
| 116 |
+
|
| 117 |
+
Each function must be in its own subdirectory under `base44/functions/` with a configuration file:
|
| 118 |
+
|
| 119 |
+
```
|
| 120 |
+
base44/
|
| 121 |
+
functions/
|
| 122 |
+
process-order/ # kebab-case directory name
|
| 123 |
+
function.jsonc # required configuration
|
| 124 |
+
index.ts # entry point
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
**function.jsonc:**
|
| 128 |
+
```jsonc
|
| 129 |
+
{
|
| 130 |
+
"name": "process-order",
|
| 131 |
+
"entry": "index.ts"
|
| 132 |
+
}
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
For complete setup and deployment instructions, see [functions-create.md](../../base44-cli/references/functions-create.md) in base44-cli.
|
| 136 |
+
|
| 137 |
+
### Basic Structure
|
| 138 |
+
|
| 139 |
+
```javascript
|
| 140 |
+
// base44/functions/process-order/index.ts
|
| 141 |
+
import { createClientFromRequest } from "npm:@base44/sdk";
|
| 142 |
+
|
| 143 |
+
Deno.serve(async (req) => {
|
| 144 |
+
// Get authenticated client from request
|
| 145 |
+
const base44 = createClientFromRequest(req);
|
| 146 |
+
|
| 147 |
+
// Parse input
|
| 148 |
+
const { orderId, action } = await req.json();
|
| 149 |
+
|
| 150 |
+
// Your logic here
|
| 151 |
+
const order = await base44.entities.Orders.get(orderId);
|
| 152 |
+
|
| 153 |
+
// Return response
|
| 154 |
+
return Response.json({
|
| 155 |
+
success: true,
|
| 156 |
+
order: order
|
| 157 |
+
});
|
| 158 |
+
});
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
### With Service Role Access
|
| 162 |
+
|
| 163 |
+
```javascript
|
| 164 |
+
import { createClientFromRequest } from "npm:@base44/sdk";
|
| 165 |
+
|
| 166 |
+
Deno.serve(async (req) => {
|
| 167 |
+
const base44 = createClientFromRequest(req);
|
| 168 |
+
|
| 169 |
+
// Check user is authenticated
|
| 170 |
+
const user = await base44.auth.me();
|
| 171 |
+
if (!user) {
|
| 172 |
+
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
// Use service role for admin operations
|
| 176 |
+
const allOrders = await base44.asServiceRole.entities.Orders.list();
|
| 177 |
+
|
| 178 |
+
return Response.json({ orders: allOrders });
|
| 179 |
+
});
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
### Using Secrets
|
| 183 |
+
|
| 184 |
+
```javascript
|
| 185 |
+
Deno.serve(async (req) => {
|
| 186 |
+
// Access environment variables (configured in app settings)
|
| 187 |
+
const apiKey = Deno.env.get("STRIPE_API_KEY");
|
| 188 |
+
|
| 189 |
+
const response = await fetch("https://api.stripe.com/v1/charges", {
|
| 190 |
+
headers: {
|
| 191 |
+
"Authorization": `Bearer ${apiKey}`
|
| 192 |
+
}
|
| 193 |
+
});
|
| 194 |
+
|
| 195 |
+
return Response.json(await response.json());
|
| 196 |
+
});
|
| 197 |
+
```
|
| 198 |
+
|
| 199 |
+
### Error Handling
|
| 200 |
+
|
| 201 |
+
```javascript
|
| 202 |
+
import { createClientFromRequest } from "npm:@base44/sdk";
|
| 203 |
+
|
| 204 |
+
Deno.serve(async (req) => {
|
| 205 |
+
try {
|
| 206 |
+
const base44 = createClientFromRequest(req);
|
| 207 |
+
const { orderId } = await req.json();
|
| 208 |
+
|
| 209 |
+
const order = await base44.entities.Orders.get(orderId);
|
| 210 |
+
if (!order) {
|
| 211 |
+
return Response.json(
|
| 212 |
+
{ error: "Order not found" },
|
| 213 |
+
{ status: 404 }
|
| 214 |
+
);
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
return Response.json({ order });
|
| 218 |
+
|
| 219 |
+
} catch (error) {
|
| 220 |
+
return Response.json(
|
| 221 |
+
{ error: error.message },
|
| 222 |
+
{ status: 500 }
|
| 223 |
+
);
|
| 224 |
+
}
|
| 225 |
+
});
|
| 226 |
+
```
|
| 227 |
+
|
| 228 |
+
## Setup Requirements
|
| 229 |
+
|
| 230 |
+
1. Enable Backend Functions in app settings (requires appropriate plan)
|
| 231 |
+
2. Create function files in `/functions` folder
|
| 232 |
+
3. Configure secrets via app dashboard for API keys
|
| 233 |
+
|
| 234 |
+
## Authentication Modes
|
| 235 |
+
|
| 236 |
+
| Mode | Context | Permissions |
|
| 237 |
+
|------|---------|-------------|
|
| 238 |
+
| User | `base44.functions.invoke()` | Runs under calling user's permissions |
|
| 239 |
+
| Service Role | `base44.asServiceRole.functions.invoke()` | Admin-level access |
|
| 240 |
+
|
| 241 |
+
Inside the function, use `createClientFromRequest(req)` to get a client that inherits the caller's auth context.
|
| 242 |
+
|
| 243 |
+
## Type Definitions
|
| 244 |
+
|
| 245 |
+
**How to get typed function names:** The Base44 CLI can generate an augmentation of `FunctionNameRegistry` from your project. For how to run it, use the **base44-cli** skill.
|
| 246 |
+
|
| 247 |
+
```typescript
|
| 248 |
+
/**
|
| 249 |
+
* Registry of function names.
|
| 250 |
+
* Augment this interface to enable autocomplete for function names.
|
| 251 |
+
* Typically populated by the Base44 CLI type generator.
|
| 252 |
+
*/
|
| 253 |
+
interface FunctionNameRegistry {}
|
| 254 |
+
|
| 255 |
+
/**
|
| 256 |
+
* Function name type - uses registry keys if augmented, otherwise string.
|
| 257 |
+
*/
|
| 258 |
+
type FunctionName = keyof FunctionNameRegistry extends never ? string : keyof FunctionNameRegistry;
|
| 259 |
+
|
| 260 |
+
/**
|
| 261 |
+
* Options for functions.fetch(). Uses native fetch options directly.
|
| 262 |
+
*/
|
| 263 |
+
type FunctionsFetchInit = RequestInit;
|
| 264 |
+
|
| 265 |
+
/** Functions module for invoking custom backend functions. */
|
| 266 |
+
interface FunctionsModule {
|
| 267 |
+
/**
|
| 268 |
+
* Invokes a custom backend function by name.
|
| 269 |
+
*
|
| 270 |
+
* If any parameter is a File object, the request will automatically be
|
| 271 |
+
* sent as multipart/form-data. Otherwise, it will be sent as JSON.
|
| 272 |
+
*
|
| 273 |
+
* @param functionName - The name of the function to invoke.
|
| 274 |
+
* @param data - Optional object containing named parameters for the function.
|
| 275 |
+
* @returns Promise resolving to the function's response.
|
| 276 |
+
*/
|
| 277 |
+
invoke(functionName: FunctionName, data?: Record<string, any>): Promise<any>;
|
| 278 |
+
|
| 279 |
+
/**
|
| 280 |
+
* Performs a direct HTTP request to a backend function path and returns the native Response.
|
| 281 |
+
*
|
| 282 |
+
* Use for streaming responses (SSE, chunked text), custom HTTP methods,
|
| 283 |
+
* or when you need raw access to the response.
|
| 284 |
+
*
|
| 285 |
+
* @param path - Function path, e.g. `/streaming_demo` or `/my-function/endpoint`
|
| 286 |
+
* @param init - Optional native fetch options.
|
| 287 |
+
* @returns Promise resolving to a native fetch Response.
|
| 288 |
+
*/
|
| 289 |
+
fetch(path: string, init?: FunctionsFetchInit): Promise<Response>;
|
| 290 |
+
}
|
| 291 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/integrations.md
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Integrations Module
|
| 2 |
+
|
| 3 |
+
Access third-party services via `base44.integrations`.
|
| 4 |
+
|
| 5 |
+
## Types of Integrations
|
| 6 |
+
|
| 7 |
+
1. **Core/Built-in**: AI, email, file uploads (available by default)
|
| 8 |
+
2. **Catalog integrations**: Pre-built connectors from Base44 catalog
|
| 9 |
+
3. **Custom integrations**: Your own OpenAPI-based integrations
|
| 10 |
+
|
| 11 |
+
## Accessing Integrations
|
| 12 |
+
|
| 13 |
+
```javascript
|
| 14 |
+
// Core integrations
|
| 15 |
+
base44.integrations.Core.FunctionName(params)
|
| 16 |
+
|
| 17 |
+
// Custom integrations
|
| 18 |
+
base44.integrations.custom.call(slug, operationId, params)
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
## Core Integrations
|
| 22 |
+
|
| 23 |
+
### InvokeLLM (AI Text Generation)
|
| 24 |
+
|
| 25 |
+
Generate text or structured JSON data using AI models.
|
| 26 |
+
|
| 27 |
+
```javascript
|
| 28 |
+
// Basic prompt - returns string
|
| 29 |
+
const response = await base44.integrations.Core.InvokeLLM({
|
| 30 |
+
prompt: "Summarize this text: ..."
|
| 31 |
+
});
|
| 32 |
+
|
| 33 |
+
// With internet context (uses Google Search, Maps, News)
|
| 34 |
+
const response = await base44.integrations.Core.InvokeLLM({
|
| 35 |
+
prompt: "What's the current weather in NYC?",
|
| 36 |
+
add_context_from_internet: true
|
| 37 |
+
});
|
| 38 |
+
|
| 39 |
+
// Structured JSON response - returns object
|
| 40 |
+
const response = await base44.integrations.Core.InvokeLLM({
|
| 41 |
+
prompt: "Analyze the sentiment of: 'Great product but slow shipping'",
|
| 42 |
+
response_json_schema: {
|
| 43 |
+
type: "object",
|
| 44 |
+
properties: {
|
| 45 |
+
sentiment: { type: "string", enum: ["positive", "negative", "mixed"] },
|
| 46 |
+
score: { type: "number", description: "Score from 1-10" },
|
| 47 |
+
key_points: { type: "array", items: { type: "string" } }
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
});
|
| 51 |
+
// Returns: { sentiment: "mixed", score: 7, key_points: ["great product", "slow shipping"] }
|
| 52 |
+
|
| 53 |
+
// With file attachments (uploaded via UploadFile)
|
| 54 |
+
const response = await base44.integrations.Core.InvokeLLM({
|
| 55 |
+
prompt: "Describe what's in this image",
|
| 56 |
+
file_urls: ["https://...uploaded_image.png"]
|
| 57 |
+
});
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
**Parameters:**
|
| 61 |
+
- `prompt` (string, required): The prompt text to send to the model
|
| 62 |
+
- `add_context_from_internet` (boolean, optional): If true, uses Google Search/Maps/News for real-time context
|
| 63 |
+
- `response_json_schema` (object, optional): JSON schema for structured output
|
| 64 |
+
- `file_urls` (string[], optional): URLs of uploaded files for context
|
| 65 |
+
|
| 66 |
+
### GenerateImage
|
| 67 |
+
|
| 68 |
+
Create AI-generated images from text prompts.
|
| 69 |
+
|
| 70 |
+
```javascript
|
| 71 |
+
const { url } = await base44.integrations.Core.GenerateImage({
|
| 72 |
+
prompt: "A serene mountain landscape with a lake"
|
| 73 |
+
});
|
| 74 |
+
console.log(url); // https://...generated_image.png
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
### SendEmail
|
| 78 |
+
|
| 79 |
+
Send emails to registered users. Every app gets this integration (no plan upgrade required).
|
| 80 |
+
|
| 81 |
+
```javascript
|
| 82 |
+
await base44.integrations.Core.SendEmail({
|
| 83 |
+
to: "user@example.com",
|
| 84 |
+
subject: "Welcome!",
|
| 85 |
+
body: "<h1>Hello</h1><p>Welcome to our app.</p>",
|
| 86 |
+
from_name: "My App" // optional, defaults to app name
|
| 87 |
+
});
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
**Parameters:**
|
| 91 |
+
- `to` (string, required): Recipient email address
|
| 92 |
+
- `subject` (string, required): Email subject line
|
| 93 |
+
- `body` (string, required): Plain text or HTML email body
|
| 94 |
+
- `from_name` (string, optional): Sender name displayed to recipient
|
| 95 |
+
|
| 96 |
+
**Limitations:**
|
| 97 |
+
- 1 credit per email (2 credits with custom domain)
|
| 98 |
+
|
| 99 |
+
### UploadFile (Public)
|
| 100 |
+
|
| 101 |
+
Upload files to public storage.
|
| 102 |
+
|
| 103 |
+
```javascript
|
| 104 |
+
const fileInput = document.querySelector('input[type="file"]');
|
| 105 |
+
const { file_url } = await base44.integrations.Core.UploadFile({
|
| 106 |
+
file: fileInput.files[0]
|
| 107 |
+
});
|
| 108 |
+
console.log(file_url); // https://...uploaded_file.pdf
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
### UploadPrivateFile
|
| 112 |
+
|
| 113 |
+
Upload files to private storage that requires a signed URL to access.
|
| 114 |
+
|
| 115 |
+
```javascript
|
| 116 |
+
const { file_uri } = await base44.integrations.Core.UploadPrivateFile({
|
| 117 |
+
file: fileInput.files[0]
|
| 118 |
+
});
|
| 119 |
+
console.log(file_uri); // "private/user123/document.pdf"
|
| 120 |
+
|
| 121 |
+
// Create a signed URL to access the file
|
| 122 |
+
const { signed_url } = await base44.integrations.Core.CreateFileSignedUrl({
|
| 123 |
+
file_uri,
|
| 124 |
+
expires_in: 3600 // URL expires in 1 hour (default: 300 seconds)
|
| 125 |
+
});
|
| 126 |
+
console.log(signed_url); // Temporary URL to access the private file
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
### CreateFileSignedUrl
|
| 130 |
+
|
| 131 |
+
Generate temporary access links for private files.
|
| 132 |
+
|
| 133 |
+
```javascript
|
| 134 |
+
const { signed_url } = await base44.integrations.Core.CreateFileSignedUrl({
|
| 135 |
+
file_uri: "private/user123/document.pdf",
|
| 136 |
+
expires_in: 7200 // 2 hours
|
| 137 |
+
});
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
**Parameters:**
|
| 141 |
+
- `file_uri` (string, required): URI from UploadPrivateFile
|
| 142 |
+
- `expires_in` (number, optional): Expiration time in seconds (default: 300)
|
| 143 |
+
|
| 144 |
+
### ExtractDataFromUploadedFile
|
| 145 |
+
|
| 146 |
+
Extract structured data from uploaded files using AI.
|
| 147 |
+
|
| 148 |
+
```javascript
|
| 149 |
+
// First upload the file
|
| 150 |
+
const { file_url } = await base44.integrations.Core.UploadFile({ file });
|
| 151 |
+
|
| 152 |
+
// Then extract structured data
|
| 153 |
+
const result = await base44.integrations.Core.ExtractDataFromUploadedFile({
|
| 154 |
+
file_url,
|
| 155 |
+
json_schema: {
|
| 156 |
+
type: "object",
|
| 157 |
+
properties: {
|
| 158 |
+
invoice_number: { type: "string" },
|
| 159 |
+
total_amount: { type: "number" },
|
| 160 |
+
date: { type: "string" },
|
| 161 |
+
vendor_name: { type: "string" }
|
| 162 |
+
}
|
| 163 |
+
}
|
| 164 |
+
});
|
| 165 |
+
console.log(result); // { invoice_number: "INV-12345", total_amount: 1250.00, ... }
|
| 166 |
+
```
|
| 167 |
+
|
| 168 |
+
## Custom Integrations
|
| 169 |
+
|
| 170 |
+
Custom integrations allow workspace administrators to connect any external API by importing an OpenAPI specification. Use `base44.integrations.custom.call()` to invoke them.
|
| 171 |
+
|
| 172 |
+
### Syntax
|
| 173 |
+
|
| 174 |
+
```javascript
|
| 175 |
+
const response = await base44.integrations.custom.call(
|
| 176 |
+
slug, // Integration identifier (set by admin)
|
| 177 |
+
operationId, // Endpoint in "method:path" format (e.g. "get:/contacts", "post:/repos/{owner}/{repo}/issues")
|
| 178 |
+
params // Optional: payload, pathParams, queryParams
|
| 179 |
+
);
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
### Examples
|
| 183 |
+
|
| 184 |
+
```javascript
|
| 185 |
+
// GET request with query params
|
| 186 |
+
const response = await base44.integrations.custom.call(
|
| 187 |
+
"my-crm",
|
| 188 |
+
"get:/contacts",
|
| 189 |
+
{ queryParams: { limit: 10, status: "active" } }
|
| 190 |
+
);
|
| 191 |
+
|
| 192 |
+
// POST request with body
|
| 193 |
+
const response = await base44.integrations.custom.call(
|
| 194 |
+
"my-crm",
|
| 195 |
+
"post:/contacts",
|
| 196 |
+
{ payload: { name: "John Doe", email: "john@example.com" } }
|
| 197 |
+
);
|
| 198 |
+
|
| 199 |
+
// Request with path parameters
|
| 200 |
+
const response = await base44.integrations.custom.call(
|
| 201 |
+
"github",
|
| 202 |
+
"post:/repos/{owner}/{repo}/issues",
|
| 203 |
+
{
|
| 204 |
+
pathParams: { owner: "myorg", repo: "myrepo" },
|
| 205 |
+
payload: { title: "Bug report", body: "Something is broken" }
|
| 206 |
+
}
|
| 207 |
+
);
|
| 208 |
+
```
|
| 209 |
+
|
| 210 |
+
### Response Structure
|
| 211 |
+
|
| 212 |
+
```javascript
|
| 213 |
+
{
|
| 214 |
+
success: true, // Whether external API returned 2xx
|
| 215 |
+
status_code: 200, // HTTP status code
|
| 216 |
+
data: { ... } // Response from external API
|
| 217 |
+
}
|
| 218 |
+
```
|
| 219 |
+
|
| 220 |
+
## Requirements
|
| 221 |
+
|
| 222 |
+
- **Core integrations**: Available on all plans
|
| 223 |
+
- **Catalog/Custom integrations**: Require Builder plan or higher
|
| 224 |
+
|
| 225 |
+
## Type Definitions
|
| 226 |
+
|
| 227 |
+
### Core Integration Parameters
|
| 228 |
+
|
| 229 |
+
```typescript
|
| 230 |
+
/** Parameters for the InvokeLLM function. */
|
| 231 |
+
interface InvokeLLMParams {
|
| 232 |
+
/** The prompt text to send to the model. */
|
| 233 |
+
prompt: string;
|
| 234 |
+
/** If true, uses Google Search/Maps/News for real-time context. */
|
| 235 |
+
add_context_from_internet?: boolean;
|
| 236 |
+
/** JSON schema for structured output. If provided, returns object instead of string. */
|
| 237 |
+
response_json_schema?: object;
|
| 238 |
+
/** File URLs (from UploadFile) to provide as context. */
|
| 239 |
+
file_urls?: string[];
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
/** Parameters for the GenerateImage function. */
|
| 243 |
+
interface GenerateImageParams {
|
| 244 |
+
/** Description of the image to generate. */
|
| 245 |
+
prompt: string;
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
/** Result from GenerateImage. */
|
| 249 |
+
interface GenerateImageResult {
|
| 250 |
+
/** URL of the generated image. */
|
| 251 |
+
url: string;
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
/** Parameters for the UploadFile function. */
|
| 255 |
+
interface UploadFileParams {
|
| 256 |
+
/** The file object to upload. */
|
| 257 |
+
file: File;
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
/** Result from UploadFile. */
|
| 261 |
+
interface UploadFileResult {
|
| 262 |
+
/** URL of the uploaded file. */
|
| 263 |
+
file_url: string;
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
/** Parameters for the SendEmail function. */
|
| 267 |
+
interface SendEmailParams {
|
| 268 |
+
/** Recipient email address. */
|
| 269 |
+
to: string;
|
| 270 |
+
/** Email subject line. */
|
| 271 |
+
subject: string;
|
| 272 |
+
/** Plain text or HTML email body. */
|
| 273 |
+
body: string;
|
| 274 |
+
/** Sender name (defaults to app name). */
|
| 275 |
+
from_name?: string;
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
/** Parameters for ExtractDataFromUploadedFile. */
|
| 279 |
+
interface ExtractDataFromUploadedFileParams {
|
| 280 |
+
/** URL of the uploaded file. */
|
| 281 |
+
file_url: string;
|
| 282 |
+
/** JSON schema defining fields to extract. */
|
| 283 |
+
json_schema: object;
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
/** Parameters for UploadPrivateFile. */
|
| 287 |
+
interface UploadPrivateFileParams {
|
| 288 |
+
/** The file object to upload. */
|
| 289 |
+
file: File;
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
/** Result from UploadPrivateFile. */
|
| 293 |
+
interface UploadPrivateFileResult {
|
| 294 |
+
/** URI of the private file (used for signed URLs). */
|
| 295 |
+
file_uri: string;
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
/** Parameters for CreateFileSignedUrl. */
|
| 299 |
+
interface CreateFileSignedUrlParams {
|
| 300 |
+
/** URI from UploadPrivateFile. */
|
| 301 |
+
file_uri: string;
|
| 302 |
+
/** Expiration time in seconds (default: 300). */
|
| 303 |
+
expires_in?: number;
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
/** Result from CreateFileSignedUrl. */
|
| 307 |
+
interface CreateFileSignedUrlResult {
|
| 308 |
+
/** Temporary signed URL to access the file. */
|
| 309 |
+
signed_url: string;
|
| 310 |
+
}
|
| 311 |
+
```
|
| 312 |
+
|
| 313 |
+
### CoreIntegrations
|
| 314 |
+
|
| 315 |
+
```typescript
|
| 316 |
+
/** Core package containing built-in Base44 integration functions. */
|
| 317 |
+
interface CoreIntegrations {
|
| 318 |
+
InvokeLLM(params: InvokeLLMParams): Promise<string | object>;
|
| 319 |
+
GenerateImage(params: GenerateImageParams): Promise<GenerateImageResult>;
|
| 320 |
+
UploadFile(params: UploadFileParams): Promise<UploadFileResult>;
|
| 321 |
+
SendEmail(params: SendEmailParams): Promise<any>;
|
| 322 |
+
ExtractDataFromUploadedFile(params: ExtractDataFromUploadedFileParams): Promise<object>;
|
| 323 |
+
UploadPrivateFile(params: UploadPrivateFileParams): Promise<UploadPrivateFileResult>;
|
| 324 |
+
CreateFileSignedUrl(params: CreateFileSignedUrlParams): Promise<CreateFileSignedUrlResult>;
|
| 325 |
+
}
|
| 326 |
+
```
|
| 327 |
+
|
| 328 |
+
### Custom Integrations
|
| 329 |
+
|
| 330 |
+
```typescript
|
| 331 |
+
/** Parameters for calling a custom integration method. */
|
| 332 |
+
interface CustomIntegrationCallParams {
|
| 333 |
+
/** Request body payload. */
|
| 334 |
+
payload?: Record<string, any>;
|
| 335 |
+
/** Path parameters to substitute in the URL. For example, { owner: "user", repo: "repo" }. */
|
| 336 |
+
pathParams?: Record<string, string>;
|
| 337 |
+
/** Query string parameters. */
|
| 338 |
+
queryParams?: Record<string, any>;
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
/** Response from a custom integration call. */
|
| 342 |
+
interface CustomIntegrationCallResponse {
|
| 343 |
+
/** Whether the external API returned a 2xx status code. */
|
| 344 |
+
success: boolean;
|
| 345 |
+
/** The HTTP status code from the external API. */
|
| 346 |
+
status_code: number;
|
| 347 |
+
/** The response data from the external API. */
|
| 348 |
+
data: any;
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
/** Module for calling custom pre-configured API integrations. */
|
| 352 |
+
interface CustomIntegrationsModule {
|
| 353 |
+
/**
|
| 354 |
+
* Call a custom integration method.
|
| 355 |
+
* @param slug - The integration's unique identifier (set by workspace admin).
|
| 356 |
+
* @param operationId - The endpoint in "method:path" format (e.g. "get:/contacts", "post:/users/{id}").
|
| 357 |
+
* @param params - Optional payload, pathParams, queryParams.
|
| 358 |
+
*/
|
| 359 |
+
call(slug: string, operationId: string, params?: CustomIntegrationCallParams): Promise<CustomIntegrationCallResponse>;
|
| 360 |
+
}
|
| 361 |
+
```
|
| 362 |
+
|
| 363 |
+
### IntegrationsModule
|
| 364 |
+
|
| 365 |
+
```typescript
|
| 366 |
+
/** Integrations module for calling integration methods. */
|
| 367 |
+
type IntegrationsModule = {
|
| 368 |
+
/** Core package with built-in integrations. */
|
| 369 |
+
Core: CoreIntegrations;
|
| 370 |
+
/** Custom integrations module. */
|
| 371 |
+
custom: CustomIntegrationsModule;
|
| 372 |
+
/** Additional integration packages (dynamic). */
|
| 373 |
+
[packageName: string]: any;
|
| 374 |
+
};
|
| 375 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/sso.md
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SSO Module
|
| 2 |
+
|
| 3 |
+
Single Sign-On (SSO) support for authenticating Base44 users with external systems. Available via `base44.asServiceRole.sso`.
|
| 4 |
+
|
| 5 |
+
> **Backend only**: This module requires service role access and can only be used in Base44-hosted backend functions.
|
| 6 |
+
|
| 7 |
+
## Methods
|
| 8 |
+
|
| 9 |
+
| Method | Signature | Description |
|
| 10 |
+
|--------|-----------|-------------|
|
| 11 |
+
| `getAccessToken(userId)` | `Promise<SsoAccessTokenResponse>` | Get an SSO access token for a specific user |
|
| 12 |
+
|
| 13 |
+
## Examples
|
| 14 |
+
|
| 15 |
+
### Get SSO Access Token
|
| 16 |
+
|
| 17 |
+
```javascript
|
| 18 |
+
import { createClientFromRequest } from "npm:@base44/sdk";
|
| 19 |
+
|
| 20 |
+
Deno.serve(async (req) => {
|
| 21 |
+
const base44 = createClientFromRequest(req);
|
| 22 |
+
|
| 23 |
+
// Get the current user
|
| 24 |
+
const user = await base44.auth.me();
|
| 25 |
+
if (!user) {
|
| 26 |
+
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
// Get SSO access token for this user
|
| 30 |
+
const { access_token } = await base44.asServiceRole.sso.getAccessToken(user.id);
|
| 31 |
+
|
| 32 |
+
// Use the token to authenticate with an external system
|
| 33 |
+
return Response.json({ ssoToken: access_token });
|
| 34 |
+
});
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
### Get Token for a Specific User (Service Role)
|
| 38 |
+
|
| 39 |
+
```javascript
|
| 40 |
+
Deno.serve(async (req) => {
|
| 41 |
+
const base44 = createClientFromRequest(req);
|
| 42 |
+
const { userId } = await req.json();
|
| 43 |
+
|
| 44 |
+
// Get SSO token for any user (service role has access to all users)
|
| 45 |
+
const { access_token } = await base44.asServiceRole.sso.getAccessToken(userId);
|
| 46 |
+
|
| 47 |
+
return Response.json({ token: access_token });
|
| 48 |
+
});
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
## Use Cases
|
| 52 |
+
|
| 53 |
+
- Authenticating Base44 users with external SaaS tools (e.g., Okta, Azure AD)
|
| 54 |
+
- Building SSO bridges between Base44 and third-party systems
|
| 55 |
+
- Generating tokens for backend-to-backend authenticated calls
|
| 56 |
+
|
| 57 |
+
## Type Definitions
|
| 58 |
+
|
| 59 |
+
```typescript
|
| 60 |
+
/** Response from the SSO access token endpoint. */
|
| 61 |
+
interface SsoAccessTokenResponse {
|
| 62 |
+
/** The SSO access token for the specified user. */
|
| 63 |
+
access_token: string;
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
/** SSO module for managing SSO authentication (service role only). */
|
| 67 |
+
interface SsoModule {
|
| 68 |
+
/**
|
| 69 |
+
* Gets an SSO access token for a specific user.
|
| 70 |
+
* @param userid - The Base44 user ID to get the SSO token for.
|
| 71 |
+
* @returns Promise resolving to the SSO access token response.
|
| 72 |
+
*/
|
| 73 |
+
getAccessToken(userid: string): Promise<SsoAccessTokenResponse>;
|
| 74 |
+
}
|
| 75 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-sdk/references/users.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Users Module
|
| 2 |
+
|
| 3 |
+
Invite users to the app via `base44.users`.
|
| 4 |
+
|
| 5 |
+
## Contents
|
| 6 |
+
- [Methods](#methods)
|
| 7 |
+
- [Examples](#examples) (Invite User)
|
| 8 |
+
- [Roles](#roles)
|
| 9 |
+
- [Notes](#notes)
|
| 10 |
+
|
| 11 |
+
## Methods
|
| 12 |
+
|
| 13 |
+
| Method | Signature | Description |
|
| 14 |
+
|--------|-----------|-------------|
|
| 15 |
+
| `inviteUser(user_email, role)` | `Promise<any>` | Invite a user to the app |
|
| 16 |
+
|
| 17 |
+
## Examples
|
| 18 |
+
|
| 19 |
+
### Invite User
|
| 20 |
+
|
| 21 |
+
```javascript
|
| 22 |
+
// Invite a user with "user" role
|
| 23 |
+
await base44.users.inviteUser("newuser@example.com", "user");
|
| 24 |
+
|
| 25 |
+
// Invite an admin
|
| 26 |
+
await base44.users.inviteUser("admin@example.com", "admin");
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
### Invite Multiple Users
|
| 30 |
+
|
| 31 |
+
```javascript
|
| 32 |
+
const usersToInvite = [
|
| 33 |
+
{ email: "user1@example.com", role: "user" },
|
| 34 |
+
{ email: "user2@example.com", role: "user" },
|
| 35 |
+
{ email: "manager@example.com", role: "admin" }
|
| 36 |
+
];
|
| 37 |
+
|
| 38 |
+
for (const user of usersToInvite) {
|
| 39 |
+
await base44.users.inviteUser(user.email, user.role);
|
| 40 |
+
console.log(`Invited ${user.email} as ${user.role}`);
|
| 41 |
+
}
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
## Roles
|
| 45 |
+
|
| 46 |
+
The `role` parameter must be one of:
|
| 47 |
+
|
| 48 |
+
| Role | Description |
|
| 49 |
+
|------|-------------|
|
| 50 |
+
| `"user"` | Standard user with default permissions |
|
| 51 |
+
| `"admin"` | Administrator with elevated permissions |
|
| 52 |
+
|
| 53 |
+
**Note:** Only `"user"` and `"admin"` are valid role values. An error will be thrown if you pass any other value.
|
| 54 |
+
|
| 55 |
+
## Notes
|
| 56 |
+
|
| 57 |
+
- **Email invitation**: The invited user receives an email with a link to join the app
|
| 58 |
+
- **Duplicate handling**: Inviting an existing user will re-send the invitation
|
| 59 |
+
- **Also available in auth**: `base44.auth.inviteUser()` provides the same functionality
|
| 60 |
+
- **Role validation**: Only `"user"` or `"admin"` are accepted
|
| 61 |
+
|
| 62 |
+
```javascript
|
| 63 |
+
// These are equivalent:
|
| 64 |
+
await base44.users.inviteUser("newuser@example.com", "user");
|
| 65 |
+
await base44.auth.inviteUser("newuser@example.com", "user");
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
## Type Definitions
|
| 69 |
+
|
| 70 |
+
```typescript
|
| 71 |
+
/** Users module for inviting users to the app. */
|
| 72 |
+
interface UsersModule {
|
| 73 |
+
/**
|
| 74 |
+
* Invite a user to the application.
|
| 75 |
+
* @param user_email - User's email address.
|
| 76 |
+
* @param role - User's role ('user' or 'admin').
|
| 77 |
+
* @returns Promise resolving when the invitation is sent.
|
| 78 |
+
* @throws Error if role is not 'user' or 'admin'.
|
| 79 |
+
*/
|
| 80 |
+
inviteUser(user_email: string, role: "user" | "admin"): Promise<any>;
|
| 81 |
+
}
|
| 82 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-troubleshooter/agents/openai.yaml
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
interface:
|
| 2 |
+
display_name: "Base44 Troubleshooter"
|
| 3 |
+
short_description: "Debug Base44 production issues with function logs"
|
| 4 |
+
default_prompt: "Use Base44 troubleshooting guidance to inspect logs and diagnose this production issue."
|
data/.codex/.codex/.tmp/plugins/plugins/base44/skills/base44-troubleshooter/references/project-logs.md
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# base44 logs
|
| 2 |
+
|
| 3 |
+
Fetch function logs for this app.
|
| 4 |
+
|
| 5 |
+
## Syntax
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
npx base44 logs [options]
|
| 9 |
+
```
|
| 10 |
+
|
| 11 |
+
## Options
|
| 12 |
+
|
| 13 |
+
| Option | Description | Required |
|
| 14 |
+
|--------|-------------|----------|
|
| 15 |
+
| `--function <names>` | Filter by function name(s), comma-separated. If omitted, fetches logs for all project functions | No |
|
| 16 |
+
| `--since <datetime>` | Show logs from this time (ISO format) | No |
|
| 17 |
+
| `--until <datetime>` | Show logs until this time (ISO format) | No |
|
| 18 |
+
| `--level <level>` | Filter by log level: `log`, `info`, `warn`, `error`, `debug` | No |
|
| 19 |
+
| `-n, --limit <n>` | Number of results to return (1-1000, default: 50) | No |
|
| 20 |
+
| `--order <order>` | Sort order: `asc` or `desc` (default: `desc`) | No |
|
| 21 |
+
|
| 22 |
+
## Examples
|
| 23 |
+
|
| 24 |
+
```bash
|
| 25 |
+
# Fetch logs for all project functions (last 50 entries)
|
| 26 |
+
npx base44 logs
|
| 27 |
+
|
| 28 |
+
# Fetch only errors
|
| 29 |
+
npx base44 logs --level error
|
| 30 |
+
|
| 31 |
+
# Fetch logs for a specific function
|
| 32 |
+
npx base44 logs --function my-function
|
| 33 |
+
|
| 34 |
+
# Fetch logs for multiple functions
|
| 35 |
+
npx base44 logs --function send-email,process-payment
|
| 36 |
+
|
| 37 |
+
# Fetch logs since a specific time
|
| 38 |
+
npx base44 logs --since 2024-01-15T10:00:00
|
| 39 |
+
|
| 40 |
+
# Fetch logs within a time range
|
| 41 |
+
npx base44 logs --since 2024-01-15T10:00:00 --until 2024-01-15T12:00:00
|
| 42 |
+
|
| 43 |
+
# Fetch last 100 log entries in ascending order
|
| 44 |
+
npx base44 logs -n 100 --order asc
|
| 45 |
+
|
| 46 |
+
# Last 10 errors for a specific function
|
| 47 |
+
npx base44 logs --function myFunction --level error --limit 10
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
## Notes
|
| 51 |
+
|
| 52 |
+
- **Authentication required.** You must be logged in before fetching logs.
|
| 53 |
+
- **Project context required.** Must be run from the project directory (where `base44/.app.jsonc` exists).
|
| 54 |
+
- When multiple functions are specified, logs are merged and sorted by timestamp.
|
| 55 |
+
- If `--function` is omitted, logs are fetched for **all functions** defined in `base44/config.jsonc`.
|
| 56 |
+
- The `--limit` applies after merging logs from all specified functions.
|
| 57 |
+
- The `--since` and `--until` values are normalized to UTC if no timezone is provided (appends `Z`).
|
data/.codex/.codex/.tmp/plugins/plugins/carta-crm/.codex-plugin/plugin.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "carta-crm",
|
| 3 |
+
"version": "1.0.3",
|
| 4 |
+
"description": "Carta CRM helps investment teams stay on top of deal flow by keeping deals, companies, and relationships in...",
|
| 5 |
+
"author": {
|
| 6 |
+
"name": "Carta Inc.",
|
| 7 |
+
"url": "https://carta.com"
|
| 8 |
+
},
|
| 9 |
+
"repository": "https://github.com/openai/plugins",
|
| 10 |
+
"license": "MIT",
|
| 11 |
+
"keywords": [],
|
| 12 |
+
"apps": "./.app.json",
|
| 13 |
+
"interface": {
|
| 14 |
+
"displayName": "Carta CRM",
|
| 15 |
+
"shortDescription": "Carta CRM helps investment teams stay on top of deal flow by keeping deals, companies, and relationships in...",
|
| 16 |
+
"longDescription": "Carta CRM helps investment teams stay on top of deal flow by keeping deals, companies, and relationships in one place. Track opportunities through each stage, capture meeting notes and key takeaways alongside the right deal or contact, and quickly find past context when you need it.",
|
| 17 |
+
"developerName": "Carta Inc.",
|
| 18 |
+
"category": "Business & Operations",
|
| 19 |
+
"capabilities": [],
|
| 20 |
+
"defaultPrompt": [
|
| 21 |
+
"Find the latest relationship context in Carta CRM"
|
| 22 |
+
],
|
| 23 |
+
"screenshots": [],
|
| 24 |
+
"websiteURL": "https://carta.com",
|
| 25 |
+
"privacyPolicyURL": "https://carta.com/legal/privacy/privacy-policy/",
|
| 26 |
+
"termsOfServiceURL": "https://carta.com/legal/terms-agreements/terms-service/",
|
| 27 |
+
"composerIcon": "./assets/logo.png",
|
| 28 |
+
"logo": "./assets/logo.png",
|
| 29 |
+
"logoDark": "./assets/logo-dark.png"
|
| 30 |
+
},
|
| 31 |
+
"homepage": "https://carta.com"
|
| 32 |
+
}
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/.codex-plugin/plugin.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "cloudflare",
|
| 3 |
+
"version": "0.1.2",
|
| 4 |
+
"description": "Cloudflare platform plugin with curated skills for Workers, Wrangler, and Agents SDK plus the official Cloudflare API MCP server.",
|
| 5 |
+
"author": {
|
| 6 |
+
"name": "Cloudflare",
|
| 7 |
+
"url": "https://workers.cloudflare.com/"
|
| 8 |
+
},
|
| 9 |
+
"homepage": "https://workers.cloudflare.com/",
|
| 10 |
+
"repository": "https://github.com/openai/plugins",
|
| 11 |
+
"license": "MIT",
|
| 12 |
+
"keywords": [
|
| 13 |
+
"cloudflare",
|
| 14 |
+
"workflow",
|
| 15 |
+
"deployment",
|
| 16 |
+
"edge-functions",
|
| 17 |
+
"edge",
|
| 18 |
+
"analytics",
|
| 19 |
+
"wrangler",
|
| 20 |
+
"agents-sdk",
|
| 21 |
+
"serverless",
|
| 22 |
+
"ai-gateway"
|
| 23 |
+
],
|
| 24 |
+
"skills": "./skills/",
|
| 25 |
+
"mcpServers": "./.mcp.json",
|
| 26 |
+
"interface": {
|
| 27 |
+
"displayName": "Cloudflare",
|
| 28 |
+
"shortDescription": "Cloudflare platform guidance with official MCP",
|
| 29 |
+
"longDescription": "Bring Cloudflare platform guidance into Codex with curated skills for the broader platform, Wrangler CLI, and the Agents SDK, plus the official Cloudflare API MCP server for authenticated access to live account data and workflows across Workers, Pages, storage, AI, networking, security, and analytics services.",
|
| 30 |
+
"developerName": "Cloudflare",
|
| 31 |
+
"category": "Developer Tools",
|
| 32 |
+
"capabilities": [
|
| 33 |
+
"Interactive",
|
| 34 |
+
"Write"
|
| 35 |
+
],
|
| 36 |
+
"websiteURL": "https://workers.cloudflare.com/",
|
| 37 |
+
"privacyPolicyURL": "https://www.cloudflare.com/privacypolicy/",
|
| 38 |
+
"termsOfServiceURL": "https://www.cloudflare.com/website-terms/",
|
| 39 |
+
"defaultPrompt": [
|
| 40 |
+
"Help me choose the right Cloudflare product, configure Wrangler, and use Cloudflare MCP to inspect or deploy this project"
|
| 41 |
+
],
|
| 42 |
+
"composerIcon": "./assets/cloudflare-small.svg",
|
| 43 |
+
"logo": "./assets/cloudflare.png",
|
| 44 |
+
"screenshots": [],
|
| 45 |
+
"brandColor": "#F48120"
|
| 46 |
+
}
|
| 47 |
+
}
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/assets/cloudflare-small.svg
ADDED
|
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/commands/build-agent.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
description: Build an AI agent on Cloudflare using the Agents SDK
|
| 3 |
+
argument-hint: [agent-description]
|
| 4 |
+
allowed-tools: [Read, Glob, Grep, Bash, Write, Edit, WebFetch]
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
# Build AI Agent on Cloudflare
|
| 8 |
+
|
| 9 |
+
This command helps you build AI agents using the Cloudflare Agents SDK with state management, real-time WebSockets, scheduled tasks, and tool integration.
|
| 10 |
+
|
| 11 |
+
## Arguments
|
| 12 |
+
|
| 13 |
+
The user invoked this command with: $ARGUMENTS
|
| 14 |
+
|
| 15 |
+
## Instructions
|
| 16 |
+
|
| 17 |
+
When this command is invoked:
|
| 18 |
+
|
| 19 |
+
1. Read the skill file at `skills/building-ai-agent-on-cloudflare/SKILL.md` for core guidance
|
| 20 |
+
2. Reference `skills/building-ai-agent-on-cloudflare/references/examples.md` for templates
|
| 21 |
+
3. Use `skills/building-ai-agent-on-cloudflare/references/agent-patterns.md` for tool calling and patterns
|
| 22 |
+
4. Use `skills/building-ai-agent-on-cloudflare/references/state-patterns.md` for state management
|
| 23 |
+
5. Consult `skills/building-ai-agent-on-cloudflare/references/troubleshooting.md` for common issues
|
| 24 |
+
|
| 25 |
+
## Capabilities
|
| 26 |
+
|
| 27 |
+
- Stateful AI agents with persistent memory
|
| 28 |
+
- Real-time WebSocket communication
|
| 29 |
+
- Scheduled tasks and cron jobs
|
| 30 |
+
- Tool integration and function calling
|
| 31 |
+
- Multi-agent orchestration
|
| 32 |
+
- RAG (Retrieval Augmented Generation) patterns
|
| 33 |
+
|
| 34 |
+
## Example Usage
|
| 35 |
+
|
| 36 |
+
```
|
| 37 |
+
/cloudflare:build-agent a customer support chatbot
|
| 38 |
+
/cloudflare:build-agent real-time coding assistant with WebSocket
|
| 39 |
+
/cloudflare:build-agent multi-agent workflow orchestrator
|
| 40 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/commands/build-mcp.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
description: Build a remote MCP server on Cloudflare with tools and OAuth
|
| 3 |
+
argument-hint: [mcp-description]
|
| 4 |
+
allowed-tools: [Read, Glob, Grep, Bash, Write, Edit, WebFetch]
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
# Build MCP Server on Cloudflare
|
| 8 |
+
|
| 9 |
+
This command helps you build remote Model Context Protocol (MCP) servers on Cloudflare with tools, OAuth authentication, and production deployment.
|
| 10 |
+
|
| 11 |
+
## Arguments
|
| 12 |
+
|
| 13 |
+
The user invoked this command with: $ARGUMENTS
|
| 14 |
+
|
| 15 |
+
## Instructions
|
| 16 |
+
|
| 17 |
+
When this command is invoked:
|
| 18 |
+
|
| 19 |
+
1. Read the skill file at `skills/building-mcp-server-on-cloudflare/SKILL.md` for core guidance
|
| 20 |
+
2. Reference `skills/building-mcp-server-on-cloudflare/references/examples.md` for official templates
|
| 21 |
+
3. Use `skills/building-mcp-server-on-cloudflare/references/oauth-setup.md` for security and OAuth
|
| 22 |
+
4. Consult `skills/building-mcp-server-on-cloudflare/references/troubleshooting.md` for common issues
|
| 23 |
+
|
| 24 |
+
## Capabilities
|
| 25 |
+
|
| 26 |
+
- Remote MCP server deployment on Cloudflare Workers
|
| 27 |
+
- OAuth 2.0 authentication setup
|
| 28 |
+
- Tool definition and implementation
|
| 29 |
+
- Production-ready deployment patterns
|
| 30 |
+
- Integration with Codex and other MCP clients
|
| 31 |
+
|
| 32 |
+
## Example Usage
|
| 33 |
+
|
| 34 |
+
```
|
| 35 |
+
/cloudflare:build-mcp a GitHub integration server
|
| 36 |
+
/cloudflare:build-mcp database query tool with OAuth
|
| 37 |
+
/cloudflare:build-mcp file management MCP server
|
| 38 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/LICENSE.txt
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf of
|
| 171 |
+
any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don\'t include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/SKILL.md
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: agents-sdk
|
| 3 |
+
description: Build AI agents on Cloudflare Workers using the Agents SDK. Load when creating stateful agents, durable workflows, real-time WebSocket apps, scheduled tasks, MCP servers, or chat applications. Covers Agent class, state management, callable RPC, Workflows integration, and React hooks. Biases towards retrieval from Cloudflare docs over pre-trained knowledge.
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
# Cloudflare Agents SDK
|
| 7 |
+
|
| 8 |
+
Your knowledge of the Agents SDK may be outdated. **Prefer retrieval over pre-training** for any Agents SDK task.
|
| 9 |
+
|
| 10 |
+
## Retrieval Sources
|
| 11 |
+
|
| 12 |
+
Fetch current docs from `https://github.com/cloudflare/agents/tree/main/docs` before implementing.
|
| 13 |
+
|
| 14 |
+
| Topic | Doc | Use for |
|
| 15 |
+
|-------|-----|---------|
|
| 16 |
+
| Getting started | `docs/getting-started.md` | First agent, project setup |
|
| 17 |
+
| State | `docs/state.md` | `setState`, `validateStateChange`, persistence |
|
| 18 |
+
| Routing | `docs/routing.md` | URL patterns, `routeAgentRequest`, `basePath` |
|
| 19 |
+
| Callable methods | `docs/callable-methods.md` | `@callable`, RPC, streaming, timeouts |
|
| 20 |
+
| Scheduling | `docs/scheduling.md` | `schedule()`, `scheduleEvery()`, cron |
|
| 21 |
+
| Workflows | `docs/workflows.md` | `AgentWorkflow`, durable multi-step tasks |
|
| 22 |
+
| HTTP/WebSockets | `docs/http-websockets.md` | Lifecycle hooks, hibernation |
|
| 23 |
+
| Email | `docs/email.md` | Email routing, secure reply resolver |
|
| 24 |
+
| MCP client | `docs/mcp-client.md` | Connecting to MCP servers |
|
| 25 |
+
| MCP server | `docs/mcp-servers.md` | Building MCP servers with `McpAgent` |
|
| 26 |
+
| Client SDK | `docs/client-sdk.md` | `useAgent`, `useAgentChat`, React hooks |
|
| 27 |
+
| Human-in-the-loop | `docs/human-in-the-loop.md` | Approval flows, pausing workflows |
|
| 28 |
+
| Resumable streaming | `docs/resumable-streaming.md` | Stream recovery on disconnect |
|
| 29 |
+
|
| 30 |
+
Cloudflare docs: https://developers.cloudflare.com/agents/
|
| 31 |
+
|
| 32 |
+
## Capabilities
|
| 33 |
+
|
| 34 |
+
The Agents SDK provides:
|
| 35 |
+
|
| 36 |
+
- **Persistent state** - SQLite-backed, auto-synced to clients
|
| 37 |
+
- **Callable RPC** - `@callable()` methods invoked over WebSocket
|
| 38 |
+
- **Scheduling** - One-time, recurring (`scheduleEvery`), and cron tasks
|
| 39 |
+
- **Workflows** - Durable multi-step background processing via `AgentWorkflow`
|
| 40 |
+
- **MCP integration** - Connect to MCP servers or build your own with `McpAgent`
|
| 41 |
+
- **Email handling** - Receive and reply to emails with secure routing
|
| 42 |
+
- **Streaming chat** - `AIChatAgent` with resumable streams
|
| 43 |
+
- **React hooks** - `useAgent`, `useAgentChat` for client apps
|
| 44 |
+
|
| 45 |
+
## FIRST: Verify Installation
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
npm ls agents # Should show agents package
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
If not installed:
|
| 52 |
+
```bash
|
| 53 |
+
npm install agents
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
## Wrangler Configuration
|
| 57 |
+
|
| 58 |
+
```jsonc
|
| 59 |
+
{
|
| 60 |
+
"durable_objects": {
|
| 61 |
+
"bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
|
| 62 |
+
},
|
| 63 |
+
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]
|
| 64 |
+
}
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
## Agent Class
|
| 68 |
+
|
| 69 |
+
```typescript
|
| 70 |
+
import { Agent, routeAgentRequest, callable } from "agents";
|
| 71 |
+
|
| 72 |
+
type State = { count: number };
|
| 73 |
+
|
| 74 |
+
export class Counter extends Agent<Env, State> {
|
| 75 |
+
initialState = { count: 0 };
|
| 76 |
+
|
| 77 |
+
// Validation hook - runs before state persists (sync, throwing rejects the update)
|
| 78 |
+
validateStateChange(nextState: State, source: Connection | "server") {
|
| 79 |
+
if (nextState.count < 0) throw new Error("Count cannot be negative");
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
// Notification hook - runs after state persists (async, non-blocking)
|
| 83 |
+
onStateUpdate(state: State, source: Connection | "server") {
|
| 84 |
+
console.log("State updated:", state);
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
@callable()
|
| 88 |
+
increment() {
|
| 89 |
+
this.setState({ count: this.state.count + 1 });
|
| 90 |
+
return this.state.count;
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
export default {
|
| 95 |
+
fetch: (req, env) => routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 })
|
| 96 |
+
};
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
## Routing
|
| 100 |
+
|
| 101 |
+
Requests route to `/agents/{agent-name}/{instance-name}`:
|
| 102 |
+
|
| 103 |
+
| Class | URL |
|
| 104 |
+
|-------|-----|
|
| 105 |
+
| `Counter` | `/agents/counter/user-123` |
|
| 106 |
+
| `ChatRoom` | `/agents/chat-room/lobby` |
|
| 107 |
+
|
| 108 |
+
Client: `useAgent({ agent: "Counter", name: "user-123" })`
|
| 109 |
+
|
| 110 |
+
## Core APIs
|
| 111 |
+
|
| 112 |
+
| Task | API |
|
| 113 |
+
|------|-----|
|
| 114 |
+
| Read state | `this.state.count` |
|
| 115 |
+
| Write state | `this.setState({ count: 1 })` |
|
| 116 |
+
| SQL query | `` this.sql`SELECT * FROM users WHERE id = ${id}` `` |
|
| 117 |
+
| Schedule (delay) | `await this.schedule(60, "task", payload)` |
|
| 118 |
+
| Schedule (cron) | `await this.schedule("0 * * * *", "task", payload)` |
|
| 119 |
+
| Schedule (interval) | `await this.scheduleEvery(30, "poll")` |
|
| 120 |
+
| RPC method | `@callable() myMethod() { ... }` |
|
| 121 |
+
| Streaming RPC | `@callable({ streaming: true }) stream(res) { ... }` |
|
| 122 |
+
| Start workflow | `await this.runWorkflow("ProcessingWorkflow", params)` |
|
| 123 |
+
|
| 124 |
+
## React Client
|
| 125 |
+
|
| 126 |
+
```tsx
|
| 127 |
+
import { useAgent } from "agents/react";
|
| 128 |
+
|
| 129 |
+
function App() {
|
| 130 |
+
const [state, setLocalState] = useState({ count: 0 });
|
| 131 |
+
|
| 132 |
+
const agent = useAgent({
|
| 133 |
+
agent: "Counter",
|
| 134 |
+
name: "my-instance",
|
| 135 |
+
onStateUpdate: (newState) => setLocalState(newState),
|
| 136 |
+
onIdentity: (name, agentType) => console.log(`Connected to ${name}`)
|
| 137 |
+
});
|
| 138 |
+
|
| 139 |
+
return (
|
| 140 |
+
<button onClick={() => agent.setState({ count: state.count + 1 })}>
|
| 141 |
+
Count: {state.count}
|
| 142 |
+
</button>
|
| 143 |
+
);
|
| 144 |
+
}
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
## References
|
| 148 |
+
|
| 149 |
+
- **[references/workflows.md](references/workflows.md)** - Durable Workflows integration
|
| 150 |
+
- **[references/callable.md](references/callable.md)** - RPC methods, streaming, timeouts
|
| 151 |
+
- **[references/state-scheduling.md](references/state-scheduling.md)** - State persistence, scheduling
|
| 152 |
+
- **[references/streaming-chat.md](references/streaming-chat.md)** - AIChatAgent, resumable streams
|
| 153 |
+
- **[references/mcp.md](references/mcp.md)** - MCP server integration
|
| 154 |
+
- **[references/email.md](references/email.md)** - Email routing and handling
|
| 155 |
+
- **[references/codemode.md](references/codemode.md)** - Code Mode (experimental)
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/agents/openai.yaml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
interface:
|
| 2 |
+
display_name: "Agents SDK"
|
| 3 |
+
short_description: "Build stateful agents on Cloudflare Workers"
|
| 4 |
+
icon_small: "./assets/cloudflare-small.svg"
|
| 5 |
+
icon_large: "./assets/cloudflare.png"
|
| 6 |
+
default_prompt: "Use the Cloudflare Agents SDK to design or implement this agent on Workers with the right state, routing, and workflow patterns."
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/assets/cloudflare-small.svg
ADDED
|
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/callable.md
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Callable Methods
|
| 2 |
+
|
| 3 |
+
Fetch `docs/callable-methods.md` from `https://github.com/cloudflare/agents/tree/main/docs` for complete documentation.
|
| 4 |
+
|
| 5 |
+
## Overview
|
| 6 |
+
|
| 7 |
+
`@callable()` exposes agent methods to clients via WebSocket RPC.
|
| 8 |
+
|
| 9 |
+
```typescript
|
| 10 |
+
import { Agent, callable } from "agents";
|
| 11 |
+
|
| 12 |
+
export class MyAgent extends Agent<Env, State> {
|
| 13 |
+
@callable()
|
| 14 |
+
async greet(name: string): Promise<string> {
|
| 15 |
+
return `Hello, ${name}!`;
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
@callable()
|
| 19 |
+
async processData(data: unknown): Promise<Result> {
|
| 20 |
+
// Long-running work
|
| 21 |
+
return result;
|
| 22 |
+
}
|
| 23 |
+
}
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
## Client Usage
|
| 27 |
+
|
| 28 |
+
```typescript
|
| 29 |
+
// Basic call
|
| 30 |
+
const greeting = await agent.call("greet", ["World"]);
|
| 31 |
+
|
| 32 |
+
// With timeout
|
| 33 |
+
const result = await agent.call("processData", [data], {
|
| 34 |
+
timeout: 5000 // 5 second timeout
|
| 35 |
+
});
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
## Streaming Responses
|
| 39 |
+
|
| 40 |
+
```typescript
|
| 41 |
+
import { Agent, callable, StreamingResponse } from "agents";
|
| 42 |
+
|
| 43 |
+
export class MyAgent extends Agent<Env, State> {
|
| 44 |
+
@callable({ streaming: true })
|
| 45 |
+
async streamResults(stream: StreamingResponse, query: string) {
|
| 46 |
+
for await (const item of fetchResults(query)) {
|
| 47 |
+
stream.send(JSON.stringify(item));
|
| 48 |
+
}
|
| 49 |
+
stream.close();
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
@callable({ streaming: true })
|
| 53 |
+
async streamWithError(stream: StreamingResponse) {
|
| 54 |
+
try {
|
| 55 |
+
// ... work
|
| 56 |
+
} catch (error) {
|
| 57 |
+
stream.error(error.message); // Signal error to client
|
| 58 |
+
return;
|
| 59 |
+
}
|
| 60 |
+
stream.close();
|
| 61 |
+
}
|
| 62 |
+
}
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
Client with streaming:
|
| 66 |
+
|
| 67 |
+
```typescript
|
| 68 |
+
await agent.call("streamResults", ["search term"], {
|
| 69 |
+
stream: {
|
| 70 |
+
onChunk: (data) => console.log("Chunk:", data),
|
| 71 |
+
onDone: () => console.log("Complete"),
|
| 72 |
+
onError: (error) => console.error("Error:", error)
|
| 73 |
+
}
|
| 74 |
+
});
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
## Introspection
|
| 78 |
+
|
| 79 |
+
```typescript
|
| 80 |
+
// Get list of callable methods on an agent
|
| 81 |
+
const methods = await agent.call("getCallableMethods", []);
|
| 82 |
+
// Returns: ["greet", "processData", "streamResults", ...]
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
## When to Use
|
| 86 |
+
|
| 87 |
+
| Scenario | Use |
|
| 88 |
+
|----------|-----|
|
| 89 |
+
| Browser/mobile calling agent | `@callable()` |
|
| 90 |
+
| External service calling agent | `@callable()` |
|
| 91 |
+
| Worker calling agent (same codebase) | DO RPC directly |
|
| 92 |
+
| Agent calling another agent | `getAgentByName()` + DO RPC |
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/codemode.md
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Code Mode (Experimental)
|
| 2 |
+
|
| 3 |
+
Code Mode generates executable JavaScript instead of making individual tool calls. This significantly reduces token usage and enables complex multi-tool workflows.
|
| 4 |
+
|
| 5 |
+
## Why Code Mode?
|
| 6 |
+
|
| 7 |
+
Traditional tool calling:
|
| 8 |
+
- One tool call per LLM request
|
| 9 |
+
- Multiple round-trips for chained operations
|
| 10 |
+
- High token usage for complex workflows
|
| 11 |
+
|
| 12 |
+
Code Mode:
|
| 13 |
+
- LLM generates code that orchestrates multiple tools
|
| 14 |
+
- Single execution for complex workflows
|
| 15 |
+
- Self-debugging and error recovery
|
| 16 |
+
- Ideal for MCP server orchestration
|
| 17 |
+
|
| 18 |
+
## Setup
|
| 19 |
+
|
| 20 |
+
### 1. Wrangler Config
|
| 21 |
+
|
| 22 |
+
```jsonc
|
| 23 |
+
{
|
| 24 |
+
"name": "my-agent-worker",
|
| 25 |
+
"compatibility_flags": ["experimental", "enable_ctx_exports"],
|
| 26 |
+
"durable_objects": {
|
| 27 |
+
// "class_name" must match your Agent class name exactly
|
| 28 |
+
"bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
|
| 29 |
+
},
|
| 30 |
+
"migrations": [
|
| 31 |
+
// Required: list all Agent classes for SQLite storage
|
| 32 |
+
{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }
|
| 33 |
+
],
|
| 34 |
+
"services": [
|
| 35 |
+
{
|
| 36 |
+
"binding": "globalOutbound",
|
| 37 |
+
// "service" must match "name" above
|
| 38 |
+
"service": "my-agent-worker",
|
| 39 |
+
"entrypoint": "globalOutbound"
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"binding": "CodeModeProxy",
|
| 43 |
+
"service": "my-agent-worker",
|
| 44 |
+
"entrypoint": "CodeModeProxy"
|
| 45 |
+
}
|
| 46 |
+
],
|
| 47 |
+
"worker_loaders": [{ "binding": "LOADER" }]
|
| 48 |
+
}
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
### 2. Export Required Classes
|
| 52 |
+
|
| 53 |
+
```typescript
|
| 54 |
+
// Export the proxy for tool execution (required for codemode)
|
| 55 |
+
export { CodeModeProxy } from "@cloudflare/codemode/ai";
|
| 56 |
+
|
| 57 |
+
// Define outbound fetch handler for security filtering
|
| 58 |
+
export const globalOutbound = {
|
| 59 |
+
fetch: async (input: string | URL | RequestInfo, init?: RequestInit) => {
|
| 60 |
+
const url = new URL(
|
| 61 |
+
typeof input === "string"
|
| 62 |
+
? input
|
| 63 |
+
: typeof input === "object" && "url" in input
|
| 64 |
+
? input.url
|
| 65 |
+
: input.toString()
|
| 66 |
+
);
|
| 67 |
+
// Block certain domains if needed
|
| 68 |
+
if (url.hostname === "blocked.example.com") {
|
| 69 |
+
return new Response("Not allowed", { status: 403 });
|
| 70 |
+
}
|
| 71 |
+
return fetch(input, init);
|
| 72 |
+
}
|
| 73 |
+
};
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
### 3. Install Dependencies
|
| 77 |
+
|
| 78 |
+
```bash
|
| 79 |
+
npm install @cloudflare/codemode ai @ai-sdk/openai zod
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
### 4. Use Code Mode in Agent
|
| 83 |
+
|
| 84 |
+
```typescript
|
| 85 |
+
import { Agent } from "agents";
|
| 86 |
+
import { experimental_codemode as codemode } from "@cloudflare/codemode/ai";
|
| 87 |
+
import { streamText, tool, convertToModelMessages } from "ai";
|
| 88 |
+
import { openai } from "@ai-sdk/openai";
|
| 89 |
+
import { env } from "cloudflare:workers";
|
| 90 |
+
import { z } from "zod";
|
| 91 |
+
|
| 92 |
+
const tools = {
|
| 93 |
+
getWeather: tool({
|
| 94 |
+
description: "Get weather for a location",
|
| 95 |
+
parameters: z.object({ location: z.string() }),
|
| 96 |
+
execute: async ({ location }) => `Weather: ${location} 72°F`
|
| 97 |
+
}),
|
| 98 |
+
sendEmail: tool({
|
| 99 |
+
description: "Send an email",
|
| 100 |
+
parameters: z.object({ to: z.string(), subject: z.string(), body: z.string() }),
|
| 101 |
+
execute: async ({ to, subject, body }) => `Email sent to ${to}`
|
| 102 |
+
})
|
| 103 |
+
};
|
| 104 |
+
|
| 105 |
+
export class MyAgent extends Agent<Env, State> {
|
| 106 |
+
tools = {};
|
| 107 |
+
|
| 108 |
+
// Method called by codemode proxy
|
| 109 |
+
callTool(functionName: string, args: unknown[]) {
|
| 110 |
+
return this.tools[functionName]?.execute?.(args, {
|
| 111 |
+
abortSignal: new AbortController().signal,
|
| 112 |
+
toolCallId: "codemode",
|
| 113 |
+
messages: []
|
| 114 |
+
});
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
async onChatMessage() {
|
| 118 |
+
this.tools = { ...tools, ...this.mcp.getAITools() };
|
| 119 |
+
|
| 120 |
+
const { prompt, tools: wrappedTools } = await codemode({
|
| 121 |
+
prompt: "You are a helpful assistant...",
|
| 122 |
+
tools: this.tools,
|
| 123 |
+
globalOutbound: env.globalOutbound,
|
| 124 |
+
loader: env.LOADER,
|
| 125 |
+
proxy: this.ctx.exports.CodeModeProxy({
|
| 126 |
+
props: {
|
| 127 |
+
binding: "MyAgent", // Class name
|
| 128 |
+
name: this.name, // Instance name
|
| 129 |
+
callback: "callTool" // Method to call
|
| 130 |
+
}
|
| 131 |
+
})
|
| 132 |
+
});
|
| 133 |
+
|
| 134 |
+
const result = streamText({
|
| 135 |
+
system: prompt,
|
| 136 |
+
model: openai("gpt-4o"),
|
| 137 |
+
messages: await convertToModelMessages(this.state.messages),
|
| 138 |
+
tools: wrappedTools // Use wrapped tools, not original
|
| 139 |
+
});
|
| 140 |
+
|
| 141 |
+
// ... handle stream
|
| 142 |
+
}
|
| 143 |
+
}
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
## Generated Code Example
|
| 147 |
+
|
| 148 |
+
When user asks "Check the weather in NYC and email me the forecast", codemode generates:
|
| 149 |
+
|
| 150 |
+
```javascript
|
| 151 |
+
async function executeTask() {
|
| 152 |
+
const weather = await codemode.getWeather({ location: "NYC" });
|
| 153 |
+
|
| 154 |
+
await codemode.sendEmail({
|
| 155 |
+
to: "user@example.com",
|
| 156 |
+
subject: "NYC Weather Forecast",
|
| 157 |
+
body: `Current weather: ${weather}`
|
| 158 |
+
});
|
| 159 |
+
|
| 160 |
+
return { success: true, weather };
|
| 161 |
+
}
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
## MCP Server Orchestration
|
| 165 |
+
|
| 166 |
+
Code Mode excels at orchestrating multiple MCP servers:
|
| 167 |
+
|
| 168 |
+
```javascript
|
| 169 |
+
async function executeTask() {
|
| 170 |
+
// Query file system MCP
|
| 171 |
+
const files = await codemode.listFiles({ path: "/projects" });
|
| 172 |
+
|
| 173 |
+
// Query database MCP
|
| 174 |
+
const status = await codemode.queryDatabase({
|
| 175 |
+
query: "SELECT * FROM projects WHERE name = ?",
|
| 176 |
+
params: [files[0].name]
|
| 177 |
+
});
|
| 178 |
+
|
| 179 |
+
// Conditional logic based on results
|
| 180 |
+
if (status.length === 0) {
|
| 181 |
+
await codemode.createTask({
|
| 182 |
+
title: `Review: ${files[0].name}`,
|
| 183 |
+
priority: "high"
|
| 184 |
+
});
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
return { files, status };
|
| 188 |
+
}
|
| 189 |
+
```
|
| 190 |
+
|
| 191 |
+
## When to Use
|
| 192 |
+
|
| 193 |
+
| Scenario | Use Code Mode? |
|
| 194 |
+
|----------|---------------|
|
| 195 |
+
| Single tool call | No |
|
| 196 |
+
| Chained tool calls | Yes |
|
| 197 |
+
| Conditional logic across tools | Yes |
|
| 198 |
+
| MCP multi-server workflows | Yes |
|
| 199 |
+
| Token budget constrained | Yes |
|
| 200 |
+
| Simple Q&A chat | No |
|
| 201 |
+
|
| 202 |
+
## Limitations
|
| 203 |
+
|
| 204 |
+
- Experimental - API may change
|
| 205 |
+
- Requires Cloudflare Workers
|
| 206 |
+
- JavaScript execution only (Python planned)
|
| 207 |
+
- Requires additional wrangler config
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/email.md
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Email Handling
|
| 2 |
+
|
| 3 |
+
Fetch `docs/email.md` from `https://github.com/cloudflare/agents/tree/main/docs` for complete documentation.
|
| 4 |
+
|
| 5 |
+
## Overview
|
| 6 |
+
|
| 7 |
+
Agents receive and reply to emails via Cloudflare Email Routing.
|
| 8 |
+
|
| 9 |
+
## Wrangler Configuration
|
| 10 |
+
|
| 11 |
+
```jsonc
|
| 12 |
+
{
|
| 13 |
+
"durable_objects": {
|
| 14 |
+
"bindings": [{ "name": "EmailAgent", "class_name": "EmailAgent" }]
|
| 15 |
+
},
|
| 16 |
+
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["EmailAgent"] }],
|
| 17 |
+
"send_email": [
|
| 18 |
+
{ "name": "SEB", "destination_address": "reply@yourdomain.com" }
|
| 19 |
+
]
|
| 20 |
+
}
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
## Basic Email Handler
|
| 24 |
+
|
| 25 |
+
```typescript
|
| 26 |
+
import { Agent } from "agents";
|
| 27 |
+
import { type AgentEmail } from "agents/email";
|
| 28 |
+
import PostalMime from "postal-mime";
|
| 29 |
+
|
| 30 |
+
export class EmailAgent extends Agent<Env, State> {
|
| 31 |
+
async onEmail(email: AgentEmail) {
|
| 32 |
+
const raw = await email.getRaw();
|
| 33 |
+
const parsed = await PostalMime.parse(raw);
|
| 34 |
+
|
| 35 |
+
console.log("From:", email.from);
|
| 36 |
+
console.log("Subject:", parsed.subject);
|
| 37 |
+
|
| 38 |
+
await this.replyToEmail(email, {
|
| 39 |
+
fromName: "My Agent",
|
| 40 |
+
subject: `Re: ${parsed.subject}`,
|
| 41 |
+
body: "Thanks for your email!"
|
| 42 |
+
});
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
## Routing Emails
|
| 48 |
+
|
| 49 |
+
```typescript
|
| 50 |
+
import { routeAgentRequest, routeAgentEmail } from "agents";
|
| 51 |
+
import { createAddressBasedEmailResolver } from "agents/email";
|
| 52 |
+
|
| 53 |
+
export default {
|
| 54 |
+
async email(message, env) {
|
| 55 |
+
await routeAgentEmail(message, env, {
|
| 56 |
+
resolver: createAddressBasedEmailResolver("EmailAgent")
|
| 57 |
+
});
|
| 58 |
+
},
|
| 59 |
+
|
| 60 |
+
async fetch(request, env) {
|
| 61 |
+
return routeAgentRequest(request, env) ?? new Response("Not found", { status: 404 });
|
| 62 |
+
}
|
| 63 |
+
};
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
## Resolvers
|
| 67 |
+
|
| 68 |
+
### Address-Based (Inbound Mail)
|
| 69 |
+
|
| 70 |
+
Routes based on recipient address:
|
| 71 |
+
|
| 72 |
+
```typescript
|
| 73 |
+
import { createAddressBasedEmailResolver } from "agents/email";
|
| 74 |
+
|
| 75 |
+
const resolver = createAddressBasedEmailResolver("EmailAgent");
|
| 76 |
+
// support@example.com → EmailAgent, instance "support"
|
| 77 |
+
// NotificationAgent+user123@example.com → NotificationAgent, instance "user123"
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
### Secure Reply (Reply Flows)
|
| 81 |
+
|
| 82 |
+
Verifies replies are authentic using HMAC-SHA256 signatures:
|
| 83 |
+
|
| 84 |
+
```typescript
|
| 85 |
+
import { createSecureReplyEmailResolver } from "agents/email";
|
| 86 |
+
|
| 87 |
+
const resolver = createSecureReplyEmailResolver(env.EMAIL_SECRET, {
|
| 88 |
+
maxAge: 7 * 24 * 60 * 60, // 7 days (default: 30 days)
|
| 89 |
+
onInvalidSignature: (email, reason) => {
|
| 90 |
+
console.warn(`Invalid signature from ${email.from}: ${reason}`);
|
| 91 |
+
}
|
| 92 |
+
});
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
Sign outbound emails to enable secure reply routing:
|
| 96 |
+
|
| 97 |
+
```typescript
|
| 98 |
+
await this.replyToEmail(email, {
|
| 99 |
+
fromName: "My Agent",
|
| 100 |
+
body: "Thanks!",
|
| 101 |
+
secret: this.env.EMAIL_SECRET // Signs headers for secure reply routing
|
| 102 |
+
});
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
### Catch-All (Single Instance)
|
| 106 |
+
|
| 107 |
+
Routes all emails to one agent instance:
|
| 108 |
+
|
| 109 |
+
```typescript
|
| 110 |
+
import { createCatchAllEmailResolver } from "agents/email";
|
| 111 |
+
|
| 112 |
+
const resolver = createCatchAllEmailResolver("EmailAgent", "default");
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
### Combining Resolvers
|
| 116 |
+
|
| 117 |
+
```typescript
|
| 118 |
+
async email(message, env) {
|
| 119 |
+
const secureReply = createSecureReplyEmailResolver(env.EMAIL_SECRET);
|
| 120 |
+
const addressBased = createAddressBasedEmailResolver("EmailAgent");
|
| 121 |
+
|
| 122 |
+
await routeAgentEmail(message, env, {
|
| 123 |
+
resolver: async (email, env) => {
|
| 124 |
+
// Try secure reply first
|
| 125 |
+
const result = await secureReply(email, env);
|
| 126 |
+
if (result) return result;
|
| 127 |
+
// Fall back to address-based
|
| 128 |
+
return addressBased(email, env);
|
| 129 |
+
}
|
| 130 |
+
});
|
| 131 |
+
}
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
## Utilities
|
| 135 |
+
|
| 136 |
+
```typescript
|
| 137 |
+
import { isAutoReplyEmail } from "agents/email";
|
| 138 |
+
|
| 139 |
+
async onEmail(email: AgentEmail) {
|
| 140 |
+
if (isAutoReplyEmail(email.headers)) {
|
| 141 |
+
// Skip auto-replies (vacation, out-of-office, etc.)
|
| 142 |
+
return;
|
| 143 |
+
}
|
| 144 |
+
// Process email...
|
| 145 |
+
}
|
| 146 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/mcp.md
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MCP Server Integration
|
| 2 |
+
|
| 3 |
+
Fetch `docs/mcp-client.md` and `docs/mcp-servers.md` from `https://github.com/cloudflare/agents/tree/main/docs` for complete documentation.
|
| 4 |
+
|
| 5 |
+
Agents include a multi-server MCP client for connecting to external MCP servers.
|
| 6 |
+
|
| 7 |
+
## Add an MCP Server
|
| 8 |
+
|
| 9 |
+
```typescript
|
| 10 |
+
import { Agent, callable } from "agents";
|
| 11 |
+
|
| 12 |
+
export class MyAgent extends Agent<Env, State> {
|
| 13 |
+
@callable()
|
| 14 |
+
async addServer(name: string, url: string) {
|
| 15 |
+
// Options-based API (recommended)
|
| 16 |
+
const result = await this.addMcpServer(name, url, {
|
| 17 |
+
callbackHost: "https://my-worker.workers.dev",
|
| 18 |
+
transport: { headers: { Authorization: "Bearer ..." } }
|
| 19 |
+
});
|
| 20 |
+
|
| 21 |
+
if (result.state === "authenticating") {
|
| 22 |
+
// OAuth required - redirect user to result.authUrl
|
| 23 |
+
return { needsAuth: true, authUrl: result.authUrl };
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
return { ready: true, id: result.id };
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
## Use MCP Tools
|
| 32 |
+
|
| 33 |
+
```typescript
|
| 34 |
+
async onChatMessage() {
|
| 35 |
+
// Get AI-compatible tools from all connected MCP servers
|
| 36 |
+
const mcpTools = this.mcp.getAITools();
|
| 37 |
+
|
| 38 |
+
const allTools = {
|
| 39 |
+
...localTools,
|
| 40 |
+
...mcpTools
|
| 41 |
+
};
|
| 42 |
+
|
| 43 |
+
const result = streamText({
|
| 44 |
+
model: openai("gpt-4o"),
|
| 45 |
+
messages: await convertToModelMessages(this.messages),
|
| 46 |
+
tools: allTools
|
| 47 |
+
});
|
| 48 |
+
|
| 49 |
+
return result.toUIMessageStreamResponse();
|
| 50 |
+
}
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
## List MCP Resources
|
| 54 |
+
|
| 55 |
+
```typescript
|
| 56 |
+
// List all registered servers
|
| 57 |
+
const servers = this.mcp.listServers();
|
| 58 |
+
|
| 59 |
+
// List tools from all servers
|
| 60 |
+
const tools = this.mcp.listTools();
|
| 61 |
+
|
| 62 |
+
// List resources
|
| 63 |
+
const resources = this.mcp.listResources();
|
| 64 |
+
|
| 65 |
+
// List prompts
|
| 66 |
+
const prompts = this.mcp.listPrompts();
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
## Remove Server
|
| 70 |
+
|
| 71 |
+
```typescript
|
| 72 |
+
await this.removeMcpServer(serverId);
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
## Building an MCP Server
|
| 76 |
+
|
| 77 |
+
Use `McpAgent` from the SDK to create an MCP server.
|
| 78 |
+
|
| 79 |
+
**Install dependencies:**
|
| 80 |
+
```bash
|
| 81 |
+
npm install @modelcontextprotocol/sdk zod
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
**Wrangler config:**
|
| 85 |
+
```jsonc
|
| 86 |
+
{
|
| 87 |
+
"durable_objects": {
|
| 88 |
+
"bindings": [{ "name": "MyMCP", "class_name": "MyMCP" }]
|
| 89 |
+
},
|
| 90 |
+
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyMCP"] }]
|
| 91 |
+
}
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
**Server implementation:**
|
| 95 |
+
```typescript
|
| 96 |
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
| 97 |
+
import { McpAgent } from "agents/mcp";
|
| 98 |
+
import { z } from "zod";
|
| 99 |
+
|
| 100 |
+
type State = { counter: number };
|
| 101 |
+
|
| 102 |
+
export class MyMCP extends McpAgent<Env, State, {}> {
|
| 103 |
+
server = new McpServer({
|
| 104 |
+
name: "MyMCPServer",
|
| 105 |
+
version: "1.0.0"
|
| 106 |
+
});
|
| 107 |
+
|
| 108 |
+
initialState = { counter: 0 };
|
| 109 |
+
|
| 110 |
+
async init() {
|
| 111 |
+
// Register a resource
|
| 112 |
+
this.server.resource("counter", "mcp://resource/counter", (uri) => ({
|
| 113 |
+
contents: [{ text: String(this.state.counter), uri: uri.href }]
|
| 114 |
+
}));
|
| 115 |
+
|
| 116 |
+
// Register a tool
|
| 117 |
+
this.server.registerTool(
|
| 118 |
+
"increment",
|
| 119 |
+
{
|
| 120 |
+
description: "Increment the counter",
|
| 121 |
+
inputSchema: { amount: z.number().default(1) }
|
| 122 |
+
},
|
| 123 |
+
async ({ amount }) => {
|
| 124 |
+
this.setState({ counter: this.state.counter + amount });
|
| 125 |
+
return {
|
| 126 |
+
content: [{ text: `Counter: ${this.state.counter}`, type: "text" }]
|
| 127 |
+
};
|
| 128 |
+
}
|
| 129 |
+
);
|
| 130 |
+
}
|
| 131 |
+
}
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
## Serve MCP Server
|
| 135 |
+
|
| 136 |
+
```typescript
|
| 137 |
+
export default {
|
| 138 |
+
fetch(request: Request, env: Env, ctx: ExecutionContext) {
|
| 139 |
+
const url = new URL(request.url);
|
| 140 |
+
|
| 141 |
+
// SSE transport (legacy)
|
| 142 |
+
if (url.pathname.startsWith("/sse")) {
|
| 143 |
+
return MyMCP.serveSSE("/sse", { binding: "MyMCP" }).fetch(request, env, ctx);
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
// Streamable HTTP transport (recommended)
|
| 147 |
+
if (url.pathname.startsWith("/mcp")) {
|
| 148 |
+
return MyMCP.serve("/mcp", { binding: "MyMCP" }).fetch(request, env, ctx);
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
return new Response("Not found", { status: 404 });
|
| 152 |
+
}
|
| 153 |
+
};
|
| 154 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/state-scheduling.md
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# State & Scheduling
|
| 2 |
+
|
| 3 |
+
Fetch `docs/state.md` and `docs/scheduling.md` from `https://github.com/cloudflare/agents/tree/main/docs` for complete documentation.
|
| 4 |
+
|
| 5 |
+
## State Management
|
| 6 |
+
|
| 7 |
+
State persists to SQLite and broadcasts to connected clients automatically.
|
| 8 |
+
|
| 9 |
+
### Define Typed State
|
| 10 |
+
|
| 11 |
+
```typescript
|
| 12 |
+
type State = {
|
| 13 |
+
count: number;
|
| 14 |
+
items: string[];
|
| 15 |
+
};
|
| 16 |
+
|
| 17 |
+
export class MyAgent extends Agent<Env, State> {
|
| 18 |
+
initialState: State = { count: 0, items: [] };
|
| 19 |
+
}
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
### Read and Update
|
| 23 |
+
|
| 24 |
+
```typescript
|
| 25 |
+
// Read (lazy-loaded from SQLite)
|
| 26 |
+
const count = this.state.count;
|
| 27 |
+
|
| 28 |
+
// Write (sync, persists, broadcasts)
|
| 29 |
+
this.setState({ count: this.state.count + 1 });
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
### Validation Hook
|
| 33 |
+
|
| 34 |
+
`validateStateChange()` runs synchronously before state persists. Throw to reject the update.
|
| 35 |
+
|
| 36 |
+
```typescript
|
| 37 |
+
validateStateChange(nextState: State, source: Connection | "server") {
|
| 38 |
+
if (nextState.count < 0) {
|
| 39 |
+
throw new Error("Count cannot be negative");
|
| 40 |
+
}
|
| 41 |
+
}
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
### Execution Order
|
| 45 |
+
|
| 46 |
+
1. `validateStateChange(nextState, source)` - sync, gating
|
| 47 |
+
2. State persisted to SQLite
|
| 48 |
+
3. State broadcast to connected clients
|
| 49 |
+
4. `onStateUpdate(nextState, source)` - async via `ctx.waitUntil`, non-gating
|
| 50 |
+
|
| 51 |
+
### Client-Side Sync (React)
|
| 52 |
+
|
| 53 |
+
```tsx
|
| 54 |
+
import { useAgent } from "agents/react";
|
| 55 |
+
|
| 56 |
+
function App() {
|
| 57 |
+
const [state, setLocalState] = useState<State>({ count: 0 });
|
| 58 |
+
|
| 59 |
+
const agent = useAgent<State>({
|
| 60 |
+
agent: "MyAgent",
|
| 61 |
+
name: "instance-1",
|
| 62 |
+
onStateUpdate: (newState) => setLocalState(newState)
|
| 63 |
+
});
|
| 64 |
+
|
| 65 |
+
return <button onClick={() => agent.setState({ count: state.count + 1 })}>
|
| 66 |
+
Count: {state.count}
|
| 67 |
+
</button>;
|
| 68 |
+
}
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
## SQL API
|
| 72 |
+
|
| 73 |
+
Direct SQLite access for custom queries:
|
| 74 |
+
|
| 75 |
+
```typescript
|
| 76 |
+
// Create table
|
| 77 |
+
this.sql`
|
| 78 |
+
CREATE TABLE IF NOT EXISTS items (
|
| 79 |
+
id TEXT PRIMARY KEY,
|
| 80 |
+
name TEXT,
|
| 81 |
+
created_at INTEGER DEFAULT (unixepoch())
|
| 82 |
+
)
|
| 83 |
+
`;
|
| 84 |
+
|
| 85 |
+
// Insert
|
| 86 |
+
this.sql`INSERT INTO items (id, name) VALUES (${id}, ${name})`;
|
| 87 |
+
|
| 88 |
+
// Query with types
|
| 89 |
+
const items = this.sql<{ id: string; name: string }>`
|
| 90 |
+
SELECT * FROM items WHERE name LIKE ${`%${search}%`}
|
| 91 |
+
`;
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
## Scheduling
|
| 95 |
+
|
| 96 |
+
### Schedule Types
|
| 97 |
+
|
| 98 |
+
| Mode | Syntax | Use Case |
|
| 99 |
+
|------|--------|----------|
|
| 100 |
+
| Delay | `this.schedule(60, ...)` | Run in 60 seconds |
|
| 101 |
+
| Date | `this.schedule(new Date(...), ...)` | Run at specific time |
|
| 102 |
+
| Cron | `this.schedule("0 8 * * *", ...)` | Recurring schedule |
|
| 103 |
+
| Interval | `this.scheduleEvery(30, ...)` | Fixed interval (every 30s) |
|
| 104 |
+
|
| 105 |
+
### Examples
|
| 106 |
+
|
| 107 |
+
```typescript
|
| 108 |
+
// Delay (seconds)
|
| 109 |
+
await this.schedule(60, "checkStatus", { id: "abc123" });
|
| 110 |
+
|
| 111 |
+
// Specific date
|
| 112 |
+
await this.schedule(new Date("2025-12-25T00:00:00Z"), "sendGreeting", { to: "user" });
|
| 113 |
+
|
| 114 |
+
// Cron (recurring)
|
| 115 |
+
await this.schedule("0 9 * * 1-5", "weekdayReport", {});
|
| 116 |
+
|
| 117 |
+
// Fixed interval (every 30 seconds, overlap prevention built-in)
|
| 118 |
+
await this.scheduleEvery(30, "pollUpdates");
|
| 119 |
+
await this.scheduleEvery(300, "syncData", { source: "api" });
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
### Handler
|
| 123 |
+
|
| 124 |
+
```typescript
|
| 125 |
+
async sendGreeting(payload: { to: string }, schedule: Schedule) {
|
| 126 |
+
console.log(`Sending greeting to ${payload.to}`);
|
| 127 |
+
// Cron schedules auto-reschedule; one-time schedules are deleted
|
| 128 |
+
}
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
### Manage Schedules
|
| 132 |
+
|
| 133 |
+
```typescript
|
| 134 |
+
const schedules = this.getSchedules();
|
| 135 |
+
const crons = this.getSchedules({ type: "cron" });
|
| 136 |
+
await this.cancelSchedule(schedule.id);
|
| 137 |
+
```
|
| 138 |
+
|
| 139 |
+
## Lifecycle Callbacks
|
| 140 |
+
|
| 141 |
+
```typescript
|
| 142 |
+
export class MyAgent extends Agent<Env, State> {
|
| 143 |
+
async onStart() {
|
| 144 |
+
// Agent started or woke from hibernation
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
onConnect(conn: Connection, ctx: ConnectionContext) {
|
| 148 |
+
// WebSocket connected
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
onMessage(conn: Connection, message: WSMessage) {
|
| 152 |
+
// WebSocket message (non-RPC)
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
onStateUpdate(state: State, source: Connection | "server") {
|
| 156 |
+
// State changed (async, non-blocking)
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
onError(error: unknown) {
|
| 160 |
+
// Error handler
|
| 161 |
+
throw error; // Re-throw to propagate
|
| 162 |
+
}
|
| 163 |
+
}
|
| 164 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/streaming-chat.md
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Streaming Chat with AIChatAgent
|
| 2 |
+
|
| 3 |
+
Fetch `docs/resumable-streaming.md` and `docs/client-sdk.md` from `https://github.com/cloudflare/agents/tree/main/docs` for complete documentation.
|
| 4 |
+
|
| 5 |
+
`AIChatAgent` provides streaming chat with automatic message persistence and resumable streams.
|
| 6 |
+
|
| 7 |
+
## Basic Chat Agent
|
| 8 |
+
|
| 9 |
+
```typescript
|
| 10 |
+
import { AIChatAgent } from "@cloudflare/ai-chat";
|
| 11 |
+
import { streamText, convertToModelMessages } from "ai";
|
| 12 |
+
import { openai } from "@ai-sdk/openai";
|
| 13 |
+
|
| 14 |
+
export class Chat extends AIChatAgent<Env> {
|
| 15 |
+
async onChatMessage(onFinish) {
|
| 16 |
+
const result = streamText({
|
| 17 |
+
model: openai("gpt-4o"),
|
| 18 |
+
messages: await convertToModelMessages(this.messages),
|
| 19 |
+
onFinish
|
| 20 |
+
});
|
| 21 |
+
return result.toUIMessageStreamResponse();
|
| 22 |
+
}
|
| 23 |
+
}
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
## With Custom System Prompt
|
| 27 |
+
|
| 28 |
+
```typescript
|
| 29 |
+
export class Chat extends AIChatAgent<Env> {
|
| 30 |
+
async onChatMessage(onFinish) {
|
| 31 |
+
const result = streamText({
|
| 32 |
+
model: openai("gpt-4o"),
|
| 33 |
+
system: "You are a helpful assistant specializing in...",
|
| 34 |
+
messages: await convertToModelMessages(this.messages),
|
| 35 |
+
onFinish
|
| 36 |
+
});
|
| 37 |
+
return result.toUIMessageStreamResponse();
|
| 38 |
+
}
|
| 39 |
+
}
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
## With Tools
|
| 43 |
+
|
| 44 |
+
```typescript
|
| 45 |
+
import { tool } from "ai";
|
| 46 |
+
import { z } from "zod";
|
| 47 |
+
|
| 48 |
+
const tools = {
|
| 49 |
+
getWeather: tool({
|
| 50 |
+
description: "Get weather for a location",
|
| 51 |
+
parameters: z.object({ location: z.string() }),
|
| 52 |
+
execute: async ({ location }) => `Weather in ${location}: 72°F, sunny`
|
| 53 |
+
})
|
| 54 |
+
};
|
| 55 |
+
|
| 56 |
+
export class Chat extends AIChatAgent<Env> {
|
| 57 |
+
async onChatMessage(onFinish) {
|
| 58 |
+
const result = streamText({
|
| 59 |
+
model: openai("gpt-4o"),
|
| 60 |
+
messages: await convertToModelMessages(this.messages),
|
| 61 |
+
tools,
|
| 62 |
+
onFinish
|
| 63 |
+
});
|
| 64 |
+
return result.toUIMessageStreamResponse();
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
## Custom UI Message Stream
|
| 70 |
+
|
| 71 |
+
For more control, use `createUIMessageStream`:
|
| 72 |
+
|
| 73 |
+
```typescript
|
| 74 |
+
import { createUIMessageStream, createUIMessageStreamResponse } from "ai";
|
| 75 |
+
|
| 76 |
+
export class Chat extends AIChatAgent<Env> {
|
| 77 |
+
async onChatMessage(onFinish) {
|
| 78 |
+
const stream = createUIMessageStream({
|
| 79 |
+
execute: async ({ writer }) => {
|
| 80 |
+
const result = streamText({
|
| 81 |
+
model: openai("gpt-4o"),
|
| 82 |
+
messages: await convertToModelMessages(this.messages),
|
| 83 |
+
onFinish
|
| 84 |
+
});
|
| 85 |
+
writer.merge(result.toUIMessageStream());
|
| 86 |
+
}
|
| 87 |
+
});
|
| 88 |
+
return createUIMessageStreamResponse({ stream });
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
## Resumable Streaming
|
| 94 |
+
|
| 95 |
+
Streams automatically resume if client disconnects and reconnects:
|
| 96 |
+
|
| 97 |
+
1. Chunks buffered to SQLite during streaming
|
| 98 |
+
2. On reconnect, buffered chunks sent immediately
|
| 99 |
+
3. Live streaming continues from where it left off
|
| 100 |
+
|
| 101 |
+
**Enabled by default.** To disable:
|
| 102 |
+
|
| 103 |
+
```tsx
|
| 104 |
+
const { messages } = useAgentChat({ agent, resume: false });
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
## React Client
|
| 108 |
+
|
| 109 |
+
```tsx
|
| 110 |
+
import { useAgent } from "agents/react";
|
| 111 |
+
import { useAgentChat } from "@cloudflare/ai-chat/react";
|
| 112 |
+
|
| 113 |
+
function ChatUI() {
|
| 114 |
+
const agent = useAgent({
|
| 115 |
+
agent: "Chat",
|
| 116 |
+
name: "my-chat-session"
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
const {
|
| 120 |
+
messages,
|
| 121 |
+
input,
|
| 122 |
+
handleInputChange,
|
| 123 |
+
handleSubmit,
|
| 124 |
+
status
|
| 125 |
+
} = useAgentChat({ agent });
|
| 126 |
+
|
| 127 |
+
return (
|
| 128 |
+
<div>
|
| 129 |
+
{messages.map((m) => (
|
| 130 |
+
<div key={m.id}>
|
| 131 |
+
<strong>{m.role}:</strong> {m.content}
|
| 132 |
+
</div>
|
| 133 |
+
))}
|
| 134 |
+
|
| 135 |
+
<form onSubmit={handleSubmit}>
|
| 136 |
+
<input
|
| 137 |
+
value={input}
|
| 138 |
+
onChange={handleInputChange}
|
| 139 |
+
disabled={status === "streaming"}
|
| 140 |
+
/>
|
| 141 |
+
<button type="submit">Send</button>
|
| 142 |
+
</form>
|
| 143 |
+
</div>
|
| 144 |
+
);
|
| 145 |
+
}
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
## Streaming RPC Methods
|
| 149 |
+
|
| 150 |
+
For non-chat streaming, use `@callable({ streaming: true })`:
|
| 151 |
+
|
| 152 |
+
```typescript
|
| 153 |
+
import { Agent, callable, StreamingResponse } from "agents";
|
| 154 |
+
|
| 155 |
+
export class MyAgent extends Agent<Env> {
|
| 156 |
+
@callable({ streaming: true })
|
| 157 |
+
async streamData(stream: StreamingResponse, query: string) {
|
| 158 |
+
for (let i = 0; i < 10; i++) {
|
| 159 |
+
stream.send(`Result ${i}: ${query}`);
|
| 160 |
+
await sleep(100);
|
| 161 |
+
}
|
| 162 |
+
stream.close();
|
| 163 |
+
}
|
| 164 |
+
}
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
Client receives streamed messages via WebSocket RPC.
|
| 168 |
+
|
| 169 |
+
## Status Values
|
| 170 |
+
|
| 171 |
+
`useAgentChat` status:
|
| 172 |
+
|
| 173 |
+
| Status | Meaning |
|
| 174 |
+
|--------|---------|
|
| 175 |
+
| `ready` | Idle, ready for input |
|
| 176 |
+
| `streaming` | Response streaming |
|
| 177 |
+
| `submitted` | Request sent, waiting |
|
| 178 |
+
| `error` | Error occurred |
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/agents-sdk/references/workflows.md
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Workflows Integration
|
| 2 |
+
|
| 3 |
+
Fetch `docs/workflows.md` from `https://github.com/cloudflare/agents/tree/main/docs` for complete documentation.
|
| 4 |
+
|
| 5 |
+
## Overview
|
| 6 |
+
|
| 7 |
+
Agents handle real-time communication; Workflows handle durable execution. Together they enable:
|
| 8 |
+
|
| 9 |
+
- Long-running background tasks with automatic retries
|
| 10 |
+
- Human-in-the-loop approval flows
|
| 11 |
+
- Multi-step pipelines that survive failures
|
| 12 |
+
|
| 13 |
+
| Use Case | Recommendation |
|
| 14 |
+
|----------|----------------|
|
| 15 |
+
| Chat/messaging | Agent only |
|
| 16 |
+
| Quick API calls (<30s) | Agent only |
|
| 17 |
+
| Background processing (<30s) | Agent `queue()` |
|
| 18 |
+
| Long-running tasks (>30s) | Agent + Workflow |
|
| 19 |
+
| Human approval flows | Agent + Workflow |
|
| 20 |
+
|
| 21 |
+
## AgentWorkflow Base Class
|
| 22 |
+
|
| 23 |
+
```typescript
|
| 24 |
+
import { AgentWorkflow } from "agents/workflows";
|
| 25 |
+
import type { AgentWorkflowEvent, AgentWorkflowStep } from "agents/workflows";
|
| 26 |
+
|
| 27 |
+
type TaskParams = { taskId: string; data: string };
|
| 28 |
+
|
| 29 |
+
export class ProcessingWorkflow extends AgentWorkflow<MyAgent, TaskParams> {
|
| 30 |
+
async run(event: AgentWorkflowEvent<TaskParams>, step: AgentWorkflowStep) {
|
| 31 |
+
const params = event.payload;
|
| 32 |
+
|
| 33 |
+
// Durable step - retries on failure
|
| 34 |
+
const result = await step.do("process", async () => {
|
| 35 |
+
return processData(params.data);
|
| 36 |
+
});
|
| 37 |
+
|
| 38 |
+
// Non-durable: progress reporting
|
| 39 |
+
await this.reportProgress({ step: "process", percent: 0.5 });
|
| 40 |
+
|
| 41 |
+
// Non-durable: broadcast to connected clients
|
| 42 |
+
this.broadcastToClients({ type: "update", taskId: params.taskId });
|
| 43 |
+
|
| 44 |
+
// Durable: merge state via step
|
| 45 |
+
await step.mergeAgentState({ lastProcessed: params.taskId });
|
| 46 |
+
|
| 47 |
+
// Durable: report completion
|
| 48 |
+
await step.reportComplete(result);
|
| 49 |
+
|
| 50 |
+
return result;
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
## Wrangler Configuration
|
| 56 |
+
|
| 57 |
+
```jsonc
|
| 58 |
+
{
|
| 59 |
+
"workflows": [
|
| 60 |
+
{ "name": "processing-workflow", "binding": "PROCESSING_WORKFLOW", "class_name": "ProcessingWorkflow" }
|
| 61 |
+
],
|
| 62 |
+
"durable_objects": {
|
| 63 |
+
"bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
|
| 64 |
+
},
|
| 65 |
+
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]
|
| 66 |
+
}
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
## Agent Methods for Workflows
|
| 70 |
+
|
| 71 |
+
```typescript
|
| 72 |
+
// Start a workflow
|
| 73 |
+
const instance = await this.runWorkflow("ProcessingWorkflow", { taskId: "123", data: "..." });
|
| 74 |
+
|
| 75 |
+
// Send event to waiting workflow
|
| 76 |
+
await this.sendWorkflowEvent("ProcessingWorkflow", workflowId, { type: "approve" });
|
| 77 |
+
|
| 78 |
+
// Query workflows
|
| 79 |
+
const workflow = await this.getWorkflow(workflowId);
|
| 80 |
+
const workflows = await this.getWorkflows({ status: "running" });
|
| 81 |
+
|
| 82 |
+
// Control workflows
|
| 83 |
+
await this.approveWorkflow(workflowId);
|
| 84 |
+
await this.rejectWorkflow(workflowId);
|
| 85 |
+
await this.terminateWorkflow(workflowId);
|
| 86 |
+
await this.pauseWorkflow(workflowId);
|
| 87 |
+
await this.resumeWorkflow(workflowId);
|
| 88 |
+
|
| 89 |
+
// Delete workflows
|
| 90 |
+
await this.deleteWorkflow(workflowId);
|
| 91 |
+
await this.deleteWorkflows({ status: "complete", before: new Date(...) });
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
## Lifecycle Callbacks
|
| 95 |
+
|
| 96 |
+
```typescript
|
| 97 |
+
export class MyAgent extends Agent<Env, State> {
|
| 98 |
+
async onWorkflowProgress(workflowName: string, workflowId: string, progress: unknown) {
|
| 99 |
+
// Workflow reported progress via this.reportProgress()
|
| 100 |
+
this.broadcast({ type: "progress", workflowId, progress });
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
async onWorkflowComplete(workflowName: string, workflowId: string, result?: unknown) {
|
| 104 |
+
// Workflow finished successfully
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
async onWorkflowError(workflowName: string, workflowId: string, error: Error) {
|
| 108 |
+
// Workflow failed
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
async onWorkflowEvent(workflowName: string, workflowId: string, event: unknown) {
|
| 112 |
+
// Workflow received an event via sendWorkflowEvent()
|
| 113 |
+
}
|
| 114 |
+
}
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
## Human-in-the-Loop
|
| 118 |
+
|
| 119 |
+
```typescript
|
| 120 |
+
// In workflow: wait for approval
|
| 121 |
+
const approved = await step.waitForEvent<{ approved: boolean }>("approval", {
|
| 122 |
+
timeout: "7d"
|
| 123 |
+
});
|
| 124 |
+
|
| 125 |
+
if (!approved.approved) {
|
| 126 |
+
throw new Error("Rejected");
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
// From agent: approve or reject
|
| 130 |
+
await this.approveWorkflow(workflowId); // Sends { approved: true }
|
| 131 |
+
await this.rejectWorkflow(workflowId); // Sends { approved: false }
|
| 132 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/SKILL.md
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: building-ai-agent-on-cloudflare
|
| 3 |
+
description: |
|
| 4 |
+
Builds AI agents on Cloudflare using the Agents SDK with state management,
|
| 5 |
+
real-time WebSockets, scheduled tasks, tool integration, and chat capabilities.
|
| 6 |
+
Generates production-ready agent code deployed to Workers.
|
| 7 |
+
|
| 8 |
+
Use when: user wants to "build an agent", "AI agent", "chat agent", "stateful
|
| 9 |
+
agent", mentions "Agents SDK", needs "real-time AI", "WebSocket AI", or asks
|
| 10 |
+
about agent "state management", "scheduled tasks", or "tool calling".
|
| 11 |
+
Biases towards retrieval from Cloudflare docs over pre-trained knowledge.
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# Building Cloudflare Agents
|
| 15 |
+
|
| 16 |
+
Your knowledge of the Agents SDK may be outdated. **Prefer retrieval over pre-training** for any agent-building task.
|
| 17 |
+
|
| 18 |
+
## Retrieval Sources
|
| 19 |
+
|
| 20 |
+
| Source | How to retrieve | Use for |
|
| 21 |
+
|--------|----------------|---------|
|
| 22 |
+
| Agents SDK docs | `https://github.com/cloudflare/agents/tree/main/docs` | SDK API, state, routing, scheduling |
|
| 23 |
+
| Cloudflare Agents docs | `https://developers.cloudflare.com/agents/` | Platform integration, deployment |
|
| 24 |
+
| Workers docs | Search tool or `https://developers.cloudflare.com/workers/` | Runtime APIs, bindings, config |
|
| 25 |
+
|
| 26 |
+
## When to Use
|
| 27 |
+
|
| 28 |
+
- User wants to build an AI agent or chatbot
|
| 29 |
+
- User needs stateful, real-time AI interactions
|
| 30 |
+
- User asks about the Cloudflare Agents SDK
|
| 31 |
+
- User wants scheduled tasks or background AI work
|
| 32 |
+
- User needs WebSocket-based AI communication
|
| 33 |
+
|
| 34 |
+
## Prerequisites
|
| 35 |
+
|
| 36 |
+
- Cloudflare account with Workers enabled
|
| 37 |
+
- Node.js 18+ and npm/pnpm/yarn
|
| 38 |
+
- Wrangler CLI (`npm install -g wrangler`)
|
| 39 |
+
|
| 40 |
+
## Quick Start
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
npm create cloudflare@latest -- my-agent --template=cloudflare/agents-starter
|
| 44 |
+
cd my-agent
|
| 45 |
+
npm start
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
Agent runs at `http://localhost:8787`
|
| 49 |
+
|
| 50 |
+
## Core Concepts
|
| 51 |
+
|
| 52 |
+
### What is an Agent?
|
| 53 |
+
|
| 54 |
+
An Agent is a stateful, persistent AI service that:
|
| 55 |
+
- Maintains state across requests and reconnections
|
| 56 |
+
- Communicates via WebSockets or HTTP
|
| 57 |
+
- Runs on Cloudflare's edge via Durable Objects
|
| 58 |
+
- Can schedule tasks and call tools
|
| 59 |
+
- Scales horizontally (each user/session gets own instance)
|
| 60 |
+
|
| 61 |
+
### Agent Lifecycle
|
| 62 |
+
|
| 63 |
+
```
|
| 64 |
+
Client connects → Agent.onConnect() → Agent processes messages
|
| 65 |
+
→ Agent.onMessage()
|
| 66 |
+
→ Agent.setState() (persists + syncs)
|
| 67 |
+
Client disconnects → State persists → Client reconnects → State restored
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
## Basic Agent Structure
|
| 71 |
+
|
| 72 |
+
```typescript
|
| 73 |
+
import { Agent, Connection } from "agents";
|
| 74 |
+
|
| 75 |
+
interface Env {
|
| 76 |
+
AI: Ai; // Workers AI binding
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
interface State {
|
| 80 |
+
messages: Array<{ role: string; content: string }>;
|
| 81 |
+
preferences: Record<string, string>;
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
export class MyAgent extends Agent<Env, State> {
|
| 85 |
+
// Initial state for new instances
|
| 86 |
+
initialState: State = {
|
| 87 |
+
messages: [],
|
| 88 |
+
preferences: {},
|
| 89 |
+
};
|
| 90 |
+
|
| 91 |
+
// Called when agent starts or resumes
|
| 92 |
+
async onStart() {
|
| 93 |
+
console.log("Agent started with state:", this.state);
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
// Handle WebSocket connections
|
| 97 |
+
async onConnect(connection: Connection) {
|
| 98 |
+
connection.send(JSON.stringify({
|
| 99 |
+
type: "welcome",
|
| 100 |
+
history: this.state.messages,
|
| 101 |
+
}));
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
// Handle incoming messages
|
| 105 |
+
async onMessage(connection: Connection, message: string) {
|
| 106 |
+
const data = JSON.parse(message);
|
| 107 |
+
|
| 108 |
+
if (data.type === "chat") {
|
| 109 |
+
await this.handleChat(connection, data.content);
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
// Handle disconnections
|
| 114 |
+
async onClose(connection: Connection) {
|
| 115 |
+
console.log("Client disconnected");
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
// React to state changes
|
| 119 |
+
onStateUpdate(state: State, source: string) {
|
| 120 |
+
console.log("State updated by:", source);
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
private async handleChat(connection: Connection, userMessage: string) {
|
| 124 |
+
// Add user message to history
|
| 125 |
+
const messages = [
|
| 126 |
+
...this.state.messages,
|
| 127 |
+
{ role: "user", content: userMessage },
|
| 128 |
+
];
|
| 129 |
+
|
| 130 |
+
// Call AI
|
| 131 |
+
const response = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", {
|
| 132 |
+
messages,
|
| 133 |
+
});
|
| 134 |
+
|
| 135 |
+
// Update state (persists and syncs to all clients)
|
| 136 |
+
this.setState({
|
| 137 |
+
...this.state,
|
| 138 |
+
messages: [
|
| 139 |
+
...messages,
|
| 140 |
+
{ role: "assistant", content: response.response },
|
| 141 |
+
],
|
| 142 |
+
});
|
| 143 |
+
|
| 144 |
+
// Send response
|
| 145 |
+
connection.send(JSON.stringify({
|
| 146 |
+
type: "response",
|
| 147 |
+
content: response.response,
|
| 148 |
+
}));
|
| 149 |
+
}
|
| 150 |
+
}
|
| 151 |
+
```
|
| 152 |
+
|
| 153 |
+
## Entry Point Configuration
|
| 154 |
+
|
| 155 |
+
```typescript
|
| 156 |
+
// src/index.ts
|
| 157 |
+
import { routeAgentRequest } from "agents";
|
| 158 |
+
import { MyAgent } from "./agent";
|
| 159 |
+
|
| 160 |
+
export default {
|
| 161 |
+
async fetch(request: Request, env: Env) {
|
| 162 |
+
// routeAgentRequest handles routing to /agents/:class/:name
|
| 163 |
+
return (
|
| 164 |
+
(await routeAgentRequest(request, env)) ||
|
| 165 |
+
new Response("Not found", { status: 404 })
|
| 166 |
+
);
|
| 167 |
+
},
|
| 168 |
+
};
|
| 169 |
+
|
| 170 |
+
export { MyAgent };
|
| 171 |
+
```
|
| 172 |
+
|
| 173 |
+
Clients connect via: `wss://my-agent.workers.dev/agents/MyAgent/session-id`
|
| 174 |
+
|
| 175 |
+
## Wrangler Configuration
|
| 176 |
+
|
| 177 |
+
```toml
|
| 178 |
+
name = "my-agent"
|
| 179 |
+
main = "src/index.ts"
|
| 180 |
+
compatibility_date = "2024-12-01"
|
| 181 |
+
|
| 182 |
+
[ai]
|
| 183 |
+
binding = "AI"
|
| 184 |
+
|
| 185 |
+
[durable_objects]
|
| 186 |
+
bindings = [{ name = "AGENT", class_name = "MyAgent" }]
|
| 187 |
+
|
| 188 |
+
[[migrations]]
|
| 189 |
+
tag = "v1"
|
| 190 |
+
new_classes = ["MyAgent"]
|
| 191 |
+
```
|
| 192 |
+
|
| 193 |
+
## State Management
|
| 194 |
+
|
| 195 |
+
### Reading State
|
| 196 |
+
|
| 197 |
+
```typescript
|
| 198 |
+
// Current state is always available
|
| 199 |
+
const currentMessages = this.state.messages;
|
| 200 |
+
const userPrefs = this.state.preferences;
|
| 201 |
+
```
|
| 202 |
+
|
| 203 |
+
### Updating State
|
| 204 |
+
|
| 205 |
+
```typescript
|
| 206 |
+
// setState persists AND syncs to all connected clients
|
| 207 |
+
this.setState({
|
| 208 |
+
...this.state,
|
| 209 |
+
messages: [...this.state.messages, newMessage],
|
| 210 |
+
});
|
| 211 |
+
|
| 212 |
+
// Partial updates work too
|
| 213 |
+
this.setState({
|
| 214 |
+
preferences: { ...this.state.preferences, theme: "dark" },
|
| 215 |
+
});
|
| 216 |
+
```
|
| 217 |
+
|
| 218 |
+
### SQL Storage
|
| 219 |
+
|
| 220 |
+
For complex queries, use the embedded SQLite database:
|
| 221 |
+
|
| 222 |
+
```typescript
|
| 223 |
+
// Create tables
|
| 224 |
+
await this.sql`
|
| 225 |
+
CREATE TABLE IF NOT EXISTS documents (
|
| 226 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 227 |
+
title TEXT NOT NULL,
|
| 228 |
+
content TEXT,
|
| 229 |
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
| 230 |
+
)
|
| 231 |
+
`;
|
| 232 |
+
|
| 233 |
+
// Insert
|
| 234 |
+
await this.sql`
|
| 235 |
+
INSERT INTO documents (title, content)
|
| 236 |
+
VALUES (${title}, ${content})
|
| 237 |
+
`;
|
| 238 |
+
|
| 239 |
+
// Query
|
| 240 |
+
const docs = await this.sql`
|
| 241 |
+
SELECT * FROM documents WHERE title LIKE ${`%${search}%`}
|
| 242 |
+
`;
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
## Scheduled Tasks
|
| 246 |
+
|
| 247 |
+
Agents can schedule future work:
|
| 248 |
+
|
| 249 |
+
```typescript
|
| 250 |
+
async onMessage(connection: Connection, message: string) {
|
| 251 |
+
const data = JSON.parse(message);
|
| 252 |
+
|
| 253 |
+
if (data.type === "schedule_reminder") {
|
| 254 |
+
// Schedule task for 1 hour from now
|
| 255 |
+
const { id } = await this.schedule(3600, "sendReminder", {
|
| 256 |
+
message: data.reminderText,
|
| 257 |
+
userId: data.userId,
|
| 258 |
+
});
|
| 259 |
+
|
| 260 |
+
connection.send(JSON.stringify({ type: "scheduled", taskId: id }));
|
| 261 |
+
}
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
// Called when scheduled task fires
|
| 265 |
+
async sendReminder(data: { message: string; userId: string }) {
|
| 266 |
+
// Send notification, email, etc.
|
| 267 |
+
console.log(`Reminder for ${data.userId}: ${data.message}`);
|
| 268 |
+
|
| 269 |
+
// Can also update state
|
| 270 |
+
this.setState({
|
| 271 |
+
...this.state,
|
| 272 |
+
lastReminder: new Date().toISOString(),
|
| 273 |
+
});
|
| 274 |
+
}
|
| 275 |
+
```
|
| 276 |
+
|
| 277 |
+
### Schedule Options
|
| 278 |
+
|
| 279 |
+
```typescript
|
| 280 |
+
// Delay in seconds
|
| 281 |
+
await this.schedule(60, "taskMethod", { data });
|
| 282 |
+
|
| 283 |
+
// Specific date
|
| 284 |
+
await this.schedule(new Date("2025-01-01T00:00:00Z"), "taskMethod", { data });
|
| 285 |
+
|
| 286 |
+
// Cron expression (recurring)
|
| 287 |
+
await this.schedule("0 9 * * *", "dailyTask", {}); // 9 AM daily
|
| 288 |
+
await this.schedule("*/5 * * * *", "everyFiveMinutes", {}); // Every 5 min
|
| 289 |
+
|
| 290 |
+
// Manage schedules
|
| 291 |
+
const schedules = await this.getSchedules();
|
| 292 |
+
await this.cancelSchedule(taskId);
|
| 293 |
+
```
|
| 294 |
+
|
| 295 |
+
## Chat Agent (AI-Powered)
|
| 296 |
+
|
| 297 |
+
For chat-focused agents, extend `AIChatAgent`:
|
| 298 |
+
|
| 299 |
+
```typescript
|
| 300 |
+
import { AIChatAgent } from "agents/ai-chat-agent";
|
| 301 |
+
|
| 302 |
+
export class ChatBot extends AIChatAgent<Env> {
|
| 303 |
+
// Called for each user message
|
| 304 |
+
async onChatMessage(message: string) {
|
| 305 |
+
const response = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", {
|
| 306 |
+
messages: [
|
| 307 |
+
{ role: "system", content: "You are a helpful assistant." },
|
| 308 |
+
...this.messages, // Automatic history management
|
| 309 |
+
{ role: "user", content: message },
|
| 310 |
+
],
|
| 311 |
+
stream: true,
|
| 312 |
+
});
|
| 313 |
+
|
| 314 |
+
// Stream response back to client
|
| 315 |
+
return response;
|
| 316 |
+
}
|
| 317 |
+
}
|
| 318 |
+
```
|
| 319 |
+
|
| 320 |
+
Features included:
|
| 321 |
+
- Automatic message history
|
| 322 |
+
- Resumable streaming (survives disconnects)
|
| 323 |
+
- Built-in `saveMessages()` for persistence
|
| 324 |
+
|
| 325 |
+
## Client Integration
|
| 326 |
+
|
| 327 |
+
### React Hook
|
| 328 |
+
|
| 329 |
+
```tsx
|
| 330 |
+
import { useAgent } from "agents/react";
|
| 331 |
+
|
| 332 |
+
function Chat() {
|
| 333 |
+
const { state, send, connected } = useAgent({
|
| 334 |
+
agent: "my-agent",
|
| 335 |
+
name: userId, // Agent instance ID
|
| 336 |
+
});
|
| 337 |
+
|
| 338 |
+
const sendMessage = (text: string) => {
|
| 339 |
+
send(JSON.stringify({ type: "chat", content: text }));
|
| 340 |
+
};
|
| 341 |
+
|
| 342 |
+
return (
|
| 343 |
+
<div>
|
| 344 |
+
{state.messages.map((msg, i) => (
|
| 345 |
+
<div key={i}>{msg.role}: {msg.content}</div>
|
| 346 |
+
))}
|
| 347 |
+
<input onKeyDown={(e) => e.key === "Enter" && sendMessage(e.target.value)} />
|
| 348 |
+
</div>
|
| 349 |
+
);
|
| 350 |
+
}
|
| 351 |
+
```
|
| 352 |
+
|
| 353 |
+
### Vanilla JavaScript
|
| 354 |
+
|
| 355 |
+
```javascript
|
| 356 |
+
const ws = new WebSocket("wss://my-agent.workers.dev/agents/MyAgent/user123");
|
| 357 |
+
|
| 358 |
+
ws.onopen = () => {
|
| 359 |
+
console.log("Connected to agent");
|
| 360 |
+
};
|
| 361 |
+
|
| 362 |
+
ws.onmessage = (event) => {
|
| 363 |
+
const data = JSON.parse(event.data);
|
| 364 |
+
console.log("Received:", data);
|
| 365 |
+
};
|
| 366 |
+
|
| 367 |
+
ws.send(JSON.stringify({ type: "chat", content: "Hello!" }));
|
| 368 |
+
```
|
| 369 |
+
|
| 370 |
+
## Common Patterns
|
| 371 |
+
|
| 372 |
+
See [references/agent-patterns.md](references/agent-patterns.md) for:
|
| 373 |
+
- Tool calling and function execution
|
| 374 |
+
- Multi-agent orchestration
|
| 375 |
+
- RAG (Retrieval Augmented Generation)
|
| 376 |
+
- Human-in-the-loop workflows
|
| 377 |
+
|
| 378 |
+
## Deployment
|
| 379 |
+
|
| 380 |
+
```bash
|
| 381 |
+
# Deploy
|
| 382 |
+
npx wrangler deploy
|
| 383 |
+
|
| 384 |
+
# View logs
|
| 385 |
+
wrangler tail
|
| 386 |
+
|
| 387 |
+
# Test endpoint
|
| 388 |
+
curl https://my-agent.workers.dev/agents/MyAgent/test-user
|
| 389 |
+
```
|
| 390 |
+
|
| 391 |
+
## Troubleshooting
|
| 392 |
+
|
| 393 |
+
See [references/troubleshooting.md](references/troubleshooting.md) for common issues.
|
| 394 |
+
|
| 395 |
+
## References
|
| 396 |
+
|
| 397 |
+
- [references/examples.md](references/examples.md) — Official templates and production examples
|
| 398 |
+
- [references/agent-patterns.md](references/agent-patterns.md) — Advanced patterns
|
| 399 |
+
- [references/state-patterns.md](references/state-patterns.md) — State management strategies
|
| 400 |
+
- [references/troubleshooting.md](references/troubleshooting.md) — Error solutions
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/agents/openai.yaml
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
interface:
|
| 2 |
+
display_name: "Building AI Agents on Cloudflare"
|
| 3 |
+
short_description: "Build stateful AI agents on Cloudflare Workers"
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/agent-patterns.md
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Agent Patterns
|
| 2 |
+
|
| 3 |
+
Advanced patterns for building sophisticated agents.
|
| 4 |
+
|
| 5 |
+
## Tool Calling
|
| 6 |
+
|
| 7 |
+
Agents can expose tools that AI models can call:
|
| 8 |
+
|
| 9 |
+
```typescript
|
| 10 |
+
import { Agent, Connection } from "agents";
|
| 11 |
+
import { z } from "zod";
|
| 12 |
+
|
| 13 |
+
interface Tool {
|
| 14 |
+
name: string;
|
| 15 |
+
description: string;
|
| 16 |
+
parameters: z.ZodSchema;
|
| 17 |
+
handler: (params: any) => Promise<string>;
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
export class ToolAgent extends Agent<Env, State> {
|
| 21 |
+
private tools: Map<string, Tool> = new Map();
|
| 22 |
+
|
| 23 |
+
async onStart() {
|
| 24 |
+
// Register tools
|
| 25 |
+
this.registerTool({
|
| 26 |
+
name: "get_weather",
|
| 27 |
+
description: "Get current weather for a city",
|
| 28 |
+
parameters: z.object({ city: z.string() }),
|
| 29 |
+
handler: async ({ city }) => {
|
| 30 |
+
const res = await fetch(`https://api.weather.com/${city}`);
|
| 31 |
+
return JSON.stringify(await res.json());
|
| 32 |
+
},
|
| 33 |
+
});
|
| 34 |
+
|
| 35 |
+
this.registerTool({
|
| 36 |
+
name: "search_database",
|
| 37 |
+
description: "Search the document database",
|
| 38 |
+
parameters: z.object({ query: z.string(), limit: z.number().default(10) }),
|
| 39 |
+
handler: async ({ query, limit }) => {
|
| 40 |
+
const results = await this.sql`
|
| 41 |
+
SELECT * FROM documents
|
| 42 |
+
WHERE content LIKE ${`%${query}%`}
|
| 43 |
+
LIMIT ${limit}
|
| 44 |
+
`;
|
| 45 |
+
return JSON.stringify(results);
|
| 46 |
+
},
|
| 47 |
+
});
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
private registerTool(tool: Tool) {
|
| 51 |
+
this.tools.set(tool.name, tool);
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
async onMessage(connection: Connection, message: string) {
|
| 55 |
+
const data = JSON.parse(message);
|
| 56 |
+
|
| 57 |
+
if (data.type === "chat") {
|
| 58 |
+
await this.handleChatWithTools(connection, data.content);
|
| 59 |
+
}
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
private async handleChatWithTools(connection: Connection, userMessage: string) {
|
| 63 |
+
// Build tool descriptions for the AI
|
| 64 |
+
const toolDescriptions = Array.from(this.tools.values()).map((t) => ({
|
| 65 |
+
type: "function",
|
| 66 |
+
function: {
|
| 67 |
+
name: t.name,
|
| 68 |
+
description: t.description,
|
| 69 |
+
parameters: JSON.parse(JSON.stringify(t.parameters)),
|
| 70 |
+
},
|
| 71 |
+
}));
|
| 72 |
+
|
| 73 |
+
// First AI call - may request tool use
|
| 74 |
+
const response = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", {
|
| 75 |
+
messages: [
|
| 76 |
+
{ role: "system", content: "You are a helpful assistant with access to tools." },
|
| 77 |
+
...this.state.messages,
|
| 78 |
+
{ role: "user", content: userMessage },
|
| 79 |
+
],
|
| 80 |
+
tools: toolDescriptions,
|
| 81 |
+
});
|
| 82 |
+
|
| 83 |
+
// Check if AI wants to use a tool
|
| 84 |
+
if (response.tool_calls) {
|
| 85 |
+
for (const toolCall of response.tool_calls) {
|
| 86 |
+
const tool = this.tools.get(toolCall.function.name);
|
| 87 |
+
if (tool) {
|
| 88 |
+
const params = JSON.parse(toolCall.function.arguments);
|
| 89 |
+
const result = await tool.handler(params);
|
| 90 |
+
|
| 91 |
+
// Send tool result back to AI
|
| 92 |
+
const finalResponse = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", {
|
| 93 |
+
messages: [
|
| 94 |
+
...this.state.messages,
|
| 95 |
+
{ role: "user", content: userMessage },
|
| 96 |
+
{ role: "assistant", tool_calls: response.tool_calls },
|
| 97 |
+
{ role: "tool", tool_call_id: toolCall.id, content: result },
|
| 98 |
+
],
|
| 99 |
+
});
|
| 100 |
+
|
| 101 |
+
connection.send(JSON.stringify({
|
| 102 |
+
type: "response",
|
| 103 |
+
content: finalResponse.response,
|
| 104 |
+
toolUsed: toolCall.function.name,
|
| 105 |
+
}));
|
| 106 |
+
}
|
| 107 |
+
}
|
| 108 |
+
} else {
|
| 109 |
+
connection.send(JSON.stringify({
|
| 110 |
+
type: "response",
|
| 111 |
+
content: response.response,
|
| 112 |
+
}));
|
| 113 |
+
}
|
| 114 |
+
}
|
| 115 |
+
}
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
## RAG (Retrieval Augmented Generation)
|
| 119 |
+
|
| 120 |
+
Combine Vectorize with Agents for knowledge-grounded responses:
|
| 121 |
+
|
| 122 |
+
```typescript
|
| 123 |
+
interface Env {
|
| 124 |
+
AI: Ai;
|
| 125 |
+
VECTORIZE: VectorizeIndex;
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
export class RAGAgent extends Agent<Env, State> {
|
| 129 |
+
async onMessage(connection: Connection, message: string) {
|
| 130 |
+
const data = JSON.parse(message);
|
| 131 |
+
|
| 132 |
+
if (data.type === "chat") {
|
| 133 |
+
// 1. Generate embedding for query
|
| 134 |
+
const embedding = await this.env.AI.run("@cf/baai/bge-base-en-v1.5", {
|
| 135 |
+
text: data.content,
|
| 136 |
+
});
|
| 137 |
+
|
| 138 |
+
// 2. Search vector database
|
| 139 |
+
const results = await this.env.VECTORIZE.query(embedding.data[0], {
|
| 140 |
+
topK: 5,
|
| 141 |
+
returnMetadata: true,
|
| 142 |
+
});
|
| 143 |
+
|
| 144 |
+
// 3. Build context from results
|
| 145 |
+
const context = results.matches
|
| 146 |
+
.map((m) => m.metadata?.text || "")
|
| 147 |
+
.join("\n\n");
|
| 148 |
+
|
| 149 |
+
// 4. Generate response with context
|
| 150 |
+
const response = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", {
|
| 151 |
+
messages: [
|
| 152 |
+
{
|
| 153 |
+
role: "system",
|
| 154 |
+
content: `Answer based on this context:\n\n${context}\n\nIf the context doesn't contain relevant information, say so.`,
|
| 155 |
+
},
|
| 156 |
+
{ role: "user", content: data.content },
|
| 157 |
+
],
|
| 158 |
+
});
|
| 159 |
+
|
| 160 |
+
// 5. Update state and respond
|
| 161 |
+
this.setState({
|
| 162 |
+
messages: [
|
| 163 |
+
...this.state.messages,
|
| 164 |
+
{ role: "user", content: data.content },
|
| 165 |
+
{ role: "assistant", content: response.response },
|
| 166 |
+
],
|
| 167 |
+
});
|
| 168 |
+
|
| 169 |
+
connection.send(JSON.stringify({
|
| 170 |
+
type: "response",
|
| 171 |
+
content: response.response,
|
| 172 |
+
sources: results.matches.map((m) => m.metadata?.source),
|
| 173 |
+
}));
|
| 174 |
+
}
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
// Ingest documents into vector store
|
| 178 |
+
async ingestDocument(doc: { id: string; text: string; source: string }) {
|
| 179 |
+
const embedding = await this.env.AI.run("@cf/baai/bge-base-en-v1.5", {
|
| 180 |
+
text: doc.text,
|
| 181 |
+
});
|
| 182 |
+
|
| 183 |
+
await this.env.VECTORIZE.upsert([{
|
| 184 |
+
id: doc.id,
|
| 185 |
+
values: embedding.data[0],
|
| 186 |
+
metadata: { text: doc.text, source: doc.source },
|
| 187 |
+
}]);
|
| 188 |
+
}
|
| 189 |
+
}
|
| 190 |
+
```
|
| 191 |
+
|
| 192 |
+
## Multi-Agent Orchestration
|
| 193 |
+
|
| 194 |
+
Coordinate multiple specialized agents:
|
| 195 |
+
|
| 196 |
+
```typescript
|
| 197 |
+
interface Env {
|
| 198 |
+
RESEARCHER: DurableObjectNamespace;
|
| 199 |
+
WRITER: DurableObjectNamespace;
|
| 200 |
+
REVIEWER: DurableObjectNamespace;
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
export class OrchestratorAgent extends Agent<Env, State> {
|
| 204 |
+
async onMessage(connection: Connection, message: string) {
|
| 205 |
+
const data = JSON.parse(message);
|
| 206 |
+
|
| 207 |
+
if (data.type === "create_article") {
|
| 208 |
+
connection.send(JSON.stringify({ type: "status", step: "researching" }));
|
| 209 |
+
|
| 210 |
+
// Step 1: Research agent gathers information
|
| 211 |
+
const researchResult = await this.callAgent(
|
| 212 |
+
this.env.RESEARCHER,
|
| 213 |
+
data.topic,
|
| 214 |
+
{ action: "research", topic: data.topic }
|
| 215 |
+
);
|
| 216 |
+
|
| 217 |
+
connection.send(JSON.stringify({ type: "status", step: "writing" }));
|
| 218 |
+
|
| 219 |
+
// Step 2: Writer agent creates draft
|
| 220 |
+
const draftResult = await this.callAgent(
|
| 221 |
+
this.env.WRITER,
|
| 222 |
+
data.topic,
|
| 223 |
+
{ action: "write", research: researchResult, topic: data.topic }
|
| 224 |
+
);
|
| 225 |
+
|
| 226 |
+
connection.send(JSON.stringify({ type: "status", step: "reviewing" }));
|
| 227 |
+
|
| 228 |
+
// Step 3: Reviewer agent improves draft
|
| 229 |
+
const finalResult = await this.callAgent(
|
| 230 |
+
this.env.REVIEWER,
|
| 231 |
+
data.topic,
|
| 232 |
+
{ action: "review", draft: draftResult }
|
| 233 |
+
);
|
| 234 |
+
|
| 235 |
+
connection.send(JSON.stringify({
|
| 236 |
+
type: "complete",
|
| 237 |
+
article: finalResult,
|
| 238 |
+
}));
|
| 239 |
+
}
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
private async callAgent(
|
| 243 |
+
namespace: DurableObjectNamespace,
|
| 244 |
+
id: string,
|
| 245 |
+
payload: any
|
| 246 |
+
): Promise<string> {
|
| 247 |
+
const agentId = namespace.idFromName(id);
|
| 248 |
+
const agent = namespace.get(agentId);
|
| 249 |
+
|
| 250 |
+
const response = await agent.fetch("http://agent/task", {
|
| 251 |
+
method: "POST",
|
| 252 |
+
body: JSON.stringify(payload),
|
| 253 |
+
});
|
| 254 |
+
|
| 255 |
+
return response.text();
|
| 256 |
+
}
|
| 257 |
+
}
|
| 258 |
+
```
|
| 259 |
+
|
| 260 |
+
## Human-in-the-Loop
|
| 261 |
+
|
| 262 |
+
Pause agent execution for human approval:
|
| 263 |
+
|
| 264 |
+
```typescript
|
| 265 |
+
interface State {
|
| 266 |
+
pendingApprovals: Array<{
|
| 267 |
+
id: string;
|
| 268 |
+
action: string;
|
| 269 |
+
data: any;
|
| 270 |
+
requestedAt: string;
|
| 271 |
+
}>;
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
export class ApprovalAgent extends Agent<Env, State> {
|
| 275 |
+
initialState: State = { pendingApprovals: [] };
|
| 276 |
+
|
| 277 |
+
async onMessage(connection: Connection, message: string) {
|
| 278 |
+
const data = JSON.parse(message);
|
| 279 |
+
|
| 280 |
+
if (data.type === "request_action") {
|
| 281 |
+
// Action requires approval
|
| 282 |
+
if (this.requiresApproval(data.action)) {
|
| 283 |
+
const approvalId = crypto.randomUUID();
|
| 284 |
+
|
| 285 |
+
this.setState({
|
| 286 |
+
pendingApprovals: [
|
| 287 |
+
...this.state.pendingApprovals,
|
| 288 |
+
{
|
| 289 |
+
id: approvalId,
|
| 290 |
+
action: data.action,
|
| 291 |
+
data: data.payload,
|
| 292 |
+
requestedAt: new Date().toISOString(),
|
| 293 |
+
},
|
| 294 |
+
],
|
| 295 |
+
});
|
| 296 |
+
|
| 297 |
+
connection.send(JSON.stringify({
|
| 298 |
+
type: "approval_required",
|
| 299 |
+
approvalId,
|
| 300 |
+
action: data.action,
|
| 301 |
+
description: this.describeAction(data.action, data.payload),
|
| 302 |
+
}));
|
| 303 |
+
|
| 304 |
+
return;
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
// Execute immediately if no approval needed
|
| 308 |
+
await this.executeAction(connection, data.action, data.payload);
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
if (data.type === "approve") {
|
| 312 |
+
const approval = this.state.pendingApprovals.find(
|
| 313 |
+
(a) => a.id === data.approvalId
|
| 314 |
+
);
|
| 315 |
+
|
| 316 |
+
if (approval) {
|
| 317 |
+
// Remove from pending
|
| 318 |
+
this.setState({
|
| 319 |
+
pendingApprovals: this.state.pendingApprovals.filter(
|
| 320 |
+
(a) => a.id !== data.approvalId
|
| 321 |
+
),
|
| 322 |
+
});
|
| 323 |
+
|
| 324 |
+
// Execute the approved action
|
| 325 |
+
await this.executeAction(connection, approval.action, approval.data);
|
| 326 |
+
}
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
if (data.type === "reject") {
|
| 330 |
+
this.setState({
|
| 331 |
+
pendingApprovals: this.state.pendingApprovals.filter(
|
| 332 |
+
(a) => a.id !== data.approvalId
|
| 333 |
+
),
|
| 334 |
+
});
|
| 335 |
+
|
| 336 |
+
connection.send(JSON.stringify({
|
| 337 |
+
type: "action_rejected",
|
| 338 |
+
approvalId: data.approvalId,
|
| 339 |
+
}));
|
| 340 |
+
}
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
private requiresApproval(action: string): boolean {
|
| 344 |
+
const sensitiveActions = ["delete", "send_email", "make_payment", "publish"];
|
| 345 |
+
return sensitiveActions.includes(action);
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
private describeAction(action: string, data: any): string {
|
| 349 |
+
// Generate human-readable description
|
| 350 |
+
return `${action}: ${JSON.stringify(data)}`;
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
private async executeAction(connection: Connection, action: string, data: any) {
|
| 354 |
+
// Execute the action
|
| 355 |
+
const result = await this.performAction(action, data);
|
| 356 |
+
|
| 357 |
+
connection.send(JSON.stringify({
|
| 358 |
+
type: "action_completed",
|
| 359 |
+
action,
|
| 360 |
+
result,
|
| 361 |
+
}));
|
| 362 |
+
}
|
| 363 |
+
}
|
| 364 |
+
```
|
| 365 |
+
|
| 366 |
+
## Streaming Responses
|
| 367 |
+
|
| 368 |
+
Stream AI responses in real-time:
|
| 369 |
+
|
| 370 |
+
```typescript
|
| 371 |
+
export class StreamingAgent extends Agent<Env, State> {
|
| 372 |
+
async onMessage(connection: Connection, message: string) {
|
| 373 |
+
const data = JSON.parse(message);
|
| 374 |
+
|
| 375 |
+
if (data.type === "chat") {
|
| 376 |
+
// Start streaming response
|
| 377 |
+
const stream = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", {
|
| 378 |
+
messages: [
|
| 379 |
+
{ role: "system", content: "You are a helpful assistant." },
|
| 380 |
+
...this.state.messages,
|
| 381 |
+
{ role: "user", content: data.content },
|
| 382 |
+
],
|
| 383 |
+
stream: true,
|
| 384 |
+
});
|
| 385 |
+
|
| 386 |
+
let fullResponse = "";
|
| 387 |
+
|
| 388 |
+
// Stream chunks to client
|
| 389 |
+
for await (const chunk of stream) {
|
| 390 |
+
if (chunk.response) {
|
| 391 |
+
fullResponse += chunk.response;
|
| 392 |
+
connection.send(JSON.stringify({
|
| 393 |
+
type: "stream",
|
| 394 |
+
content: chunk.response,
|
| 395 |
+
done: false,
|
| 396 |
+
}));
|
| 397 |
+
}
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
// Update state with complete response
|
| 401 |
+
this.setState({
|
| 402 |
+
messages: [
|
| 403 |
+
...this.state.messages,
|
| 404 |
+
{ role: "user", content: data.content },
|
| 405 |
+
{ role: "assistant", content: fullResponse },
|
| 406 |
+
],
|
| 407 |
+
});
|
| 408 |
+
|
| 409 |
+
// Signal completion
|
| 410 |
+
connection.send(JSON.stringify({
|
| 411 |
+
type: "stream",
|
| 412 |
+
content: "",
|
| 413 |
+
done: true,
|
| 414 |
+
}));
|
| 415 |
+
}
|
| 416 |
+
}
|
| 417 |
+
}
|
| 418 |
+
```
|
| 419 |
+
|
| 420 |
+
## Connecting to MCP Servers
|
| 421 |
+
|
| 422 |
+
Agents can connect to MCP servers as clients:
|
| 423 |
+
|
| 424 |
+
```typescript
|
| 425 |
+
export class MCPClientAgent extends Agent<Env, State> {
|
| 426 |
+
async onStart() {
|
| 427 |
+
// Connect to external MCP server
|
| 428 |
+
await this.addMcpServer(
|
| 429 |
+
"github",
|
| 430 |
+
"https://github-mcp.example.com/sse",
|
| 431 |
+
{ headers: { Authorization: `Bearer ${this.env.GITHUB_TOKEN}` } }
|
| 432 |
+
);
|
| 433 |
+
|
| 434 |
+
await this.addMcpServer(
|
| 435 |
+
"database",
|
| 436 |
+
"https://db-mcp.example.com/sse"
|
| 437 |
+
);
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
async onMessage(connection: Connection, message: string) {
|
| 441 |
+
const data = JSON.parse(message);
|
| 442 |
+
|
| 443 |
+
if (data.type === "use_tool") {
|
| 444 |
+
// Call tool on connected MCP server
|
| 445 |
+
const servers = await this.getMcpServers();
|
| 446 |
+
const server = servers.find((s) => s.name === data.server);
|
| 447 |
+
|
| 448 |
+
if (server) {
|
| 449 |
+
const result = await server.callTool(data.tool, data.params);
|
| 450 |
+
connection.send(JSON.stringify({ type: "tool_result", result }));
|
| 451 |
+
}
|
| 452 |
+
}
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
async onClose() {
|
| 456 |
+
// Cleanup MCP connections
|
| 457 |
+
await this.removeMcpServer("github");
|
| 458 |
+
await this.removeMcpServer("database");
|
| 459 |
+
}
|
| 460 |
+
}
|
| 461 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/examples.md
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Project Bootstrapping
|
| 2 |
+
|
| 3 |
+
Instructions for creating new agent projects.
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## Create Command
|
| 8 |
+
|
| 9 |
+
Execute in terminal to generate a new project:
|
| 10 |
+
|
| 11 |
+
```bash
|
| 12 |
+
npm create cloudflare@latest -- my-agent \
|
| 13 |
+
--template=cloudflare/agents-starter
|
| 14 |
+
```
|
| 15 |
+
|
| 16 |
+
Or use npx directly:
|
| 17 |
+
|
| 18 |
+
```bash
|
| 19 |
+
npx create-cloudflare@latest --template cloudflare/agents-starter
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
Includes:
|
| 23 |
+
- Persistent data via `this.setState` and `this.sql`
|
| 24 |
+
- WebSocket real-time connections
|
| 25 |
+
- Workers AI bindings ready
|
| 26 |
+
- React chat interface example
|
| 27 |
+
|
| 28 |
+
---
|
| 29 |
+
|
| 30 |
+
## Project Layout
|
| 31 |
+
|
| 32 |
+
Generated structure:
|
| 33 |
+
|
| 34 |
+
```
|
| 35 |
+
my-agent/
|
| 36 |
+
├── src/
|
| 37 |
+
│ ├── app.tsx # React chat interface
|
| 38 |
+
│ ├── server.ts # Agent implementation
|
| 39 |
+
│ ├── tools.ts # Tool definitions
|
| 40 |
+
│ └── utils.ts # Helpers
|
| 41 |
+
├── wrangler.toml # Platform configuration
|
| 42 |
+
└── package.json
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
---
|
| 46 |
+
|
| 47 |
+
## Agent Variations
|
| 48 |
+
|
| 49 |
+
**Chat-focused:**
|
| 50 |
+
|
| 51 |
+
Inherit from base `Agent` class, implement `onMessage` handler:
|
| 52 |
+
- Manual conversation tracking
|
| 53 |
+
- Full control over responses
|
| 54 |
+
- Integrates with any AI provider
|
| 55 |
+
|
| 56 |
+
**Persistent data:**
|
| 57 |
+
|
| 58 |
+
Use `this.setState()` for automatic persistence:
|
| 59 |
+
- JSON-serializable data
|
| 60 |
+
- Auto-syncs to connected clients
|
| 61 |
+
- Survives instance eviction
|
| 62 |
+
|
| 63 |
+
**Per-session isolation:**
|
| 64 |
+
|
| 65 |
+
Route by unique identifier in URL path:
|
| 66 |
+
- Each identifier gets dedicated instance
|
| 67 |
+
- Isolated data storage
|
| 68 |
+
- Horizontal scaling automatic
|
| 69 |
+
|
| 70 |
+
---
|
| 71 |
+
|
| 72 |
+
## Platform Documentation
|
| 73 |
+
|
| 74 |
+
- developers.cloudflare.com/agents/
|
| 75 |
+
- developers.cloudflare.com/agents/getting-started/
|
| 76 |
+
- developers.cloudflare.com/agents/api-reference/
|
| 77 |
+
|
| 78 |
+
**Source repositories:**
|
| 79 |
+
- `github.com/cloudflare/agents-starter` (starter template)
|
| 80 |
+
- `github.com/cloudflare/agents/tree/main/examples` (reference implementations)
|
| 81 |
+
|
| 82 |
+
**Related services:**
|
| 83 |
+
|
| 84 |
+
- developers.cloudflare.com/workers-ai/ (AI models)
|
| 85 |
+
- developers.cloudflare.com/vectorize/ (vector search)
|
| 86 |
+
- developers.cloudflare.com/d1/ (SQL database)
|
| 87 |
+
|
| 88 |
+
---
|
| 89 |
+
|
| 90 |
+
## Reference Implementations
|
| 91 |
+
|
| 92 |
+
Located at `github.com/cloudflare/agents/tree/main/examples`:
|
| 93 |
+
|
| 94 |
+
| Example | Description |
|
| 95 |
+
|---------|-------------|
|
| 96 |
+
| `resumable-stream-chat` | Chat with reconnection-safe streaming |
|
| 97 |
+
| `email-agent` | Handle incoming emails via Email Routing |
|
| 98 |
+
| `mcp-client` | Connect agents to external MCP servers |
|
| 99 |
+
| `mcp-worker` | Expose agent capabilities via MCP protocol |
|
| 100 |
+
| `cross-domain` | Multi-domain authentication patterns |
|
| 101 |
+
| `tictactoe` | Multiplayer game with shared state |
|
| 102 |
+
| `a2a` | Agent-to-agent communication |
|
| 103 |
+
| `codemode` | Code transformation workflows |
|
| 104 |
+
| `playground` | Interactive testing sandbox |
|
| 105 |
+
|
| 106 |
+
Browse each folder for complete implementation code and wrangler configuration.
|
| 107 |
+
|
| 108 |
+
---
|
| 109 |
+
|
| 110 |
+
## Selection Matrix
|
| 111 |
+
|
| 112 |
+
| Goal | Approach |
|
| 113 |
+
|------|----------|
|
| 114 |
+
| Conversational bot | Agent + onMessage handler |
|
| 115 |
+
| Custom data schema | Agent + setState() |
|
| 116 |
+
| Knowledge retrieval | Agent + Vectorize |
|
| 117 |
+
| Background jobs | Agent + schedule() |
|
| 118 |
+
| External integrations | Agent + tool definitions |
|
| 119 |
+
|
| 120 |
+
---
|
| 121 |
+
|
| 122 |
+
## Commands Reference
|
| 123 |
+
|
| 124 |
+
**Local execution:**
|
| 125 |
+
|
| 126 |
+
```bash
|
| 127 |
+
cd my-agent
|
| 128 |
+
npm install
|
| 129 |
+
npm start
|
| 130 |
+
# Accessible at http://localhost:8787
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
**Production push:**
|
| 134 |
+
|
| 135 |
+
```bash
|
| 136 |
+
npx wrangler deploy
|
| 137 |
+
# Accessible at https://[name].[subdomain].workers.dev
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
**WebSocket connection:**
|
| 141 |
+
|
| 142 |
+
```javascript
|
| 143 |
+
// URL pattern: /agents/:className/:instanceName
|
| 144 |
+
const socket = new WebSocket("wss://my-agent.workers.dev/agents/MyAgent/session-123");
|
| 145 |
+
|
| 146 |
+
socket.onmessage = (e) => {
|
| 147 |
+
console.log("Received:", JSON.parse(e.data));
|
| 148 |
+
};
|
| 149 |
+
|
| 150 |
+
socket.send(JSON.stringify({ type: "chat", content: "Hello" }));
|
| 151 |
+
```
|
| 152 |
+
|
| 153 |
+
**React integration:**
|
| 154 |
+
|
| 155 |
+
```tsx
|
| 156 |
+
import { useAgent } from "agents/react";
|
| 157 |
+
|
| 158 |
+
function Chat() {
|
| 159 |
+
const { state, send } = useAgent({
|
| 160 |
+
agent: "my-agent",
|
| 161 |
+
name: "session-123",
|
| 162 |
+
});
|
| 163 |
+
|
| 164 |
+
// state auto-updates, send() dispatches messages
|
| 165 |
+
}
|
| 166 |
+
```
|
| 167 |
+
|
| 168 |
+
---
|
| 169 |
+
|
| 170 |
+
## Key Methods (from Agent class)
|
| 171 |
+
|
| 172 |
+
| Method | Purpose |
|
| 173 |
+
|--------|---------|
|
| 174 |
+
| `onStart()` | Runs on instance startup |
|
| 175 |
+
| `onConnect()` | Handles new WebSocket connections |
|
| 176 |
+
| `onMessage()` | Processes incoming messages |
|
| 177 |
+
| `onClose()` | Cleanup on disconnect |
|
| 178 |
+
| `setState()` | Persist and broadcast data |
|
| 179 |
+
| `this.sql` | Query embedded SQLite |
|
| 180 |
+
| `schedule()` | Delayed/recurring tasks |
|
| 181 |
+
| `broadcast()` | Message all connections |
|
| 182 |
+
|
| 183 |
+
---
|
| 184 |
+
|
| 185 |
+
## Help Channels
|
| 186 |
+
|
| 187 |
+
- Cloudflare Discord
|
| 188 |
+
- GitHub discussions on cloudflare/agents repository
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/state-patterns.md
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# State Management Patterns
|
| 2 |
+
|
| 3 |
+
Strategies for managing state in Cloudflare Agents.
|
| 4 |
+
|
| 5 |
+
## How State Works
|
| 6 |
+
|
| 7 |
+
State is automatically persisted to the `cf_agents_state` SQL table. The `this.state` getter lazily loads from storage, while `this.setState()` serializes and persists changes. State survives Durable Object evictions.
|
| 8 |
+
|
| 9 |
+
```typescript
|
| 10 |
+
class MyAgent extends Agent<Env, { count: number }> {
|
| 11 |
+
initialState = { count: 0 };
|
| 12 |
+
|
| 13 |
+
increment() {
|
| 14 |
+
this.setState({ count: this.state.count + 1 });
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
onStateUpdate(state: State, source: string) {
|
| 18 |
+
console.log("State updated by:", source);
|
| 19 |
+
}
|
| 20 |
+
}
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
## State vs SQL: When to Use Which
|
| 24 |
+
|
| 25 |
+
### Use `this.state` + `setState()` When:
|
| 26 |
+
|
| 27 |
+
- Data is small (< 1MB recommended)
|
| 28 |
+
- Needs real-time sync to all connected clients
|
| 29 |
+
- Simple key-value or object structure
|
| 30 |
+
- Frequently read, occasionally updated
|
| 31 |
+
|
| 32 |
+
```typescript
|
| 33 |
+
interface State {
|
| 34 |
+
currentUser: { id: string; name: string };
|
| 35 |
+
preferences: Record<string, string>;
|
| 36 |
+
recentMessages: Message[]; // Keep limited, e.g., last 50
|
| 37 |
+
isTyping: boolean;
|
| 38 |
+
}
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
### Use `this.sql` When:
|
| 42 |
+
|
| 43 |
+
- Large datasets (many records)
|
| 44 |
+
- Complex queries (JOINs, aggregations, filtering)
|
| 45 |
+
- Historical data / audit logs
|
| 46 |
+
- Data that doesn't need real-time sync
|
| 47 |
+
|
| 48 |
+
```typescript
|
| 49 |
+
// Good for SQL
|
| 50 |
+
// - Full message history
|
| 51 |
+
// - User documents
|
| 52 |
+
// - Analytics events
|
| 53 |
+
// - Search indexes
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
## Hybrid Pattern
|
| 57 |
+
|
| 58 |
+
Combine both for optimal performance:
|
| 59 |
+
|
| 60 |
+
```typescript
|
| 61 |
+
interface State {
|
| 62 |
+
recentMessages: Message[];
|
| 63 |
+
onlineUsers: string[];
|
| 64 |
+
currentDocument: Document | null;
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
export class HybridAgent extends Agent<Env, State> {
|
| 68 |
+
initialState: State = {
|
| 69 |
+
recentMessages: [],
|
| 70 |
+
onlineUsers: [],
|
| 71 |
+
currentDocument: null,
|
| 72 |
+
};
|
| 73 |
+
|
| 74 |
+
async onStart() {
|
| 75 |
+
await this.sql`
|
| 76 |
+
CREATE TABLE IF NOT EXISTS messages (
|
| 77 |
+
id TEXT PRIMARY KEY,
|
| 78 |
+
user_id TEXT NOT NULL,
|
| 79 |
+
content TEXT NOT NULL,
|
| 80 |
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
| 81 |
+
)
|
| 82 |
+
`;
|
| 83 |
+
|
| 84 |
+
const recent = await this.sql`
|
| 85 |
+
SELECT * FROM messages
|
| 86 |
+
ORDER BY created_at DESC
|
| 87 |
+
LIMIT 50
|
| 88 |
+
`;
|
| 89 |
+
|
| 90 |
+
this.setState({
|
| 91 |
+
...this.state,
|
| 92 |
+
recentMessages: recent.reverse(),
|
| 93 |
+
});
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
async addMessage(message: Message) {
|
| 97 |
+
await this.sql`
|
| 98 |
+
INSERT INTO messages (id, user_id, content)
|
| 99 |
+
VALUES (${message.id}, ${message.userId}, ${message.content})
|
| 100 |
+
`;
|
| 101 |
+
|
| 102 |
+
const recentMessages = [...this.state.recentMessages, message].slice(-50);
|
| 103 |
+
this.setState({ ...this.state, recentMessages });
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
---
|
| 109 |
+
|
| 110 |
+
## Queue System
|
| 111 |
+
|
| 112 |
+
The SDK includes a built-in queue for background task processing. Tasks are stored in SQLite and processed in FIFO order.
|
| 113 |
+
|
| 114 |
+
### Queue Methods
|
| 115 |
+
|
| 116 |
+
| Method | Purpose |
|
| 117 |
+
|--------|---------|
|
| 118 |
+
| `queue(callback, payload)` | Add task, returns task ID |
|
| 119 |
+
| `dequeue(id)` | Remove specific task |
|
| 120 |
+
| `dequeueAll()` | Clear entire queue |
|
| 121 |
+
| `dequeueAllByCallback(name)` | Remove tasks by callback name |
|
| 122 |
+
| `getQueue(id)` | Get single task |
|
| 123 |
+
| `getQueues(key, value)` | Find tasks by payload field |
|
| 124 |
+
|
| 125 |
+
### Queue Example
|
| 126 |
+
|
| 127 |
+
```typescript
|
| 128 |
+
export class TaskAgent extends Agent<Env, State> {
|
| 129 |
+
async onMessage(connection: Connection, message: string) {
|
| 130 |
+
const data = JSON.parse(message);
|
| 131 |
+
|
| 132 |
+
if (data.type === "process_later") {
|
| 133 |
+
const taskId = await this.queue("processItem", {
|
| 134 |
+
itemId: data.itemId,
|
| 135 |
+
priority: data.priority,
|
| 136 |
+
});
|
| 137 |
+
|
| 138 |
+
connection.send(JSON.stringify({ queued: true, taskId }));
|
| 139 |
+
}
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
// Callback receives payload and QueueItem metadata
|
| 143 |
+
async processItem(payload: { itemId: string }, item: QueueItem) {
|
| 144 |
+
console.log(`Processing ${payload.itemId}, queued at ${item.createdAt}`);
|
| 145 |
+
// Successfully executed tasks are auto-removed
|
| 146 |
+
}
|
| 147 |
+
}
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
+
**Queue characteristics:**
|
| 151 |
+
- Sequential processing (no parallelization)
|
| 152 |
+
- Persists across agent restarts
|
| 153 |
+
- No built-in retry mechanism
|
| 154 |
+
- Payloads must be JSON-serializable
|
| 155 |
+
|
| 156 |
+
---
|
| 157 |
+
|
| 158 |
+
## Context Management
|
| 159 |
+
|
| 160 |
+
Custom methods automatically have full agent context. Use `getCurrentAgent()` to access context from external functions.
|
| 161 |
+
|
| 162 |
+
```typescript
|
| 163 |
+
import { getCurrentAgent } from "agents";
|
| 164 |
+
|
| 165 |
+
// External utility function
|
| 166 |
+
async function logActivity(action: string) {
|
| 167 |
+
const { agent } = getCurrentAgent<MyAgent>();
|
| 168 |
+
await agent.sql`
|
| 169 |
+
INSERT INTO activity_log (action, timestamp)
|
| 170 |
+
VALUES (${action}, ${Date.now()})
|
| 171 |
+
`;
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
export class MyAgent extends Agent<Env, State> {
|
| 175 |
+
async performAction() {
|
| 176 |
+
// Context automatically available
|
| 177 |
+
await logActivity("action_performed");
|
| 178 |
+
}
|
| 179 |
+
}
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
`getCurrentAgent<T>()` returns:
|
| 183 |
+
- `agent` - The current agent instance
|
| 184 |
+
- `connection` - Connection object (if applicable)
|
| 185 |
+
- `request` - Request object (if applicable)
|
| 186 |
+
|
| 187 |
+
---
|
| 188 |
+
|
| 189 |
+
## State Synchronization
|
| 190 |
+
|
| 191 |
+
### Optimistic Updates
|
| 192 |
+
|
| 193 |
+
Update UI immediately, then persist:
|
| 194 |
+
|
| 195 |
+
```typescript
|
| 196 |
+
async onMessage(connection: Connection, message: string) {
|
| 197 |
+
const data = JSON.parse(message);
|
| 198 |
+
|
| 199 |
+
if (data.type === "update_preference") {
|
| 200 |
+
this.setState({
|
| 201 |
+
...this.state,
|
| 202 |
+
preferences: {
|
| 203 |
+
...this.state.preferences,
|
| 204 |
+
[data.key]: data.value,
|
| 205 |
+
},
|
| 206 |
+
});
|
| 207 |
+
|
| 208 |
+
await this.sql`
|
| 209 |
+
INSERT OR REPLACE INTO preferences (key, value)
|
| 210 |
+
VALUES (${data.key}, ${data.value})
|
| 211 |
+
`;
|
| 212 |
+
}
|
| 213 |
+
}
|
| 214 |
+
```
|
| 215 |
+
|
| 216 |
+
### Conflict Resolution
|
| 217 |
+
|
| 218 |
+
Handle concurrent updates with versioning:
|
| 219 |
+
|
| 220 |
+
```typescript
|
| 221 |
+
interface State {
|
| 222 |
+
document: {
|
| 223 |
+
content: string;
|
| 224 |
+
version: number;
|
| 225 |
+
lastModifiedBy: string;
|
| 226 |
+
};
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
async updateDocument(userId: string, newContent: string, expectedVersion: number) {
|
| 230 |
+
if (this.state.document.version !== expectedVersion) {
|
| 231 |
+
throw new Error("Conflict: document was modified by another user");
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
this.setState({
|
| 235 |
+
...this.state,
|
| 236 |
+
document: {
|
| 237 |
+
content: newContent,
|
| 238 |
+
version: expectedVersion + 1,
|
| 239 |
+
lastModifiedBy: userId,
|
| 240 |
+
},
|
| 241 |
+
});
|
| 242 |
+
}
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
### Per-Connection State
|
| 246 |
+
|
| 247 |
+
Track ephemeral state for each connected client:
|
| 248 |
+
|
| 249 |
+
```typescript
|
| 250 |
+
export class MultiUserAgent extends Agent<Env, State> {
|
| 251 |
+
private connectionState = new Map<string, {
|
| 252 |
+
userId: string;
|
| 253 |
+
cursor: { x: number; y: number };
|
| 254 |
+
lastActivity: number;
|
| 255 |
+
}>();
|
| 256 |
+
|
| 257 |
+
async onConnect(connection: Connection) {
|
| 258 |
+
this.connectionState.set(connection.id, {
|
| 259 |
+
userId: "",
|
| 260 |
+
cursor: { x: 0, y: 0 },
|
| 261 |
+
lastActivity: Date.now(),
|
| 262 |
+
});
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
async onClose(connection: Connection) {
|
| 266 |
+
this.connectionState.delete(connection.id);
|
| 267 |
+
}
|
| 268 |
+
}
|
| 269 |
+
```
|
| 270 |
+
|
| 271 |
+
---
|
| 272 |
+
|
| 273 |
+
## State Migration
|
| 274 |
+
|
| 275 |
+
When state schema changes:
|
| 276 |
+
|
| 277 |
+
```typescript
|
| 278 |
+
interface StateV2 {
|
| 279 |
+
messages: Array<{ id: string; content: string; timestamp: string }>;
|
| 280 |
+
version: 2;
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
export class MigratingAgent extends Agent<Env, StateV2> {
|
| 284 |
+
initialState: StateV2 = {
|
| 285 |
+
messages: [],
|
| 286 |
+
version: 2,
|
| 287 |
+
};
|
| 288 |
+
|
| 289 |
+
async onStart() {
|
| 290 |
+
const rawState = this.state as any;
|
| 291 |
+
|
| 292 |
+
if (!rawState.version || rawState.version < 2) {
|
| 293 |
+
const migratedMessages = (rawState.messages || []).map(
|
| 294 |
+
(content: string, i: number) => ({
|
| 295 |
+
id: `migrated-${i}`,
|
| 296 |
+
content,
|
| 297 |
+
timestamp: new Date().toISOString(),
|
| 298 |
+
})
|
| 299 |
+
);
|
| 300 |
+
|
| 301 |
+
this.setState({
|
| 302 |
+
messages: migratedMessages,
|
| 303 |
+
version: 2,
|
| 304 |
+
});
|
| 305 |
+
}
|
| 306 |
+
}
|
| 307 |
+
}
|
| 308 |
+
```
|
| 309 |
+
|
| 310 |
+
---
|
| 311 |
+
|
| 312 |
+
## State Size Management
|
| 313 |
+
|
| 314 |
+
Keep state lean for performance:
|
| 315 |
+
|
| 316 |
+
```typescript
|
| 317 |
+
export class LeanStateAgent extends Agent<Env, State> {
|
| 318 |
+
private readonly MAX_RECENT_MESSAGES = 100;
|
| 319 |
+
|
| 320 |
+
async addMessage(message: Message) {
|
| 321 |
+
await this.sql`INSERT INTO messages (id, content) VALUES (${message.id}, ${message.content})`;
|
| 322 |
+
|
| 323 |
+
let recentMessages = [...this.state.recentMessages, message];
|
| 324 |
+
if (recentMessages.length > this.MAX_RECENT_MESSAGES) {
|
| 325 |
+
recentMessages = recentMessages.slice(-this.MAX_RECENT_MESSAGES);
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
this.setState({
|
| 329 |
+
...this.state,
|
| 330 |
+
recentMessages,
|
| 331 |
+
stats: {
|
| 332 |
+
...this.state.stats,
|
| 333 |
+
totalMessages: this.state.stats.totalMessages + 1,
|
| 334 |
+
lastActivity: new Date().toISOString(),
|
| 335 |
+
},
|
| 336 |
+
});
|
| 337 |
+
}
|
| 338 |
+
}
|
| 339 |
+
```
|
| 340 |
+
|
| 341 |
+
---
|
| 342 |
+
|
| 343 |
+
## Debugging State
|
| 344 |
+
|
| 345 |
+
```typescript
|
| 346 |
+
async onMessage(connection: Connection, message: string) {
|
| 347 |
+
const data = JSON.parse(message);
|
| 348 |
+
|
| 349 |
+
if (data.type === "debug_state") {
|
| 350 |
+
connection.send(JSON.stringify({
|
| 351 |
+
type: "debug_response",
|
| 352 |
+
state: this.state,
|
| 353 |
+
stateSize: JSON.stringify(this.state).length,
|
| 354 |
+
sqlTables: await this.sql`
|
| 355 |
+
SELECT name FROM sqlite_master WHERE type='table'
|
| 356 |
+
`,
|
| 357 |
+
}));
|
| 358 |
+
}
|
| 359 |
+
}
|
| 360 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-ai-agent-on-cloudflare/references/troubleshooting.md
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Agent Troubleshooting
|
| 2 |
+
|
| 3 |
+
Common issues and solutions for Cloudflare Agents.
|
| 4 |
+
|
| 5 |
+
## Connection Issues
|
| 6 |
+
|
| 7 |
+
### "WebSocket connection failed"
|
| 8 |
+
|
| 9 |
+
**Symptoms:** Client cannot connect to agent.
|
| 10 |
+
|
| 11 |
+
**Causes & Solutions:**
|
| 12 |
+
|
| 13 |
+
1. **Worker not deployed**
|
| 14 |
+
```bash
|
| 15 |
+
wrangler deployments list
|
| 16 |
+
wrangler deploy # If not deployed
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
2. **Wrong URL path**
|
| 20 |
+
```javascript
|
| 21 |
+
// Ensure your routing handles the agent path
|
| 22 |
+
// Client:
|
| 23 |
+
new WebSocket("wss://my-worker.workers.dev/agent/user123");
|
| 24 |
+
|
| 25 |
+
// Worker must route to agent:
|
| 26 |
+
if (url.pathname.startsWith("/agent/")) {
|
| 27 |
+
const id = url.pathname.split("/")[2];
|
| 28 |
+
return env.AGENT.get(env.AGENT.idFromName(id)).fetch(request);
|
| 29 |
+
}
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
3. **CORS issues (browser clients)**
|
| 33 |
+
Agents handle WebSocket upgrades automatically, but ensure your entry worker doesn't block the request.
|
| 34 |
+
|
| 35 |
+
### "Connection closed unexpectedly"
|
| 36 |
+
|
| 37 |
+
1. **Agent threw an error**
|
| 38 |
+
```bash
|
| 39 |
+
wrangler tail # Check for exceptions
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
2. **Message handler crashed**
|
| 43 |
+
```typescript
|
| 44 |
+
async onMessage(connection: Connection, message: string) {
|
| 45 |
+
try {
|
| 46 |
+
// Your logic
|
| 47 |
+
} catch (error) {
|
| 48 |
+
console.error("Message handling error:", error);
|
| 49 |
+
connection.send(JSON.stringify({ type: "error", message: error.message }));
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
3. **Hibernation woke agent with stale connection**
|
| 55 |
+
Ensure you handle reconnection gracefully in client code.
|
| 56 |
+
|
| 57 |
+
## State Issues
|
| 58 |
+
|
| 59 |
+
### "State not persisting"
|
| 60 |
+
|
| 61 |
+
**Causes:**
|
| 62 |
+
|
| 63 |
+
1. **Didn't call `setState()`**
|
| 64 |
+
```typescript
|
| 65 |
+
// Wrong - direct mutation doesn't persist
|
| 66 |
+
this.state.messages.push(newMessage);
|
| 67 |
+
|
| 68 |
+
// Correct - use setState
|
| 69 |
+
this.setState({
|
| 70 |
+
...this.state,
|
| 71 |
+
messages: [...this.state.messages, newMessage],
|
| 72 |
+
});
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
2. **Agent crashed before state saved**
|
| 76 |
+
`setState()` is durable, but if agent crashes during processing before `setState()`, changes are lost.
|
| 77 |
+
|
| 78 |
+
3. **Wrong agent instance**
|
| 79 |
+
Each unique ID gets a separate agent. Ensure clients connect to the same ID.
|
| 80 |
+
|
| 81 |
+
### "State out of sync between clients"
|
| 82 |
+
|
| 83 |
+
`setState()` automatically syncs to all connected clients via `onStateUpdate()`. If sync isn't working:
|
| 84 |
+
|
| 85 |
+
1. **Check `onStateUpdate` is implemented**
|
| 86 |
+
```typescript
|
| 87 |
+
onStateUpdate(state: State, source: string) {
|
| 88 |
+
// This fires when state changes from any source
|
| 89 |
+
console.log("State updated:", state, "from:", source);
|
| 90 |
+
}
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
2. **Client not listening for state updates**
|
| 94 |
+
```typescript
|
| 95 |
+
// React hook handles this automatically
|
| 96 |
+
const { state } = useAgent({ agent: "my-agent", name: id });
|
| 97 |
+
|
| 98 |
+
// Manual WebSocket - listen for state messages
|
| 99 |
+
ws.onmessage = (event) => {
|
| 100 |
+
const data = JSON.parse(event.data);
|
| 101 |
+
if (data.type === "state_update") {
|
| 102 |
+
updateLocalState(data.state);
|
| 103 |
+
}
|
| 104 |
+
};
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
### "State too large" / Performance issues
|
| 108 |
+
|
| 109 |
+
State is serialized as JSON. Keep it small:
|
| 110 |
+
|
| 111 |
+
```typescript
|
| 112 |
+
// Bad - storing everything in state
|
| 113 |
+
interface State {
|
| 114 |
+
allMessages: Message[]; // Could be thousands
|
| 115 |
+
allDocuments: Document[];
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
// Good - state for hot data, SQL for cold
|
| 119 |
+
interface State {
|
| 120 |
+
recentMessages: Message[]; // Last 50 only
|
| 121 |
+
currentDocument: Document | null;
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
// Store full history in SQL
|
| 125 |
+
await this.sql`INSERT INTO messages ...`;
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
## SQL Issues
|
| 129 |
+
|
| 130 |
+
### "no such table"
|
| 131 |
+
|
| 132 |
+
Table not created. Create in `onStart()`:
|
| 133 |
+
|
| 134 |
+
```typescript
|
| 135 |
+
async onStart() {
|
| 136 |
+
await this.sql`
|
| 137 |
+
CREATE TABLE IF NOT EXISTS messages (
|
| 138 |
+
id TEXT PRIMARY KEY,
|
| 139 |
+
content TEXT NOT NULL,
|
| 140 |
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
| 141 |
+
)
|
| 142 |
+
`;
|
| 143 |
+
}
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
### "SQL logic error"
|
| 147 |
+
|
| 148 |
+
Check your query syntax. Use tagged templates correctly:
|
| 149 |
+
|
| 150 |
+
```typescript
|
| 151 |
+
// Wrong - string interpolation (SQL injection risk!)
|
| 152 |
+
await this.sql`SELECT * FROM users WHERE id = '${userId}'`;
|
| 153 |
+
|
| 154 |
+
// Correct - parameterized query
|
| 155 |
+
await this.sql`SELECT * FROM users WHERE id = ${userId}`;
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
### SQL query returns empty
|
| 159 |
+
|
| 160 |
+
1. **Wrong table name**
|
| 161 |
+
2. **Data in different agent instance** (each agent ID has isolated storage)
|
| 162 |
+
3. **Query conditions don't match**
|
| 163 |
+
|
| 164 |
+
Debug:
|
| 165 |
+
```typescript
|
| 166 |
+
const tables = await this.sql`
|
| 167 |
+
SELECT name FROM sqlite_master WHERE type='table'
|
| 168 |
+
`;
|
| 169 |
+
console.log("Tables:", tables);
|
| 170 |
+
|
| 171 |
+
const count = await this.sql`SELECT COUNT(*) as count FROM messages`;
|
| 172 |
+
console.log("Message count:", count);
|
| 173 |
+
```
|
| 174 |
+
|
| 175 |
+
## Scheduled Task Issues
|
| 176 |
+
|
| 177 |
+
### "Task never fires"
|
| 178 |
+
|
| 179 |
+
1. **Method name mismatch**
|
| 180 |
+
```typescript
|
| 181 |
+
// Schedule references method that must exist
|
| 182 |
+
await this.schedule(60, "sendReminder", { ... });
|
| 183 |
+
|
| 184 |
+
// Method must be defined on the class
|
| 185 |
+
async sendReminder(data: any) {
|
| 186 |
+
// This method MUST exist
|
| 187 |
+
}
|
| 188 |
+
```
|
| 189 |
+
|
| 190 |
+
2. **Cron syntax error**
|
| 191 |
+
```typescript
|
| 192 |
+
// Invalid cron
|
| 193 |
+
await this.schedule("every 5 minutes", "task", {}); // Wrong
|
| 194 |
+
|
| 195 |
+
// Valid cron
|
| 196 |
+
await this.schedule("*/5 * * * *", "task", {}); // Every 5 minutes
|
| 197 |
+
```
|
| 198 |
+
|
| 199 |
+
3. **Task was cancelled**
|
| 200 |
+
```typescript
|
| 201 |
+
const schedules = await this.getSchedules();
|
| 202 |
+
console.log("Active schedules:", schedules);
|
| 203 |
+
```
|
| 204 |
+
|
| 205 |
+
### "Task fires multiple times"
|
| 206 |
+
|
| 207 |
+
If you schedule in `onStart()` without checking:
|
| 208 |
+
|
| 209 |
+
```typescript
|
| 210 |
+
async onStart() {
|
| 211 |
+
// Bad - schedules new task every time agent wakes
|
| 212 |
+
await this.schedule("0 9 * * *", "dailyTask", {});
|
| 213 |
+
|
| 214 |
+
// Good - check first
|
| 215 |
+
const schedules = await this.getSchedules();
|
| 216 |
+
const hasDaily = schedules.some(s => s.callback === "dailyTask");
|
| 217 |
+
if (!hasDaily) {
|
| 218 |
+
await this.schedule("0 9 * * *", "dailyTask", {});
|
| 219 |
+
}
|
| 220 |
+
}
|
| 221 |
+
```
|
| 222 |
+
|
| 223 |
+
## Deployment Issues
|
| 224 |
+
|
| 225 |
+
### "Class MyAgent is not exported"
|
| 226 |
+
|
| 227 |
+
```typescript
|
| 228 |
+
// src/index.ts - Must export the class
|
| 229 |
+
export { MyAgent } from "./agent";
|
| 230 |
+
|
| 231 |
+
// Or if defined in same file
|
| 232 |
+
export class MyAgent extends Agent { ... }
|
| 233 |
+
```
|
| 234 |
+
|
| 235 |
+
### "Durable Object not found"
|
| 236 |
+
|
| 237 |
+
Check `wrangler.toml`:
|
| 238 |
+
|
| 239 |
+
```toml
|
| 240 |
+
[durable_objects]
|
| 241 |
+
bindings = [{ name = "AGENT", class_name = "MyAgent" }]
|
| 242 |
+
|
| 243 |
+
[[migrations]]
|
| 244 |
+
tag = "v1"
|
| 245 |
+
new_classes = ["MyAgent"]
|
| 246 |
+
```
|
| 247 |
+
|
| 248 |
+
### "Migration required"
|
| 249 |
+
|
| 250 |
+
When adding new Durable Object classes:
|
| 251 |
+
|
| 252 |
+
```toml
|
| 253 |
+
[[migrations]]
|
| 254 |
+
tag = "v2" # Increment from previous
|
| 255 |
+
new_classes = ["NewAgentClass"]
|
| 256 |
+
|
| 257 |
+
# Or for renames
|
| 258 |
+
# renamed_classes = [{ from = "OldName", to = "NewName" }]
|
| 259 |
+
```
|
| 260 |
+
|
| 261 |
+
## AI Integration Issues
|
| 262 |
+
|
| 263 |
+
### "AI binding not found"
|
| 264 |
+
|
| 265 |
+
Add to `wrangler.toml`:
|
| 266 |
+
|
| 267 |
+
```toml
|
| 268 |
+
[ai]
|
| 269 |
+
binding = "AI"
|
| 270 |
+
```
|
| 271 |
+
|
| 272 |
+
### "Model not found" / "Rate limited"
|
| 273 |
+
|
| 274 |
+
```typescript
|
| 275 |
+
// Check model name is correct
|
| 276 |
+
const response = await this.env.AI.run(
|
| 277 |
+
"@cf/meta/llama-3-8b-instruct", // Exact model name
|
| 278 |
+
{ messages: [...] }
|
| 279 |
+
);
|
| 280 |
+
|
| 281 |
+
// Handle rate limits
|
| 282 |
+
try {
|
| 283 |
+
const response = await this.env.AI.run(...);
|
| 284 |
+
} catch (error) {
|
| 285 |
+
if (error.message.includes("rate limit")) {
|
| 286 |
+
// Retry with backoff or use queue
|
| 287 |
+
}
|
| 288 |
+
}
|
| 289 |
+
```
|
| 290 |
+
|
| 291 |
+
### "Streaming not working"
|
| 292 |
+
|
| 293 |
+
```typescript
|
| 294 |
+
// Enable streaming
|
| 295 |
+
const stream = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", {
|
| 296 |
+
messages: [...],
|
| 297 |
+
stream: true, // Must be true
|
| 298 |
+
});
|
| 299 |
+
|
| 300 |
+
// Iterate over stream
|
| 301 |
+
for await (const chunk of stream) {
|
| 302 |
+
connection.send(JSON.stringify({ type: "chunk", content: chunk.response }));
|
| 303 |
+
}
|
| 304 |
+
```
|
| 305 |
+
|
| 306 |
+
## Debugging Tips
|
| 307 |
+
|
| 308 |
+
### Enable Verbose Logging
|
| 309 |
+
|
| 310 |
+
```typescript
|
| 311 |
+
export class MyAgent extends Agent<Env, State> {
|
| 312 |
+
async onStart() {
|
| 313 |
+
console.log("Agent starting, state:", JSON.stringify(this.state));
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
async onConnect(connection: Connection) {
|
| 317 |
+
console.log("Client connected:", connection.id);
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
async onMessage(connection: Connection, message: string) {
|
| 321 |
+
console.log("Received message:", message);
|
| 322 |
+
// ... handle
|
| 323 |
+
console.log("State after:", JSON.stringify(this.state));
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
async onClose(connection: Connection) {
|
| 327 |
+
console.log("Client disconnected:", connection.id);
|
| 328 |
+
}
|
| 329 |
+
}
|
| 330 |
+
```
|
| 331 |
+
|
| 332 |
+
View logs:
|
| 333 |
+
```bash
|
| 334 |
+
wrangler tail --format pretty
|
| 335 |
+
```
|
| 336 |
+
|
| 337 |
+
### Test Locally First
|
| 338 |
+
|
| 339 |
+
```bash
|
| 340 |
+
npm start
|
| 341 |
+
# Connect with test client or use browser console:
|
| 342 |
+
# new WebSocket("ws://localhost:8787/agent/test")
|
| 343 |
+
```
|
| 344 |
+
|
| 345 |
+
### Inspect State
|
| 346 |
+
|
| 347 |
+
Add a debug endpoint:
|
| 348 |
+
|
| 349 |
+
```typescript
|
| 350 |
+
async onRequest(request: Request) {
|
| 351 |
+
const url = new URL(request.url);
|
| 352 |
+
|
| 353 |
+
if (url.pathname === "/debug") {
|
| 354 |
+
return Response.json({
|
| 355 |
+
state: this.state,
|
| 356 |
+
schedules: await this.getSchedules(),
|
| 357 |
+
});
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
return new Response("Not found", { status: 404 });
|
| 361 |
+
}
|
| 362 |
+
```
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/SKILL.md
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: building-mcp-server-on-cloudflare
|
| 3 |
+
description: |
|
| 4 |
+
Builds remote MCP (Model Context Protocol) servers on Cloudflare Workers
|
| 5 |
+
with tools, OAuth authentication, and production deployment. Generates
|
| 6 |
+
server code, configures auth providers, and deploys to Workers.
|
| 7 |
+
|
| 8 |
+
Use when: user wants to "build MCP server", "create MCP tools", "remote
|
| 9 |
+
MCP", "deploy MCP", add "OAuth to MCP", or mentions Model Context Protocol
|
| 10 |
+
on Cloudflare. Also triggers on "MCP authentication" or "MCP deployment".
|
| 11 |
+
Biases towards retrieval from Cloudflare docs over pre-trained knowledge.
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# Building MCP Servers on Cloudflare
|
| 15 |
+
|
| 16 |
+
Your knowledge of the MCP SDK and Cloudflare Workers integration may be outdated. **Prefer retrieval over pre-training** for any MCP server task.
|
| 17 |
+
|
| 18 |
+
## Retrieval Sources
|
| 19 |
+
|
| 20 |
+
| Source | How to retrieve | Use for |
|
| 21 |
+
|--------|----------------|---------|
|
| 22 |
+
| MCP docs | `https://developers.cloudflare.com/agents/mcp/` | Server setup, auth, deployment |
|
| 23 |
+
| MCP spec | `https://modelcontextprotocol.io/` | Protocol spec, tool/resource definitions |
|
| 24 |
+
| Workers docs | Search tool or `https://developers.cloudflare.com/workers/` | Runtime APIs, bindings, config |
|
| 25 |
+
|
| 26 |
+
## When to Use
|
| 27 |
+
|
| 28 |
+
- User wants to build a remote MCP server
|
| 29 |
+
- User needs to expose tools via MCP
|
| 30 |
+
- User asks about MCP authentication or OAuth
|
| 31 |
+
- User wants to deploy MCP to Cloudflare Workers
|
| 32 |
+
|
| 33 |
+
## Prerequisites
|
| 34 |
+
|
| 35 |
+
- Cloudflare account with Workers enabled
|
| 36 |
+
- Node.js 18+ and npm/pnpm/yarn
|
| 37 |
+
- Wrangler CLI (`npm install -g wrangler`)
|
| 38 |
+
|
| 39 |
+
## Quick Start
|
| 40 |
+
|
| 41 |
+
### Option 1: Public Server (No Auth)
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
npm create cloudflare@latest -- my-mcp-server \
|
| 45 |
+
--template=cloudflare/ai/demos/remote-mcp-authless
|
| 46 |
+
cd my-mcp-server
|
| 47 |
+
npm start
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
Server runs at `http://localhost:8788/mcp`
|
| 51 |
+
|
| 52 |
+
### Option 2: Authenticated Server (OAuth)
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
npm create cloudflare@latest -- my-mcp-server \
|
| 56 |
+
--template=cloudflare/ai/demos/remote-mcp-github-oauth
|
| 57 |
+
cd my-mcp-server
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
Requires OAuth app setup. See [references/oauth-setup.md](references/oauth-setup.md).
|
| 61 |
+
|
| 62 |
+
## Core Workflow
|
| 63 |
+
|
| 64 |
+
### Step 1: Define Tools
|
| 65 |
+
|
| 66 |
+
Tools are functions MCP clients can call. Define them using `server.tool()`:
|
| 67 |
+
|
| 68 |
+
```typescript
|
| 69 |
+
import { McpAgent } from "agents/mcp";
|
| 70 |
+
import { z } from "zod";
|
| 71 |
+
|
| 72 |
+
export class MyMCP extends McpAgent {
|
| 73 |
+
server = new Server({ name: "my-mcp", version: "1.0.0" });
|
| 74 |
+
|
| 75 |
+
async init() {
|
| 76 |
+
// Simple tool with parameters
|
| 77 |
+
this.server.tool(
|
| 78 |
+
"add",
|
| 79 |
+
{ a: z.number(), b: z.number() },
|
| 80 |
+
async ({ a, b }) => ({
|
| 81 |
+
content: [{ type: "text", text: String(a + b) }],
|
| 82 |
+
})
|
| 83 |
+
);
|
| 84 |
+
|
| 85 |
+
// Tool that calls external API
|
| 86 |
+
this.server.tool(
|
| 87 |
+
"get_weather",
|
| 88 |
+
{ city: z.string() },
|
| 89 |
+
async ({ city }) => {
|
| 90 |
+
const response = await fetch(`https://api.weather.com/${city}`);
|
| 91 |
+
const data = await response.json();
|
| 92 |
+
return {
|
| 93 |
+
content: [{ type: "text", text: JSON.stringify(data) }],
|
| 94 |
+
};
|
| 95 |
+
}
|
| 96 |
+
);
|
| 97 |
+
}
|
| 98 |
+
}
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
### Step 2: Configure Entry Point
|
| 102 |
+
|
| 103 |
+
**Public server** (`src/index.ts`):
|
| 104 |
+
|
| 105 |
+
```typescript
|
| 106 |
+
import { MyMCP } from "./mcp";
|
| 107 |
+
|
| 108 |
+
export default {
|
| 109 |
+
fetch(request: Request, env: Env, ctx: ExecutionContext) {
|
| 110 |
+
const url = new URL(request.url);
|
| 111 |
+
if (url.pathname === "/mcp") {
|
| 112 |
+
return MyMCP.serveSSE("/mcp").fetch(request, env, ctx);
|
| 113 |
+
}
|
| 114 |
+
return new Response("MCP Server", { status: 200 });
|
| 115 |
+
},
|
| 116 |
+
};
|
| 117 |
+
|
| 118 |
+
export { MyMCP };
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
**Authenticated server** — See [references/oauth-setup.md](references/oauth-setup.md).
|
| 122 |
+
|
| 123 |
+
### Step 3: Test Locally
|
| 124 |
+
|
| 125 |
+
```bash
|
| 126 |
+
# Start server
|
| 127 |
+
npm start
|
| 128 |
+
|
| 129 |
+
# In another terminal, test with MCP Inspector
|
| 130 |
+
npx @modelcontextprotocol/inspector@latest
|
| 131 |
+
# Open http://localhost:5173, enter http://localhost:8788/mcp
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
### Step 4: Deploy
|
| 135 |
+
|
| 136 |
+
```bash
|
| 137 |
+
npx wrangler deploy
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
Server accessible at `https://[worker-name].[account].workers.dev/mcp`
|
| 141 |
+
|
| 142 |
+
### Step 5: Connect Clients
|
| 143 |
+
|
| 144 |
+
**Codex MCP client setup:**
|
| 145 |
+
|
| 146 |
+
```bash
|
| 147 |
+
codex mcp add my-server -- npx mcp-remote https://my-mcp.workers.dev/mcp
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
+
Restart Codex after updating the MCP configuration.
|
| 151 |
+
|
| 152 |
+
## Tool Patterns
|
| 153 |
+
|
| 154 |
+
### Return Types
|
| 155 |
+
|
| 156 |
+
```typescript
|
| 157 |
+
// Text response
|
| 158 |
+
return { content: [{ type: "text", text: "result" }] };
|
| 159 |
+
|
| 160 |
+
// Multiple content items
|
| 161 |
+
return {
|
| 162 |
+
content: [
|
| 163 |
+
{ type: "text", text: "Here's the data:" },
|
| 164 |
+
{ type: "text", text: JSON.stringify(data, null, 2) },
|
| 165 |
+
],
|
| 166 |
+
};
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
### Input Validation with Zod
|
| 170 |
+
|
| 171 |
+
```typescript
|
| 172 |
+
this.server.tool(
|
| 173 |
+
"create_user",
|
| 174 |
+
{
|
| 175 |
+
email: z.string().email(),
|
| 176 |
+
name: z.string().min(1).max(100),
|
| 177 |
+
role: z.enum(["admin", "user", "guest"]),
|
| 178 |
+
age: z.number().int().min(0).optional(),
|
| 179 |
+
},
|
| 180 |
+
async (params) => {
|
| 181 |
+
// params are fully typed and validated
|
| 182 |
+
}
|
| 183 |
+
);
|
| 184 |
+
```
|
| 185 |
+
|
| 186 |
+
### Accessing Environment/Bindings
|
| 187 |
+
|
| 188 |
+
```typescript
|
| 189 |
+
export class MyMCP extends McpAgent<Env> {
|
| 190 |
+
async init() {
|
| 191 |
+
this.server.tool("query_db", { sql: z.string() }, async ({ sql }) => {
|
| 192 |
+
// Access D1 binding
|
| 193 |
+
const result = await this.env.DB.prepare(sql).all();
|
| 194 |
+
return { content: [{ type: "text", text: JSON.stringify(result) }] };
|
| 195 |
+
});
|
| 196 |
+
}
|
| 197 |
+
}
|
| 198 |
+
```
|
| 199 |
+
|
| 200 |
+
## Authentication
|
| 201 |
+
|
| 202 |
+
For OAuth-protected servers, see [references/oauth-setup.md](references/oauth-setup.md).
|
| 203 |
+
|
| 204 |
+
Supported providers:
|
| 205 |
+
- GitHub
|
| 206 |
+
- Google
|
| 207 |
+
- Auth0
|
| 208 |
+
- Stytch
|
| 209 |
+
- WorkOS
|
| 210 |
+
- Any OAuth 2.0 compliant provider
|
| 211 |
+
|
| 212 |
+
## Wrangler Configuration
|
| 213 |
+
|
| 214 |
+
Minimal `wrangler.toml`:
|
| 215 |
+
|
| 216 |
+
```toml
|
| 217 |
+
name = "my-mcp-server"
|
| 218 |
+
main = "src/index.ts"
|
| 219 |
+
compatibility_date = "2024-12-01"
|
| 220 |
+
|
| 221 |
+
[durable_objects]
|
| 222 |
+
bindings = [{ name = "MCP", class_name = "MyMCP" }]
|
| 223 |
+
|
| 224 |
+
[[migrations]]
|
| 225 |
+
tag = "v1"
|
| 226 |
+
new_classes = ["MyMCP"]
|
| 227 |
+
```
|
| 228 |
+
|
| 229 |
+
With bindings (D1, KV, etc.):
|
| 230 |
+
|
| 231 |
+
```toml
|
| 232 |
+
[[d1_databases]]
|
| 233 |
+
binding = "DB"
|
| 234 |
+
database_name = "my-db"
|
| 235 |
+
database_id = "xxx"
|
| 236 |
+
|
| 237 |
+
[[kv_namespaces]]
|
| 238 |
+
binding = "KV"
|
| 239 |
+
id = "xxx"
|
| 240 |
+
```
|
| 241 |
+
|
| 242 |
+
## Common Issues
|
| 243 |
+
|
| 244 |
+
### "Tool not found" in Client
|
| 245 |
+
|
| 246 |
+
1. Verify tool name matches exactly (case-sensitive)
|
| 247 |
+
2. Ensure `init()` registers tools before connections
|
| 248 |
+
3. Check server logs: `wrangler tail`
|
| 249 |
+
|
| 250 |
+
### Connection Fails
|
| 251 |
+
|
| 252 |
+
1. Confirm endpoint path is `/mcp`
|
| 253 |
+
2. Check CORS if browser-based client
|
| 254 |
+
3. Verify Worker is deployed: `wrangler deployments list`
|
| 255 |
+
|
| 256 |
+
### OAuth Redirect Errors
|
| 257 |
+
|
| 258 |
+
1. Callback URL must match OAuth app config exactly
|
| 259 |
+
2. Check `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` are set
|
| 260 |
+
3. For local dev, use `http://localhost:8788/callback`
|
| 261 |
+
|
| 262 |
+
## References
|
| 263 |
+
|
| 264 |
+
- [references/examples.md](references/examples.md) — Official templates and production examples
|
| 265 |
+
- [references/oauth-setup.md](references/oauth-setup.md) — OAuth provider configuration
|
| 266 |
+
- [references/troubleshooting.md](references/troubleshooting.md) — Error codes and fixes
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/agents/openai.yaml
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
interface:
|
| 2 |
+
display_name: "Building MCP Servers on Cloudflare"
|
| 3 |
+
short_description: "Build remote MCP servers on Cloudflare Workers"
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/references/examples.md
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Project Bootstrapping
|
| 2 |
+
|
| 3 |
+
Instructions for creating new MCP server projects.
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## Create Commands
|
| 8 |
+
|
| 9 |
+
Execute in terminal to generate a new project:
|
| 10 |
+
|
| 11 |
+
**Without authentication:**
|
| 12 |
+
|
| 13 |
+
```bash
|
| 14 |
+
npm create cloudflare@latest -- my-mcp-server \
|
| 15 |
+
--template=cloudflare/ai/demos/remote-mcp-authless
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
**With GitHub login:**
|
| 19 |
+
|
| 20 |
+
```bash
|
| 21 |
+
npm create cloudflare@latest -- my-mcp-server \
|
| 22 |
+
--template=cloudflare/ai/demos/remote-mcp-github-oauth
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
**With Google login:**
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
npm create cloudflare@latest -- my-mcp-server \
|
| 29 |
+
--template=cloudflare/ai/demos/remote-mcp-google-oauth
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
---
|
| 33 |
+
|
| 34 |
+
## Additional Boilerplate Locations
|
| 35 |
+
|
| 36 |
+
**Main repository:** `github.com/cloudflare/ai` (check demos directory)
|
| 37 |
+
|
| 38 |
+
Other authentication providers:
|
| 39 |
+
- Auth0
|
| 40 |
+
- WorkOS AuthKit
|
| 41 |
+
- Logto
|
| 42 |
+
- Descope
|
| 43 |
+
- Stytch
|
| 44 |
+
|
| 45 |
+
**Cloudflare tooling:** `github.com/cloudflare/mcp-server-cloudflare`
|
| 46 |
+
|
| 47 |
+
---
|
| 48 |
+
|
| 49 |
+
## Selection Matrix
|
| 50 |
+
|
| 51 |
+
| Goal | Boilerplate |
|
| 52 |
+
|------|-------------|
|
| 53 |
+
| Testing/learning | authless |
|
| 54 |
+
| GitHub API access | github-oauth |
|
| 55 |
+
| Google API access | google-oauth |
|
| 56 |
+
| Enterprise auth | auth0 / authkit |
|
| 57 |
+
| Slack apps | slack-oauth |
|
| 58 |
+
| Zero Trust | cf-access |
|
| 59 |
+
|
| 60 |
+
---
|
| 61 |
+
|
| 62 |
+
## Platform Documentation
|
| 63 |
+
|
| 64 |
+
- developers.cloudflare.com/agents/model-context-protocol/
|
| 65 |
+
- developers.cloudflare.com/agents/guides/remote-mcp-server/
|
| 66 |
+
- developers.cloudflare.com/agents/guides/test-remote-mcp-server/
|
| 67 |
+
- developers.cloudflare.com/agents/model-context-protocol/authorization/
|
| 68 |
+
|
| 69 |
+
---
|
| 70 |
+
|
| 71 |
+
## Commands Reference
|
| 72 |
+
|
| 73 |
+
**Local execution:**
|
| 74 |
+
|
| 75 |
+
```bash
|
| 76 |
+
cd my-mcp-server
|
| 77 |
+
npm install
|
| 78 |
+
npm start
|
| 79 |
+
# Accessible at http://localhost:8788/mcp
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
**Production push:**
|
| 83 |
+
|
| 84 |
+
```bash
|
| 85 |
+
npx wrangler deploy
|
| 86 |
+
# Accessible at https://[worker-name].[subdomain].workers.dev/mcp
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
**Codex MCP client setup:**
|
| 90 |
+
|
| 91 |
+
```bash
|
| 92 |
+
codex mcp add my-server -- npx mcp-remote https://my-mcp-server.my-account.workers.dev/mcp
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
**Inspector testing:**
|
| 96 |
+
|
| 97 |
+
```bash
|
| 98 |
+
npx @modelcontextprotocol/inspector@latest
|
| 99 |
+
# Launch browser at http://localhost:5173
|
| 100 |
+
# Input your server URL: http://localhost:8788/mcp
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
---
|
| 104 |
+
|
| 105 |
+
## Help Channels
|
| 106 |
+
|
| 107 |
+
- Cloudflare Discord
|
| 108 |
+
- GitHub discussions on cloudflare/ai repository
|
data/.codex/.codex/.tmp/plugins/plugins/cloudflare/skills/building-mcp-server-on-cloudflare/references/oauth-setup.md
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Securing MCP Servers
|
| 2 |
+
|
| 3 |
+
MCP servers require authentication to ensure only trusted users can access them. The MCP specification uses OAuth 2.1 for authentication between clients and servers.
|
| 4 |
+
|
| 5 |
+
Cloudflare's `workers-oauth-provider` handles token management, client registration, and access token validation automatically.
|
| 6 |
+
|
| 7 |
+
## Basic Setup
|
| 8 |
+
|
| 9 |
+
```typescript
|
| 10 |
+
import { OAuthProvider } from "@cloudflare/workers-oauth-provider";
|
| 11 |
+
import { createMcpHandler } from "agents/mcp";
|
| 12 |
+
|
| 13 |
+
const apiHandler = {
|
| 14 |
+
async fetch(request: Request, env: unknown, ctx: ExecutionContext) {
|
| 15 |
+
return createMcpHandler(server)(request, env, ctx);
|
| 16 |
+
}
|
| 17 |
+
};
|
| 18 |
+
|
| 19 |
+
export default new OAuthProvider({
|
| 20 |
+
authorizeEndpoint: "/authorize",
|
| 21 |
+
tokenEndpoint: "/oauth/token",
|
| 22 |
+
clientRegistrationEndpoint: "/oauth/register",
|
| 23 |
+
apiRoute: "/mcp",
|
| 24 |
+
apiHandler: apiHandler,
|
| 25 |
+
defaultHandler: AuthHandler
|
| 26 |
+
});
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
## Proxy Server Pattern
|
| 30 |
+
|
| 31 |
+
MCP servers often act as OAuth clients too. Your server sits between Codex and a third-party API like GitHub. To Codex, you're a server. To GitHub, you're a client. This lets users authenticate with their GitHub credentials.
|
| 32 |
+
|
| 33 |
+
Building a secure proxy server requires careful attention to several security concerns.
|
| 34 |
+
|
| 35 |
+
---
|
| 36 |
+
|
| 37 |
+
## Security Requirements
|
| 38 |
+
|
| 39 |
+
### Redirect URI Validation
|
| 40 |
+
|
| 41 |
+
The `workers-oauth-provider` validates that `redirect_uri` in authorization requests matches registered URIs. This prevents attackers from redirecting authorization codes to malicious endpoints.
|
| 42 |
+
|
| 43 |
+
### Consent Dialog
|
| 44 |
+
|
| 45 |
+
When proxying to third-party providers, implement your own consent dialog before forwarding users upstream. This prevents the "confused deputy" problem where attackers exploit cached consent.
|
| 46 |
+
|
| 47 |
+
Your consent dialog should:
|
| 48 |
+
- Identify the requesting MCP client by name
|
| 49 |
+
- Display the specific scopes being requested
|
| 50 |
+
|
| 51 |
+
---
|
| 52 |
+
|
| 53 |
+
## CSRF Protection
|
| 54 |
+
|
| 55 |
+
Prevent attackers from tricking users into approving malicious OAuth clients. Use a random token stored in a secure cookie.
|
| 56 |
+
|
| 57 |
+
```typescript
|
| 58 |
+
// Generate token when showing consent form
|
| 59 |
+
function generateCSRFProtection(): { token: string; setCookie: string } {
|
| 60 |
+
const token = crypto.randomUUID();
|
| 61 |
+
const setCookie = `__Host-CSRF_TOKEN=${token}; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=600`;
|
| 62 |
+
return { token, setCookie };
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
// Validate token when user approves
|
| 66 |
+
function validateCSRFToken(formData: FormData, request: Request): { clearCookie: string } {
|
| 67 |
+
const tokenFromForm = formData.get("csrf_token");
|
| 68 |
+
const cookieHeader = request.headers.get("Cookie") || "";
|
| 69 |
+
const tokenFromCookie = cookieHeader
|
| 70 |
+
.split(";")
|
| 71 |
+
.find((c) => c.trim().startsWith("__Host-CSRF_TOKEN="))
|
| 72 |
+
?.split("=")[1];
|
| 73 |
+
|
| 74 |
+
if (!tokenFromForm || !tokenFromCookie || tokenFromForm !== tokenFromCookie) {
|
| 75 |
+
throw new Error("CSRF token mismatch");
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
return {
|
| 79 |
+
clearCookie: `__Host-CSRF_TOKEN=; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=0`
|
| 80 |
+
};
|
| 81 |
+
}
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
Include the token as a hidden form field:
|
| 85 |
+
|
| 86 |
+
```html
|
| 87 |
+
<input type="hidden" name="csrf_token" value="${csrfToken}" />
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
---
|
| 91 |
+
|
| 92 |
+
## Input Sanitization
|
| 93 |
+
|
| 94 |
+
Client-controlled content (names, logos, URIs) can execute malicious scripts if not sanitized. Treat all client metadata as untrusted.
|
| 95 |
+
|
| 96 |
+
```typescript
|
| 97 |
+
function sanitizeText(text: string): string {
|
| 98 |
+
return text
|
| 99 |
+
.replace(/&/g, "&")
|
| 100 |
+
.replace(/</g, "<")
|
| 101 |
+
.replace(/>/g, ">")
|
| 102 |
+
.replace(/"/g, """)
|
| 103 |
+
.replace(/'/g, "'");
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
function sanitizeUrl(url: string): string {
|
| 107 |
+
if (!url) return "";
|
| 108 |
+
try {
|
| 109 |
+
const parsed = new URL(url);
|
| 110 |
+
if (!["http:", "https:"].includes(parsed.protocol)) {
|
| 111 |
+
return "";
|
| 112 |
+
}
|
| 113 |
+
return url;
|
| 114 |
+
} catch {
|
| 115 |
+
return "";
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
```
|
| 119 |
+
|
| 120 |
+
**Required protections:**
|
| 121 |
+
- Client names/descriptions: HTML-escape before rendering
|
| 122 |
+
- Logo URLs: Allow only `http:` and `https:` schemes
|
| 123 |
+
- Client URIs: Same as logo URLs
|
| 124 |
+
- Scopes: Treat as text, HTML-escape
|
| 125 |
+
|
| 126 |
+
---
|
| 127 |
+
|
| 128 |
+
## Content Security Policy
|
| 129 |
+
|
| 130 |
+
CSP headers block dangerous content and provide defense in depth.
|
| 131 |
+
|
| 132 |
+
```typescript
|
| 133 |
+
function buildSecurityHeaders(setCookie: string, nonce?: string): HeadersInit {
|
| 134 |
+
const cspDirectives = [
|
| 135 |
+
"default-src 'none'",
|
| 136 |
+
"script-src 'self'" + (nonce ? ` 'nonce-${nonce}'` : ""),
|
| 137 |
+
"style-src 'self' 'unsafe-inline'",
|
| 138 |
+
"img-src 'self' https:",
|
| 139 |
+
"font-src 'self'",
|
| 140 |
+
"form-action 'self'",
|
| 141 |
+
"frame-ancestors 'none'",
|
| 142 |
+
"base-uri 'self'",
|
| 143 |
+
"connect-src 'self'"
|
| 144 |
+
].join("; ");
|
| 145 |
+
|
| 146 |
+
return {
|
| 147 |
+
"Content-Security-Policy": cspDirectives,
|
| 148 |
+
"X-Frame-Options": "DENY",
|
| 149 |
+
"X-Content-Type-Options": "nosniff",
|
| 150 |
+
"Content-Type": "text/html; charset=utf-8",
|
| 151 |
+
"Set-Cookie": setCookie
|
| 152 |
+
};
|
| 153 |
+
}
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
---
|
| 157 |
+
|
| 158 |
+
## State Management
|
| 159 |
+
|
| 160 |
+
Ensure the same user that hits authorize reaches the callback. Use a random state token stored in KV with short expiration.
|
| 161 |
+
|
| 162 |
+
```typescript
|
| 163 |
+
// Create state before redirecting to upstream provider
|
| 164 |
+
async function createOAuthState(
|
| 165 |
+
oauthReqInfo: AuthRequest,
|
| 166 |
+
kv: KVNamespace
|
| 167 |
+
): Promise<{ stateToken: string }> {
|
| 168 |
+
const stateToken = crypto.randomUUID();
|
| 169 |
+
await kv.put(`oauth:state:${stateToken}`, JSON.stringify(oauthReqInfo), {
|
| 170 |
+
expirationTtl: 600
|
| 171 |
+
});
|
| 172 |
+
return { stateToken };
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
// Bind state to browser session via hashed cookie
|
| 176 |
+
async function bindStateToSession(stateToken: string): Promise<{ setCookie: string }> {
|
| 177 |
+
const encoder = new TextEncoder();
|
| 178 |
+
const data = encoder.encode(stateToken);
|
| 179 |
+
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
| 180 |
+
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
| 181 |
+
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
|
| 182 |
+
|
| 183 |
+
return {
|
| 184 |
+
setCookie: `__Host-CONSENTED_STATE=${hashHex}; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=600`
|
| 185 |
+
};
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
// Validate in callback - check both KV and session cookie
|
| 189 |
+
async function validateOAuthState(
|
| 190 |
+
request: Request,
|
| 191 |
+
kv: KVNamespace
|
| 192 |
+
): Promise<{ oauthReqInfo: AuthRequest; clearCookie: string }> {
|
| 193 |
+
const url = new URL(request.url);
|
| 194 |
+
const stateFromQuery = url.searchParams.get("state");
|
| 195 |
+
|
| 196 |
+
if (!stateFromQuery) {
|
| 197 |
+
throw new Error("Missing state parameter");
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
// Check KV
|
| 201 |
+
const storedDataJson = await kv.get(`oauth:state:${stateFromQuery}`);
|
| 202 |
+
if (!storedDataJson) {
|
| 203 |
+
throw new Error("Invalid or expired state");
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
// Check session cookie matches
|
| 207 |
+
const cookieHeader = request.headers.get("Cookie") || "";
|
| 208 |
+
const consentedStateHash = cookieHeader
|
| 209 |
+
.split(";")
|
| 210 |
+
.find((c) => c.trim().startsWith("__Host-CONSENTED_STATE="))
|
| 211 |
+
?.split("=")[1];
|
| 212 |
+
|
| 213 |
+
if (!consentedStateHash) {
|
| 214 |
+
throw new Error("Missing session binding cookie");
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
// Hash state and compare
|
| 218 |
+
const encoder = new TextEncoder();
|
| 219 |
+
const hashBuffer = await crypto.subtle.digest("SHA-256", encoder.encode(stateFromQuery));
|
| 220 |
+
const stateHash = Array.from(new Uint8Array(hashBuffer))
|
| 221 |
+
.map((b) => b.toString(16).padStart(2, "0"))
|
| 222 |
+
.join("");
|
| 223 |
+
|
| 224 |
+
if (stateHash !== consentedStateHash) {
|
| 225 |
+
throw new Error("State token does not match session");
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
await kv.delete(`oauth:state:${stateFromQuery}`);
|
| 229 |
+
|
| 230 |
+
return {
|
| 231 |
+
oauthReqInfo: JSON.parse(storedDataJson),
|
| 232 |
+
clearCookie: `__Host-CONSENTED_STATE=; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=0`
|
| 233 |
+
};
|
| 234 |
+
}
|
| 235 |
+
```
|
| 236 |
+
|
| 237 |
+
---
|
| 238 |
+
|
| 239 |
+
## Approved Clients Registry
|
| 240 |
+
|
| 241 |
+
Maintain a registry of approved client IDs per user. Store in a cryptographically signed cookie with HMAC-SHA256.
|
| 242 |
+
|
| 243 |
+
```typescript
|
| 244 |
+
export async function addApprovedClient(
|
| 245 |
+
request: Request,
|
| 246 |
+
clientId: string,
|
| 247 |
+
cookieSecret: string
|
| 248 |
+
): Promise<string> {
|
| 249 |
+
const existingClients = await getApprovedClientsFromCookie(request, cookieSecret) || [];
|
| 250 |
+
const updatedClients = Array.from(new Set([...existingClients, clientId]));
|
| 251 |
+
|
| 252 |
+
const payload = JSON.stringify(updatedClients);
|
| 253 |
+
const signature = await signData(payload, cookieSecret);
|
| 254 |
+
const cookieValue = `${signature}.${btoa(payload)}`;
|
| 255 |
+
|
| 256 |
+
return `__Host-APPROVED_CLIENTS=${cookieValue}; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=2592000`;
|
| 257 |
+
}
|
| 258 |
+
```
|
| 259 |
+
|
| 260 |
+
When reading the cookie, verify the signature before trusting data. If client isn't approved, show consent dialog.
|
| 261 |
+
|
| 262 |
+
---
|
| 263 |
+
|
| 264 |
+
## Cookie Security
|
| 265 |
+
|
| 266 |
+
### Why `__Host-` prefix?
|
| 267 |
+
|
| 268 |
+
The `__Host-` prefix prevents subdomain attacks on `*.workers.dev` domains. Requirements:
|
| 269 |
+
- Must have `Secure` flag (HTTPS only)
|
| 270 |
+
- Must have `Path=/`
|
| 271 |
+
- Must not have `Domain` attribute
|
| 272 |
+
|
| 273 |
+
Without this prefix, an attacker on `evil.workers.dev` could set cookies for your `mcp-server.workers.dev` domain.
|
| 274 |
+
|
| 275 |
+
### Multiple OAuth Providers
|
| 276 |
+
|
| 277 |
+
If running multiple OAuth flows on the same domain, namespace your cookies:
|
| 278 |
+
- `__Host-CSRF_TOKEN_GITHUB` vs `__Host-CSRF_TOKEN_GOOGLE`
|
| 279 |
+
- `__Host-APPROVED_CLIENTS_GITHUB` vs `__Host-APPROVED_CLIENTS_GOOGLE`
|
| 280 |
+
|
| 281 |
+
---
|
| 282 |
+
|
| 283 |
+
## Inline JavaScript
|
| 284 |
+
|
| 285 |
+
If your consent dialog needs inline JavaScript, use data attributes and nonces:
|
| 286 |
+
|
| 287 |
+
```typescript
|
| 288 |
+
const nonce = crypto.randomUUID();
|
| 289 |
+
|
| 290 |
+
const html = `
|
| 291 |
+
<script nonce="${nonce}" data-redirect-url="${sanitizeUrl(redirectUrl)}">
|
| 292 |
+
setTimeout(() => {
|
| 293 |
+
const script = document.querySelector('script[data-redirect-url]');
|
| 294 |
+
window.location.href = script.dataset.redirectUrl;
|
| 295 |
+
}, 2000);
|
| 296 |
+
</script>
|
| 297 |
+
`;
|
| 298 |
+
|
| 299 |
+
return new Response(html, {
|
| 300 |
+
headers: buildSecurityHeaders(setCookie, nonce)
|
| 301 |
+
});
|
| 302 |
+
```
|
| 303 |
+
|
| 304 |
+
Data attributes store user-controlled data separately from executable code. Nonces with CSP allow your specific script while blocking injected scripts.
|
| 305 |
+
|
| 306 |
+
---
|
| 307 |
+
|
| 308 |
+
## Provider-Specific Setup
|
| 309 |
+
|
| 310 |
+
### GitHub
|
| 311 |
+
|
| 312 |
+
1. Create OAuth App at github.com/settings/developers
|
| 313 |
+
2. Set callback URL: `https://[worker].workers.dev/callback`
|
| 314 |
+
3. Store secrets:
|
| 315 |
+
```bash
|
| 316 |
+
wrangler secret put GITHUB_CLIENT_ID
|
| 317 |
+
wrangler secret put GITHUB_CLIENT_SECRET
|
| 318 |
+
```
|
| 319 |
+
|
| 320 |
+
### Google
|
| 321 |
+
|
| 322 |
+
1. Create OAuth Client at console.cloud.google.com/apis/credentials
|
| 323 |
+
2. Set authorized redirect URI
|
| 324 |
+
3. Scopes: `openid email profile`
|
| 325 |
+
|
| 326 |
+
### Auth0
|
| 327 |
+
|
| 328 |
+
1. Create Regular Web Application in Auth0 Dashboard
|
| 329 |
+
2. Set allowed callback URLs
|
| 330 |
+
3. Endpoints: `https://${AUTH0_DOMAIN}/authorize`, `/oauth/token`, `/userinfo`
|
| 331 |
+
|
| 332 |
+
---
|
| 333 |
+
|
| 334 |
+
## References
|
| 335 |
+
|
| 336 |
+
- [MCP Authorization Spec](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization)
|
| 337 |
+
- [MCP Security Best Practices](https://modelcontextprotocol.io/specification/draft/basic/security_best_practices)
|
| 338 |
+
- [RFC 9700 - OAuth Security](https://www.rfc-editor.org/rfc/rfc9700)
|